Skip to content

Commit 895f626

Browse files
authored
Merge branch 'dev' into issue-105-validator_worker-logging
2 parents 2e3e873 + 12908f2 commit 895f626

File tree

13 files changed

+349
-143
lines changed

13 files changed

+349
-143
lines changed

adapter/src/dummy.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use futures::future::{BoxFuture, FutureExt};
22
use primitives::adapter::{Adapter, AdapterError, AdapterResult, DummyAdapterOptions, Session};
33
use primitives::channel_validator::ChannelValidator;
44
use primitives::config::Config;
5-
use primitives::{Channel, ValidatorId};
5+
use primitives::{Channel, ToETHChecksum, ValidatorId};
66
use std::collections::HashMap;
77

88
#[derive(Debug, Clone)]
@@ -43,7 +43,7 @@ impl Adapter for DummyAdapter {
4343
let signature = format!(
4444
"Dummy adapter signature for {} by {}",
4545
state_root,
46-
self.whoami().to_hex_checksummed_string()
46+
self.whoami().to_checksum()
4747
);
4848
Ok(signature)
4949
}
@@ -57,7 +57,7 @@ impl Adapter for DummyAdapter {
5757
// select the `identity` and compare it to the signer
5858
// for empty string this will return array with 1 element - an empty string `[""]`
5959
let is_same = match signature.rsplit(' ').take(1).next() {
60-
Some(from) => from == signer.to_hex_checksummed_string(),
60+
Some(from) => from == signer.to_checksum(),
6161
None => false,
6262
};
6363

adapter/src/ethereum.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use primitives::{
1313
adapter::{Adapter, AdapterError, AdapterResult, KeystoreOptions, Session},
1414
channel_validator::ChannelValidator,
1515
config::Config,
16-
Channel, ValidatorId,
16+
Channel, ToETHChecksum, ValidatorId,
1717
};
1818
use serde::{Deserialize, Serialize};
1919
use serde_hex::{SerHexOpt, StrictPfx};
@@ -211,7 +211,7 @@ impl Adapter for EthereumAdapter {
211211
let verified = ewt_verify(header_encoded, payload_encoded, token_encoded)
212212
.map_err(|e| map_error(&e.to_string()))?;
213213

214-
if self.whoami().to_hex_checksummed_string() != verified.payload.id {
214+
if self.whoami().to_checksum() != verified.payload.id {
215215
return Err(AdapterError::Configuration(
216216
"token payload.id !== whoami(): token was not intended for us".to_string(),
217217
));
@@ -265,10 +265,10 @@ impl Adapter for EthereumAdapter {
265265

266266
let era = Utc::now().timestamp_millis() as f64 / 60000.0;
267267
let payload = Payload {
268-
id: validator.to_hex_checksummed_string(),
268+
id: validator.to_checksum(),
269269
era: era.floor() as i64,
270270
identity: None,
271-
address: self.whoami().to_hex_checksummed_string(),
271+
address: self.whoami().to_checksum(),
272272
};
273273

274274
ewt_sign(&wallet, &self.keystore_pwd, &payload)
@@ -424,7 +424,7 @@ mod test {
424424
let whoami = eth_adapter.whoami();
425425
assert_eq!(
426426
whoami.to_string(),
427-
"0x2bdeafae53940669daa6f519373f686c1f3d3393",
427+
"0x2bDeAFAE53940669DaA6F519373f686c1f3d3393",
428428
"failed to get correct whoami"
429429
);
430430

@@ -460,7 +460,7 @@ mod test {
460460
let payload = Payload {
461461
id: "awesomeValidator".into(),
462462
era: 100_000,
463-
address: eth_adapter.whoami().to_hex_checksummed_string(),
463+
address: eth_adapter.whoami().to_checksum(),
464464
identity: None,
465465
};
466466
let wallet = eth_adapter.wallet.clone();
@@ -542,7 +542,7 @@ mod test {
542542
.expect("Failed to set balance");
543543

544544
let leader_validator_desc = ValidatorDesc {
545-
// keystore.json addresss (same with js)
545+
// keystore.json address (same with js)
546546
id: ValidatorId::try_from("2bdeafae53940669daa6f519373f686c1f3d3393")
547547
.expect("failed to create id"),
548548
url: "http://localhost:8005".to_string(),
@@ -551,7 +551,7 @@ mod test {
551551
};
552552

553553
let follower_validator_desc = ValidatorDesc {
554-
// keystore2.json addresss (same with js)
554+
// keystore2.json address (same with js)
555555
id: ValidatorId::try_from("6704Fbfcd5Ef766B287262fA2281C105d57246a6")
556556
.expect("failed to create id"),
557557
url: "http://localhost:8006".to_string(),
@@ -605,7 +605,7 @@ mod test {
605605
.expect("open channel");
606606

607607
let contract_addr = <[u8; 20]>::from_hex(&format!("{:?}", adex_contract.address())[2..])
608-
.expect("failed to deserialise contract addr");
608+
.expect("failed to deserialize contract addr");
609609

610610
let channel_id = eth_channel.hash(&contract_addr).expect("hash hex");
611611
// set id to proper id
@@ -669,7 +669,7 @@ mod test {
669669
.expect("failed to deserialize address");
670670

671671
let payload = Payload {
672-
id: eth_adapter.whoami().to_hex_checksummed_string(),
672+
id: eth_adapter.whoami().to_checksum(),
673673
era: 100_000,
674674
address: format!("{:?}", leader_account),
675675
identity: Some(identity),

primitives/src/balances_map.rs

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,93 @@
11
use std::collections::BTreeMap;
22

3-
use crate::BigNum;
3+
use crate::{BigNum, ValidatorId};
4+
use std::collections::btree_map::{Entry, Iter, Values};
45

5-
pub type BalancesMap = BTreeMap<String, BigNum>;
6+
use serde::{ser::SerializeMap, Deserialize, Serialize, Serializer};
7+
use std::iter::FromIterator;
8+
use std::ops::Index;
9+
10+
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
11+
#[serde(transparent)]
12+
pub struct BalancesMap(BTreeMap<ValidatorId, BigNum>);
13+
14+
impl Index<&'_ ValidatorId> for BalancesMap {
15+
type Output = BigNum;
16+
17+
fn index(&self, index: &ValidatorId) -> &Self::Output {
18+
self.0.index(index)
19+
}
20+
}
21+
22+
impl BalancesMap {
23+
pub fn iter(&self) -> Iter<'_, ValidatorId, BigNum> {
24+
self.0.iter()
25+
}
26+
27+
pub fn values(&self) -> Values<'_, ValidatorId, BigNum> {
28+
self.0.values()
29+
}
30+
31+
pub fn get(&self, key: &ValidatorId) -> Option<&BigNum> {
32+
self.0.get(key)
33+
}
34+
35+
pub fn entry(&mut self, key: ValidatorId) -> Entry<'_, ValidatorId, BigNum> {
36+
self.0.entry(key)
37+
}
38+
39+
pub fn insert(&mut self, key: ValidatorId, value: BigNum) -> Option<BigNum> {
40+
self.0.insert(key, value)
41+
}
42+
}
43+
44+
impl FromIterator<(ValidatorId, BigNum)> for BalancesMap {
45+
fn from_iter<I: IntoIterator<Item = (ValidatorId, BigNum)>>(iter: I) -> Self {
46+
// @TODO: Is there better way to do this?
47+
let btree_map: BTreeMap<ValidatorId, BigNum> = iter.into_iter().collect();
48+
49+
BalancesMap(btree_map)
50+
}
51+
}
52+
53+
impl Serialize for BalancesMap {
54+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
55+
where
56+
S: Serializer,
57+
{
58+
let mut map = serializer.serialize_map(Some(self.0.len()))?;
59+
60+
for (key, big_num) in self.0.iter() {
61+
map.serialize_entry(&key.to_hex_prefix_string(), big_num)?;
62+
}
63+
map.end()
64+
}
65+
}
66+
67+
#[cfg(test)]
68+
mod test {
69+
use super::*;
70+
use crate::util::tests::prep_db::IDS;
71+
use crate::BigNum;
72+
73+
#[test]
74+
fn test_balances_map_serialization() {
75+
let data = vec![
76+
(IDS["leader"].clone(), BigNum::from(50_u64)),
77+
(IDS["follower"].clone(), BigNum::from(100_u64)),
78+
];
79+
80+
let balances_map: BalancesMap = data.into_iter().collect();
81+
82+
let actual_json = serde_json::to_string(&balances_map).expect("Should serialize it");
83+
// should be all lowercase!
84+
let expected_json = r#"{"0xc91763d7f14ac5c5ddfbcd012e0d2a61ab9bded3":"100","0xce07cbb7e054514d590a0262c93070d838bfba2e":"50"}"#;
85+
86+
assert_eq!(expected_json, actual_json);
87+
88+
let balances_map_from_json: BalancesMap =
89+
serde_json::from_str(&actual_json).expect("Should deserialize it");
90+
91+
assert_eq!(balances_map, balances_map_from_json);
92+
}
93+
}

primitives/src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,3 +55,11 @@ impl error::Error for DomainError {
5555
None
5656
}
5757
}
58+
59+
/// Trait that creates a String which is `0x` prefixed and encodes the bytes by `eth_checksum`
60+
pub trait ToETHChecksum: AsRef<[u8]> {
61+
fn to_checksum(&self) -> String {
62+
// checksum replaces `0x` prefix and adds one itself
63+
eth_checksum::checksum(&hex::encode(self.as_ref()))
64+
}
65+
}

primitives/src/sentry.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ pub struct ApproveStateValidatorMessage {
3232
pub enum Event {
3333
#[serde(rename_all = "camelCase")]
3434
Impression {
35-
publisher: String,
35+
publisher: ValidatorId,
3636
ad_unit: Option<String>,
3737
},
3838
Click {
@@ -74,8 +74,8 @@ pub struct EventAggregate {
7474
#[serde(rename_all = "camelCase")]
7575
pub struct AggregateEvents {
7676
#[serde(default, skip_serializing_if = "Option::is_none")]
77-
pub event_counts: Option<HashMap<String, BigNum>>,
78-
pub event_payouts: HashMap<String, BigNum>,
77+
pub event_counts: Option<HashMap<ValidatorId, BigNum>>,
78+
pub event_payouts: HashMap<ValidatorId, BigNum>,
7979
}
8080

8181
#[derive(Debug, Serialize, Deserialize)]

primitives/src/validator.rs

Lines changed: 36 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use chrono::{DateTime, Utc};
2-
use serde::{Deserialize, Serialize};
2+
use serde::{Deserialize, Serialize, Serializer};
33
use serde_hex::{SerHex, StrictPfx};
44
use std::fmt;
55

6-
use crate::{BalancesMap, BigNum, DomainError};
6+
use crate::{BalancesMap, BigNum, DomainError, ToETHChecksum};
77
use std::convert::TryFrom;
88

99
#[derive(Debug)]
@@ -14,7 +14,7 @@ pub enum ValidatorError {
1414
InvalidTransition,
1515
}
1616

17-
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
17+
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
1818
#[serde(transparent)]
1919
pub struct ValidatorId(#[serde(with = "SerHex::<StrictPfx>")] [u8; 20]);
2020

@@ -23,12 +23,26 @@ impl ValidatorId {
2323
&self.0
2424
}
2525

26+
/// To Hex non-`0x` prefixed string without **Checksum**ing the string
2627
pub fn to_hex_non_prefix_string(&self) -> String {
2728
hex::encode(self.0)
2829
}
2930

30-
pub fn to_hex_checksummed_string(&self) -> String {
31-
eth_checksum::checksum(&format!("0x{}", self.to_hex_non_prefix_string()))
31+
/// To Hex `0x` prefixed string **without** __Checksum__ing the string
32+
pub fn to_hex_prefix_string(&self) -> String {
33+
format!("0x{}", self.to_hex_non_prefix_string())
34+
}
35+
}
36+
37+
impl ToETHChecksum for ValidatorId {}
38+
39+
impl Serialize for ValidatorId {
40+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
41+
where
42+
S: Serializer,
43+
{
44+
let checksum = self.to_checksum();
45+
serializer.serialize_str(&checksum)
3246
}
3347
}
3448

@@ -79,7 +93,7 @@ impl TryFrom<&String> for ValidatorId {
7993

8094
impl fmt::Display for ValidatorId {
8195
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82-
write!(f, "{}", format!("0x{}", self.to_hex_non_prefix_string()))
96+
write!(f, "{}", self.to_checksum())
8397
}
8498
}
8599

@@ -207,3 +221,19 @@ pub mod postgres {
207221
}
208222
}
209223
}
224+
225+
#[cfg(test)]
226+
mod test {
227+
use super::*;
228+
229+
#[test]
230+
fn validator_id_is_checksummed_when_serialized() {
231+
let validator_id_checksum_str = "0xce07CbB7e054514D590a0262C93070D838bFBA2e";
232+
233+
let validator_id =
234+
ValidatorId::try_from(validator_id_checksum_str).expect("Valid string was provided");
235+
let actual_json = serde_json::to_string(&validator_id).expect("Should serialize");
236+
let expected_json = format!(r#""{}""#, validator_id_checksum_str);
237+
assert_eq!(expected_json, actual_json);
238+
}
239+
}

sentry/src/access.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,10 +188,11 @@ mod test {
188188

189189
channel
190190
}
191+
191192
fn get_impression_events(count: i8) -> Vec<Event> {
192193
(0..count)
193194
.map(|_| Event::Impression {
194-
publisher: "working".to_string(),
195+
publisher: IDS["publisher2"].clone(),
195196
ad_unit: None,
196197
})
197198
.collect()

0 commit comments

Comments
 (0)