Skip to content

Commit e4739e4

Browse files
committed
fix: ethereum, dummy adapter
1 parent 8fb4304 commit e4739e4

File tree

4 files changed

+40
-63
lines changed

4 files changed

+40
-63
lines changed

adapter/src/dummy.rs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,8 @@ impl Adapter for DummyAdapter {
4242
})
4343
}
4444

45-
fn unlock(&self) -> AdapterResult<bool> {
46-
Ok(true)
45+
fn unlock(&self) -> AdapterResult<()> {
46+
Ok(())
4747
}
4848

4949
fn whoami(&self) -> String {
@@ -80,12 +80,14 @@ impl Adapter for DummyAdapter {
8080
fn session_from_token(&self, token: &str) -> AdapterResult<Session> {
8181
let identity = self
8282
.authorization_tokens
83-
.clone()
84-
.into_iter()
83+
.iter()
8584
.find(|(_, id)| *id == token);
8685

8786
match identity {
88-
Some((id, _)) => Ok(Session { uid: id, era: 0 }),
87+
Some((id, _)) => Ok(Session {
88+
uid: id.to_owned(),
89+
era: 0,
90+
}),
8991
None => Err(AdapterError::Authentication(format!(
9092
"no session token for this auth: {}",
9193
token
@@ -96,13 +98,12 @@ impl Adapter for DummyAdapter {
9698
fn get_auth(&self, _validator: &ValidatorDesc) -> AdapterResult<String> {
9799
let who = self
98100
.session_tokens
99-
.clone()
100-
.into_iter()
101-
.find(|(_, id)| *id == self.identity);
101+
.iter()
102+
.find(|(_, id)| *id == &self.identity);
102103

103104
match who {
104105
Some((id, _)) => {
105-
let auth = self.authorization_tokens.get(&id).expect("id should exist");
106+
let auth = self.authorization_tokens.get(id).expect("id should exist");
106107
Ok(auth.to_owned())
107108
}
108109
None => Err(AdapterError::Authentication(format!(

adapter/src/ethereum.rs

Lines changed: 22 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ lazy_static! {
2828
include_bytes!("../../lib/protocol-eth/abi/AdExCore.json");
2929
static ref IDENTITY_ABI: &'static [u8] =
3030
include_bytes!("../../lib/protocol-eth/abi/Identity.json");
31+
static ref CHANNEL_STATE_ACTIVE: U256 = 1.into();
32+
static ref PRIVILEGE_LEVEL_NONE: U256 = 0.into();
3133
}
3234

3335
#[derive(Debug, Clone)]
@@ -86,7 +88,7 @@ impl Adapter for EthereumAdapter {
8688
})
8789
}
8890

89-
fn unlock(&self) -> AdapterResult<bool> {
91+
fn unlock(&self) -> AdapterResult<()> {
9092
let account = SafeAccount::from_file(
9193
serde_json::from_value(self.keystore_json.clone())
9294
.map_err(|_| map_error("Invalid keystore json provided"))?,
@@ -97,8 +99,7 @@ impl Adapter for EthereumAdapter {
9799

98100
self.wallet.replace(Some(account));
99101

100-
// wallet has been unlocked
101-
Ok(true)
102+
Ok(())
102103
}
103104

104105
fn whoami(&self) -> String {
@@ -124,7 +125,7 @@ impl Adapter for EthereumAdapter {
124125
fn verify(&self, signer: &str, state_root: &str, sig: &str) -> AdapterResult<bool> {
125126
let (decoded_adress, decoded_signature) = match (hex::decode(signer), hex::decode(sig)) {
126127
(Ok(address), Ok(sig)) => (address, sig),
127-
(_, _) => {
128+
_ => {
128129
return Err(AdapterError::Signature(
129130
"invalid signature or address".to_string(),
130131
))
@@ -135,10 +136,7 @@ impl Adapter for EthereumAdapter {
135136
let signature = Signature::from_electrum(&decoded_signature);
136137
let message = Message::from_slice(&hash_message(state_root));
137138

138-
match verify_address(&address, &signature, &message) {
139-
Ok(result) => Ok(result),
140-
Err(_) => Ok(false),
141-
}
139+
verify_address(&address, &signature, &message).or(Ok(false))
142140
}
143141

144142
fn validate_channel(&self, channel: &Channel) -> AdapterResult<bool> {
@@ -159,14 +157,8 @@ impl Adapter for EthereumAdapter {
159157
));
160158
}
161159
// check if channel is valid
162-
let is_channel_valid = EthereumAdapter::is_channel_valid(&self.config, channel);
163-
if is_channel_valid.is_err() {
164-
return Err(AdapterError::InvalidChannel(
165-
is_channel_valid
166-
.err()
167-
.expect("failed to get channel error")
168-
.to_string(),
169-
));
160+
if let Err(error) = EthereumAdapter::is_channel_valid(&self.config, channel) {
161+
return Err(AdapterError::InvalidChannel(error.to_string()));
170162
}
171163
// query the blockchain for the channel status
172164
let contract_address = Address::from_slice(self.config.ethereum_core_address.as_bytes());
@@ -178,7 +170,7 @@ impl Adapter for EthereumAdapter {
178170
.wait()
179171
.map_err(|_| map_error("contract channel status query failed"))?;
180172

181-
if channel_status != 1.into() {
173+
if channel_status != *CHANNEL_STATE_ACTIVE {
182174
return Err(AdapterError::Configuration(
183175
"channel is not Active on the ethereum network".to_string(),
184176
));
@@ -192,14 +184,11 @@ impl Adapter for EthereumAdapter {
192184
return Err(AdapterError::Failed("invaild token id".to_string()));
193185
}
194186

195-
let token_id = token.to_owned()[token.len() - 16..].to_string();
187+
let token_id = token[token.len() - 16..].to_string();
196188

197189
let mut session_tokens = self.session_tokens.borrow_mut();
198-
if session_tokens.get(&token_id).is_some() {
199-
return Ok(session_tokens
200-
.get(&token_id)
201-
.expect("failed to get session")
202-
.to_owned());
190+
if let Some(token) = session_tokens.get(&token_id) {
191+
return Ok(token.to_owned());
203192
}
204193

205194
let parts: Vec<&str> = token.split('.').collect();
@@ -208,7 +197,7 @@ impl Adapter for EthereumAdapter {
208197
(Some(header_encoded), Some(payload_encoded), Some(token_encoded)) => {
209198
(header_encoded, payload_encoded, token_encoded)
210199
}
211-
(_, _, _) => {
200+
_ => {
212201
return Err(AdapterError::Failed(format!(
213202
"{} token string is incorrect",
214203
token
@@ -236,7 +225,7 @@ impl Adapter for EthereumAdapter {
236225
.wait()
237226
.map_err(|_| map_error("failed query priviledge level on contract"))?;
238227

239-
if priviledge_level == 0.into() {
228+
if priviledge_level == *PRIVILEGE_LEVEL_NONE {
240229
return Err(AdapterError::Authorization(
241230
"insufficient privilege".to_string(),
242231
));
@@ -286,14 +275,11 @@ impl Adapter for EthereumAdapter {
286275
}
287276

288277
fn check_validator_id_checksum(channel: &Channel) -> bool {
289-
let invalid_address_checkum: Vec<&ValidatorDesc> = channel
278+
channel
290279
.spec
291280
.validators
292281
.into_iter()
293-
.filter(|v| v.id != eth_checksum::checksum(&v.id))
294-
.collect();
295-
296-
invalid_address_checkum.is_empty()
282+
.any(|v| v.id != eth_checksum::checksum(&v.id))
297283
}
298284

299285
fn hash_message(message: &str) -> [u8; 32] {
@@ -361,15 +347,11 @@ pub fn ewt_sign(
361347
alg: "ETH".to_string(),
362348
};
363349

364-
let header_encoded = base64::encode_config(
365-
&serde_json::to_string(&header)?.as_bytes(),
366-
base64::URL_SAFE_NO_PAD,
367-
);
350+
let header_encoded =
351+
base64::encode_config(&serde_json::to_string(&header)?, base64::URL_SAFE_NO_PAD);
368352

369-
let payload_encoded = base64::encode_config(
370-
&serde_json::to_string(payload)?.as_bytes(),
371-
base64::URL_SAFE_NO_PAD,
372-
);
353+
let payload_encoded =
354+
base64::encode_config(&serde_json::to_string(payload)?, base64::URL_SAFE_NO_PAD);
373355

374356
let message = Message::from_slice(&hash_message(&format!(
375357
"{}.{}",
@@ -441,7 +423,7 @@ mod test {
441423
let eth_adapter = setup_eth_adapter();
442424
let unlock = eth_adapter.unlock().expect("should unlock eth adapter");
443425

444-
assert_eq!(true, unlock, "failed to unlock eth adapter");
426+
assert_eq!((), unlock, "failed to unlock eth adapter");
445427
}
446428

447429
#[test]
@@ -483,7 +465,7 @@ mod test {
483465

484466
let payload = Payload {
485467
id: "awesomeValidator".to_string(),
486-
era: 10_0000,
468+
era: 100_000,
487469
address: Some(eth_adapter.whoami()),
488470
identity: None,
489471
};

adapter/src/lib.rs

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
1-
#![feature(async_await, await_macro)]
2-
#![deny(rust_2018_idioms)]
3-
#![deny(clippy::all)]
4-
#![deny(clippy::match_bool)]
5-
#![doc(test(attr(feature(async_await, await_macro))))]
6-
71
use std::error::Error;
82

3+
use chrono::{DateTime, Utc};
94
use ethabi::encode;
105
use ethabi::param_type::ParamType;
116
use ethabi::token::{LenientTokenizer, StrictTokenizer, Tokenizer};
7+
use primitives::BigNum;
128
use primitives::Channel;
139
use sha2::{Digest, Sha256};
1410
use std::convert::From;
1511
use tiny_keccak::Keccak;
1612

17-
use primitives::BigNum;
18-
1913
pub use self::dummy::DummyAdapter;
2014
pub use self::ethereum::EthereumAdapter;
2115

@@ -81,7 +75,7 @@ impl From<&Channel> for EthereumChannel {
8175

8276
let spec_hash = format!("{:02x}", hash.result());
8377

84-
let validators: Vec<String> = channel
78+
let validators = channel
8579
.spec
8680
.validators
8781
.into_iter()
@@ -92,7 +86,7 @@ impl From<&Channel> for EthereumChannel {
9286
&channel.creator,
9387
&channel.deposit_asset,
9488
&channel.deposit_amount.to_string(),
95-
channel.valid_until.timestamp(),
89+
channel.valid_until,
9690
validators,
9791
&spec_hash,
9892
)
@@ -104,16 +98,16 @@ impl EthereumChannel {
10498
creator: &str,
10599
token_addr: &str,
106100
token_amount: &str,
107-
valid_until: i64,
101+
valid_until: DateTime<Utc>,
108102
validators: Vec<String>,
109103
spec: &str,
110104
) -> Self {
111-
//@TODO some validation
105+
// @TODO some validation
112106
Self {
113107
creator: creator.to_owned(),
114108
token_addr: token_addr.to_owned(),
115109
token_amount: token_amount.to_owned(),
116-
valid_until,
110+
valid_until: valid_until.timestamp(),
117111
validators: format!("[{}]", validators.join(",")),
118112
spec: spec.to_owned(),
119113
}

primitives/src/adapter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ pub trait Adapter: ChannelValidator + Clone + Debug {
5656
fn init(opts: AdapterOptions, config: &Config) -> AdapterResult<Self::Output>;
5757

5858
/// Unlock adapter
59-
fn unlock(&self) -> AdapterResult<bool>;
59+
fn unlock(&self) -> AdapterResult<()>;
6060

6161
/// Get Adapter whoami
6262
fn whoami(&self) -> String;

0 commit comments

Comments
 (0)