Skip to content

Commit 49863fe

Browse files
authored
Merge pull request #140 from AdExNetwork/issue-118-123-leader-follower-and-producer-ticks
Issues #118 Leader/follower
2 parents 6748650 + 3c79e28 commit 49863fe

File tree

14 files changed

+341
-119
lines changed

14 files changed

+341
-119
lines changed

adapter/src/lib.rs

+43-64
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,21 @@
44
#![deny(clippy::match_bool)]
55
#![doc(test(attr(feature(async_await, await_macro))))]
66

7-
use ethabi::encode;
8-
use ethabi::param_type::{ParamType, Reader};
9-
use ethabi::token::{LenientTokenizer, StrictTokenizer, Token, Tokenizer};
107
use std::error::Error;
8+
9+
use ethabi::encode;
10+
use ethabi::param_type::ParamType;
11+
use ethabi::token::{LenientTokenizer, StrictTokenizer, Tokenizer};
1112
use tiny_keccak::Keccak;
1213

13-
pub mod dummy;
14-
pub mod ethereum;
14+
use primitives::BigNum;
1515

1616
pub use self::dummy::DummyAdapter;
1717
pub use self::ethereum::EthereumAdapter;
1818

19+
pub mod dummy;
20+
pub mod ethereum;
21+
1922
pub enum AdapterTypes {
2023
DummyAdapter(DummyAdapter),
2124
EthereumAdapter(EthereumAdapter),
@@ -25,9 +28,11 @@ pub fn get_signable_state_root(
2528
channel_id: &str,
2629
balance_root: &str,
2730
) -> Result<[u8; 32], Box<dyn Error>> {
28-
let types = ["bytes32".to_string(), "bytes32".to_string()];
29-
let values = [channel_id.to_string(), balance_root.to_string()];
30-
let encoded = encode_params(&types, &values, true)?;
31+
let params = [
32+
(ParamType::FixedBytes(32), channel_id),
33+
(ParamType::FixedBytes(32), balance_root),
34+
];
35+
let encoded = encode_params(&params, true)?;
3136

3237
let mut result = Keccak::new_keccak256();
3338
result.update(&encoded);
@@ -38,10 +43,12 @@ pub fn get_signable_state_root(
3843
Ok(res)
3944
}
4045

41-
pub fn get_balance_leaf(acc: &str, amnt: &str) -> Result<[u8; 32], Box<dyn Error>> {
42-
let types: Vec<String> = vec!["address".to_string(), "uint256".to_string()];
43-
let values = [acc.to_string(), amnt.to_string()];
44-
let encoded = encode_params(&types, &values, true)?;
46+
pub fn get_balance_leaf(acc: &str, amnt: &BigNum) -> Result<[u8; 32], Box<dyn Error>> {
47+
let params = [
48+
(ParamType::Address, acc),
49+
(ParamType::Uint(256), &amnt.to_str_radix(16)),
50+
];
51+
let encoded = encode_params(&params, true)?;
4552

4653
let mut result = Keccak::new_keccak256();
4754
result.update(&encoded);
@@ -83,29 +90,20 @@ impl EthereumChannel {
8390
}
8491

8592
pub fn hash(&self, contract_addr: &str) -> Result<[u8; 32], Box<dyn Error>> {
86-
let types: Vec<String> = vec![
87-
"address",
88-
"address",
89-
"address",
90-
"uint256",
91-
"uint256",
92-
"address[]",
93-
"bytes32",
94-
]
95-
.into_iter()
96-
.map(ToString::to_string)
97-
.collect();
98-
99-
let values = [
100-
contract_addr.to_string(),
101-
self.creator.to_owned(),
102-
self.token_addr.to_owned(),
103-
self.token_amount.to_owned(),
104-
self.valid_until.to_owned(),
105-
self.validators.to_owned(),
106-
self.spec.to_owned(),
93+
let params = [
94+
(ParamType::Address, contract_addr),
95+
(ParamType::Address, &self.creator),
96+
(ParamType::Address, &self.token_addr),
97+
(ParamType::Uint(256), &self.token_amount),
98+
(ParamType::Uint(256), &self.valid_until),
99+
(
100+
ParamType::Array(Box::new(ParamType::Address)),
101+
&self.validators,
102+
),
103+
(ParamType::FixedBytes(32), &self.spec),
107104
];
108-
let encoded = encode_params(&types, &values, true)?;
105+
106+
let encoded = encode_params(&params, true)?;
109107
let mut result = Keccak::new_keccak256();
110108
result.update(&encoded);
111109

@@ -149,50 +147,31 @@ impl EthereumChannel {
149147
}
150148
}
151149

152-
fn encode_params(
153-
types: &[String],
154-
values: &[String],
155-
lenient: bool,
156-
) -> Result<Vec<u8>, Box<dyn Error>> {
157-
assert_eq!(types.len(), values.len());
158-
159-
let types: Vec<ParamType> = types
160-
.iter()
161-
.map(|s| Reader::read(s))
162-
.collect::<Result<_, _>>()?;
163-
164-
let params: Vec<_> = types
165-
.into_iter()
166-
.zip(values.iter().map(|s| s as &str))
167-
.collect();
168-
169-
let tokens = parse_tokens(&params, lenient)?;
170-
let result = encode(&tokens);
171-
172-
Ok(result.to_vec())
173-
}
174-
175-
fn parse_tokens(params: &[(ParamType, &str)], lenient: bool) -> Result<Vec<Token>, Box<dyn Error>> {
176-
params
150+
fn encode_params(params: &[(ParamType, &str)], lenient: bool) -> Result<Vec<u8>, Box<dyn Error>> {
151+
let tokens = params
177152
.iter()
178-
.map(|&(ref param, value)| {
153+
.map(|(param, value)| {
179154
if lenient {
180155
LenientTokenizer::tokenize(param, value)
181156
} else {
182157
StrictTokenizer::tokenize(param, value)
183158
}
184159
})
185-
.collect::<Result<_, _>>()
186-
.map_err(From::from)
160+
.collect::<Result<Vec<_>, _>>()?;
161+
162+
Ok(encode(&tokens).to_vec())
187163
}
188164

189165
#[cfg(test)]
190166
mod test {
191-
use super::*;
167+
use std::convert::TryFrom;
168+
192169
use byteorder::{BigEndian, ByteOrder};
193170
use chrono::{TimeZone, Utc};
171+
194172
use primitives::merkle_tree::MerkleTree;
195-
use std::convert::TryFrom;
173+
174+
use super::*;
196175

197176
#[test]
198177
fn test_get_signable_state_root_hash_is_aligned_with_js_impl() {

primitives/src/adapter.rs

+1-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
1-
use futures::prelude::*;
2-
use std::collections::HashMap;
3-
use std::pin::Pin;
4-
// use domain::validator::message::State;
51
use crate::channel_validator::ChannelValidator;
62
use crate::validator::ValidatorDesc;
73
use crate::{Channel, Config};
8-
//use crate::sanity::SanityChecker;
4+
use std::collections::HashMap;
95
use std::error::Error;
106
use std::fmt;
117
use std::fmt::Debug;

primitives/src/big_num.rs

+4
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ impl BigNum {
4040

4141
self.0.to_u64()
4242
}
43+
44+
pub fn to_str_radix(&self, radix: u32) -> String {
45+
self.0.to_str_radix(radix)
46+
}
4347
}
4448

4549
impl Integer for BigNum {

primitives/src/config.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub struct Config {
3030
pub max_channels: u32,
3131
pub wait_time: u32,
3232
pub aggr_throttle: u32,
33-
pub heartbeat_time: u32,
33+
pub heartbeat_time: u32, // in milliseconds
3434
pub channels_find_limit: u32,
3535
pub events_find_limit: u32,
3636
pub health_threshold_promilles: u32,

primitives/src/sentry.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
use crate::validator::{ApproveState, Heartbeat, MessageTypes, NewState};
2-
use crate::{BalancesMap, BigNum, Channel};
2+
use crate::{BigNum, Channel};
33
use chrono::{DateTime, Utc};
4-
use hex::FromHex;
54
use serde::{Deserialize, Serialize};
65
use std::collections::HashMap;
76

87
#[derive(Serialize, Deserialize, Debug)]
98
#[serde(rename_all = "camelCase")]
109
pub struct LastApproved {
11-
new_state: NewState,
12-
approved_state: ApproveState,
10+
/// NewState can be None if the channel is brand new
11+
pub new_state: Option<NewState>,
12+
/// ApproveState can be None if the channel is brand new
13+
pub approved_state: Option<ApproveState>,
1314
}
1415

1516
#[serde(tag = "type", rename_all = "SCREAMING_SNAKE_CASE")]
@@ -69,7 +70,7 @@ pub struct ChannelAllResponse {
6970
#[derive(Serialize, Deserialize, Debug)]
7071
#[serde(rename_all = "camelCase")]
7172
pub struct LastApprovedResponse {
72-
pub last_approved: LastApproved,
73+
pub last_approved: Option<LastApproved>,
7374
pub heartbeats: Option<Vec<Heartbeat>>,
7475
}
7576

primitives/src/util/tests/prep_db.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@ lazy_static! {
1111
ids.insert("leader", "awesomeLeader".into());
1212
ids.insert("follower", "awesomeFollower".into());
1313
ids.insert("user", "awesomeTestUser".into());
14-
ids.insert("publisher", "myAwesomePublisher".into());
14+
ids.insert("publisher", "b7d3f81e857692d13e9d63b232a90f4a1793189e".into());
1515
ids.insert("publisher2", "myAwesomePublisher2".into());
1616
ids.insert("creator", "awesomeCreator".into());
17+
ids.insert("tester", "2892f6C41E0718eeeDd49D98D648C789668cA67d".into());
1718

1819
ids
1920
};
@@ -27,6 +28,7 @@ lazy_static! {
2728
auth.insert("publisher", "testing".into());
2829
auth.insert("publisher2", "testing2".into());
2930
auth.insert("creator", "awesomeCreator".into());
31+
auth.insert("tester", "AUTH_awesomeTester".into());
3032

3133
auth
3234
};
@@ -47,7 +49,7 @@ lazy_static! {
4749
let nonce = BigNum::from(<Faker as Number>::between(100_000_000, 999_999_999));
4850

4951
Channel {
50-
id: "awesomeTestChannel".to_string(),
52+
id: "061d5e2a67d0a9a10f1c732bca12a676d83f79663a396f7d87b3e30b9b411088".to_string(),
5153
creator: "awesomeCreator".to_string(),
5254
deposit_asset: "DAI".to_string(),
5355
deposit_amount: 1_000.into(),

primitives/src/validator.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ pub struct ApproveState {
5353
pub struct NewState {
5454
pub state_root: String,
5555
pub signature: String,
56-
pub balances: String,
56+
pub balances: BalancesMap,
5757
}
5858

5959
#[derive(Default, Serialize, Deserialize, Debug, Clone)]
@@ -62,7 +62,7 @@ pub struct RejectState {
6262
pub reason: String,
6363
pub state_root: String,
6464
pub signature: String,
65-
pub balances: Option<String>,
65+
pub balances: Option<BalancesMap>,
6666
pub timestamp: Option<DateTime<Utc>>,
6767
}
6868

validator_worker/src/core/events.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
use std::collections::HashMap;
2-
3-
use chrono::{DateTime, Utc};
41
use num_traits::CheckedSub;
5-
use serde::{Deserialize, Serialize};
62

7-
use crate::core::fees::get_balances_after_fees_tree;
83
use primitives::sentry::{AggregateEvents, EventAggregate};
94
use primitives::validator::Accounting;
105
use primitives::{BalancesMap, BigNum, Channel, DomainError};
116

7+
use crate::core::fees::get_balances_after_fees_tree;
8+
129
pub(crate) fn merge_aggrs(
1310
accounting: &Accounting,
1411
aggregates: &[EventAggregate],
@@ -81,12 +78,15 @@ fn merge_payouts_into_balances<'a, T: Iterator<Item = &'a AggregateEvents>>(
8178

8279
#[cfg(test)]
8380
mod test {
84-
use super::*;
81+
use chrono::Utc;
82+
8583
use primitives::util::tests::prep_db::{
8684
DUMMY_CHANNEL, DUMMY_VALIDATOR_FOLLOWER, DUMMY_VALIDATOR_LEADER,
8785
};
8886
use primitives::{Channel, ChannelSpec, ValidatorDesc};
8987

88+
use super::*;
89+
9090
#[test]
9191
fn should_merge_event_aggrs_and_apply_fees() {
9292
// fees: 100

0 commit comments

Comments
 (0)