Skip to content

Commit 30b375d

Browse files
authored
Merge pull request #413 from AdExNetwork/issue-382-campaign-insert-events
Issue 382 campaign insert events
2 parents c6c63bc + 598ab52 commit 30b375d

34 files changed

+1156
-364
lines changed

Cargo.lock

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

adapter/src/dummy.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,8 @@ impl Adapter for DummyAdapter {
9292
Ok(())
9393
}
9494

95-
fn whoami(&self) -> &ValidatorId {
96-
&self.identity
95+
fn whoami(&self) -> ValidatorId {
96+
self.identity
9797
}
9898

9999
fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError> {

adapter/src/ethereum.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -149,8 +149,8 @@ impl Adapter for EthereumAdapter {
149149
Ok(())
150150
}
151151

152-
fn whoami(&self) -> &ValidatorId {
153-
&self.address
152+
fn whoami(&self) -> ValidatorId {
153+
self.address
154154
}
155155

156156
fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError> {
@@ -263,7 +263,7 @@ impl Adapter for EthereumAdapter {
263263
address: self.whoami().to_checksum(),
264264
};
265265

266-
ewt_sign(&wallet, &self.keystore_pwd, &payload)
266+
ewt_sign(wallet, &self.keystore_pwd, &payload)
267267
.map_err(|err| AdapterError::Adapter(Error::SignMessage(err).into()))
268268
}
269269

@@ -401,8 +401,8 @@ fn hash_message(message: &[u8]) -> [u8; 32] {
401401
let message_length = message.len();
402402

403403
let mut result = Keccak::new_keccak256();
404-
result.update(&format!("{}{}", eth, message_length).as_bytes());
405-
result.update(&message);
404+
result.update(format!("{}{}", eth, message_length).as_bytes());
405+
result.update(message);
406406

407407
let mut res: [u8; 32] = [0; 32];
408408
result.finalize(&mut res);
@@ -453,7 +453,7 @@ pub fn ewt_sign(
453453
base64::URL_SAFE_NO_PAD,
454454
);
455455
let message = Message::from(hash_message(
456-
&format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
456+
format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
457457
));
458458
let signature: Signature = signer
459459
.sign(password, &message)
@@ -475,7 +475,7 @@ pub fn ewt_verify(
475475
token: &str,
476476
) -> Result<VerifyPayload, EwtVerifyError> {
477477
let message = Message::from(hash_message(
478-
&format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
478+
format!("{}.{}", header_encoded, payload_encoded).as_bytes(),
479479
));
480480

481481
let decoded_signature = base64::decode_config(&token, base64::URL_SAFE_NO_PAD)

adview-manager/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ fn get_unit_html(
172172
) -> String {
173173
let image_url = normalize_url(&ad_unit.media_url);
174174

175-
let element_html = if is_video(&ad_unit) {
175+
let element_html = if is_video(ad_unit) {
176176
video_html(on_load, size, &image_url, &ad_unit.media_mime)
177177
} else {
178178
image_html(on_load, size, &image_url)

primitives/src/adapter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ pub trait Adapter: Send + Sync + fmt::Debug + Clone {
8181
fn unlock(&mut self) -> AdapterResult<(), Self::AdapterError>;
8282

8383
/// Get Adapter whoami
84-
fn whoami(&self) -> &ValidatorId;
84+
fn whoami(&self) -> ValidatorId;
8585

8686
/// Signs the provided state_root
8787
fn sign(&self, state_root: &str) -> AdapterResult<String, Self::AdapterError>;

primitives/src/big_num.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ impl TryFrom<&str> for BigNum {
243243
type Error = super::DomainError;
244244

245245
fn try_from(num: &str) -> Result<Self, Self::Error> {
246-
let big_uint = BigUint::from_str(&num)
246+
let big_uint = BigUint::from_str(num)
247247
.map_err(|err| super::DomainError::InvalidArgument(err.to_string()))?;
248248

249249
Ok(Self(big_uint))

primitives/src/campaign.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ impl Campaign {
195195
}
196196
}
197197

198-
/// Matches the Channel.leader to the Campaign.spec.leader
198+
/// Matches the Channel.leader to the Campaign.validators.leader
199199
/// If they match it returns `Some`, otherwise, it returns `None`
200200
pub fn leader(&self) -> Option<&'_ ValidatorDesc> {
201201
self.validators.find(&self.channel.leader)
@@ -318,7 +318,7 @@ pub mod validators {
318318
}
319319

320320
pub fn iter(&self) -> Iter<'_> {
321-
Iter::new(&self)
321+
Iter::new(self)
322322
}
323323
}
324324

primitives/src/campaign_validator.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ impl Validator for Campaign {
5757
return Err(Validation::UnlistedValidator.into());
5858
}
5959

60-
if !creator_listed(&self, &config.creators_whitelist) {
60+
if !creator_listed(self, &config.creators_whitelist) {
6161
return Err(Validation::UnlistedCreator.into());
6262
}
6363

primitives/src/channel.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -238,9 +238,9 @@ impl SpecValidators {
238238

239239
pub fn find(&self, validator_id: &ValidatorId) -> Option<SpecValidator<'_>> {
240240
if &self.leader().id == validator_id {
241-
Some(SpecValidator::Leader(&self.leader()))
241+
Some(SpecValidator::Leader(self.leader()))
242242
} else if &self.follower().id == validator_id {
243-
Some(SpecValidator::Follower(&self.follower()))
243+
Some(SpecValidator::Follower(self.follower()))
244244
} else {
245245
None
246246
}
@@ -257,7 +257,7 @@ impl SpecValidators {
257257
}
258258

259259
pub fn iter(&self) -> Iter<'_> {
260-
Iter::new(&self)
260+
Iter::new(self)
261261
}
262262
}
263263

primitives/src/sentry.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ pub mod campaign_create {
380380
}
381381
}
382382
}
383-
383+
384384
// All editable fields stored in one place, used for checking when a budget is changed
385385
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
386386
pub struct ModifyCampaign {

primitives/src/sentry/accounting.rs

Lines changed: 11 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -69,20 +69,26 @@ impl<S: BalancesState> Balances<S> {
6969
Ok(())
7070
}
7171

72-
/// Adds the spender to the Balances with `UnifiedNum::from(0)` if he does not exist
72+
/// Adds the spender to the Balances with `0` if he does not exist
7373
pub fn add_spender(&mut self, spender: Address) {
74-
self.spenders.entry(spender).or_insert(UnifiedNum::from(0));
74+
self.spenders
75+
.entry(spender)
76+
.or_insert_with(UnifiedNum::default);
7577
}
7678

77-
/// Adds the earner to the Balances with `UnifiedNum::from(0)` if he does not exist
79+
/// Adds the earner to the Balances with `0` if he does not exist
7880
pub fn add_earner(&mut self, earner: Address) {
79-
self.earners.entry(earner).or_insert(UnifiedNum::from(0));
81+
self.earners
82+
.entry(earner)
83+
.or_insert_with(UnifiedNum::default);
8084
}
8185
}
8286

83-
#[derive(Debug)]
87+
#[derive(Debug, Error)]
8488
pub enum OverflowError {
89+
#[error("Spender {0} amount overflowed")]
8590
Spender(Address),
91+
#[error("Earner {0} amount overflowed")]
8692
Earner(Address),
8793
}
8894

@@ -206,30 +212,3 @@ mod de {
206212
}
207213
}
208214
}
209-
210-
#[cfg(feature = "postgres")]
211-
mod postgres {
212-
use super::*;
213-
use postgres_types::Json;
214-
use tokio_postgres::Row;
215-
216-
impl TryFrom<&Row> for Accounting<CheckedState> {
217-
type Error = Error;
218-
219-
fn try_from(row: &Row) -> Result<Self, Self::Error> {
220-
let balances = Balances::<UncheckedState> {
221-
earners: row.get::<_, Json<_>>("earners").0,
222-
spenders: row.get::<_, Json<_>>("spenders").0,
223-
state: PhantomData::default(),
224-
}
225-
.check()?;
226-
227-
Ok(Self {
228-
channel: row.get("channel"),
229-
balances,
230-
updated: row.get("updated"),
231-
created: row.get("created"),
232-
})
233-
}
234-
}
235-
}

primitives/src/util/tests/time.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,5 @@ pub fn past_datetime(from: Option<&DateTime<Utc>>) -> DateTime<Utc> {
2525

2626
let from = from.unwrap_or(&default_from);
2727

28-
datetime_between(&from, Some(&to))
28+
datetime_between(from, Some(&to))
2929
}

primitives/src/validator.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ impl ValidatorId {
2727
}
2828

2929
pub fn inner(&self) -> &[u8; 20] {
30-
&self.0.as_bytes()
30+
self.0.as_bytes()
3131
}
3232
}
3333

@@ -53,7 +53,7 @@ impl From<&[u8; 20]> for ValidatorId {
5353

5454
impl AsRef<[u8]> for ValidatorId {
5555
fn as_ref(&self) -> &[u8] {
56-
&self.0.as_ref()
56+
self.0.as_ref()
5757
}
5858
}
5959

sentry/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ redis = { version = "0.20", features = ["aio", "tokio-comp"] }
2929
deadpool = "0.8.0"
3030
deadpool-postgres = "0.9.0"
3131
tokio-postgres = { version = "0.7.0", features = ["with-chrono-0_4", "with-serde_json-1"] }
32+
postgres-types = { version = "0.2.1", features = ["derive", "with-chrono-0_4", "with-serde_json-1"] }
3233

3334
# Migrations
3435
migrant_lib = { version = "^0.32", features = ["d-postgres"] }

sentry/migrations/20190806011140_initial-tables/up.sql

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,16 @@ CREATE AGGREGATE jsonb_object_agg (jsonb) (
6868
INITCOND = '{}'
6969
);
7070

71+
CREATE TYPE AccountingSide AS ENUM ('Earner', 'Spender');
72+
7173
CREATE TABLE accounting (
7274
channel_id varchar(66) NOT NULL,
73-
channel jsonb NOT NULL,
74-
earners jsonb DEFAULT '{}' NULL,
75-
spenders jsonb DEFAULT '{}' NULL,
75+
side AccountingSide NOT NULL,
76+
"address" varchar(42) NOT NULL,
77+
amount bigint NOT NULL,
7678
updated timestamp(2) with time zone DEFAULT NULL NULL,
7779
created timestamp(2) with time zone NOT NULL,
7880

79-
PRIMARY KEY (channel_id)
80-
)
81+
-- Do not rename the Primary key constraint (`accounting_pkey`)!
82+
PRIMARY KEY (channel_id, side, "address")
83+
);

sentry/src/access.rs

Lines changed: 11 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use thiserror::Error;
1313

1414
#[derive(Debug, PartialEq, Eq, Error)]
1515
pub enum Error {
16-
#[error("channel is expired")]
16+
#[error("Campaign is expired")]
1717
CampaignIsExpired,
1818
#[error("event submission restricted")]
1919
ForbiddenReferrer,
@@ -37,17 +37,10 @@ pub async fn check_access(
3737
if current_time > campaign.active.to {
3838
return Err(Error::CampaignIsExpired);
3939
}
40-
41-
let (is_creator, auth_uid) = match auth {
42-
Some(auth) => (
43-
auth.uid.to_address() == campaign.creator,
44-
auth.uid.to_string(),
45-
),
46-
None => (false, Default::default()),
47-
};
40+
let auth_uid = auth.map(|auth| auth.uid.to_string()).unwrap_or_default();
4841

4942
// Rules for events
50-
if forbidden_country(&session) || forbidden_referrer(&session) {
43+
if forbidden_country(session) || forbidden_referrer(session) {
5144
return Err(Error::ForbiddenReferrer);
5245
}
5346

@@ -83,22 +76,13 @@ pub async fn check_access(
8376
return Ok(());
8477
}
8578

86-
let apply_all_rules = try_join_all(rules.iter().map(|rule| {
87-
apply_rule(
88-
redis.clone(),
89-
&rule,
90-
&events,
91-
&campaign,
92-
&auth_uid,
93-
&session,
94-
)
95-
}));
79+
let apply_all_rules = try_join_all(
80+
rules
81+
.iter()
82+
.map(|rule| apply_rule(redis.clone(), rule, events, campaign, &auth_uid, session)),
83+
);
9684

97-
if let Err(rule_error) = apply_all_rules.await {
98-
Err(Error::RulesError(rule_error))
99-
} else {
100-
Ok(())
101-
}
85+
apply_all_rules.await.map_err(Error::RulesError).map(|_| ())
10286
}
10387

10488
async fn apply_rule(
@@ -188,9 +172,8 @@ mod test {
188172
config::configuration,
189173
event_submission::{RateLimit, Rule},
190174
sentry::Event,
191-
targeting::Rules,
192-
util::tests::prep_db::{ADDRESSES, DUMMY_CAMPAIGN, DUMMY_CHANNEL, IDS},
193-
Channel, Config, EventSubmission,
175+
util::tests::prep_db::{ADDRESSES, DUMMY_CAMPAIGN, IDS},
176+
Config, EventSubmission,
194177
};
195178

196179
use deadpool::managed::Object;

sentry/src/analytics_recorder.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,6 @@ pub async fn record(
114114
.ignore();
115115
}
116116
}
117-
_ => {}
118117
});
119118

120119
if let Err(err) = db.query_async::<_, Option<String>>(&mut conn).await {

sentry/src/db.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ pub async fn setup_migrations(environment: &str) {
7777
.database_password(POSTGRES_PASSWORD.as_str())
7878
.database_host(POSTGRES_HOST.as_str())
7979
.database_port(*POSTGRES_PORT)
80-
.database_name(&POSTGRES_DB.as_ref().unwrap_or(&POSTGRES_USER))
80+
.database_name(POSTGRES_DB.as_ref().unwrap_or(&POSTGRES_USER))
8181
.build()
8282
.expect("Should build migration settings");
8383

0 commit comments

Comments
 (0)