Skip to content

Commit 47684b8

Browse files
committed
adapter - ethereum - impl relayer call, remove unnecessary test and clean-up a bit
1 parent 5cbd283 commit 47684b8

File tree

1 file changed

+61
-95
lines changed

1 file changed

+61
-95
lines changed

adapter/src/ethereum.rs

Lines changed: 61 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use ethkey::Password;
55
use ethstore::SafeAccount;
66
use futures::compat::Future01CompatExt;
77
use futures::future::{BoxFuture, FutureExt};
8+
use futures::TryFutureExt;
89
use lazy_static::lazy_static;
910
use parity_crypto::publickey::{
1011
public_to_address, recover, verify_address, Address, Message, Signature,
@@ -15,6 +16,7 @@ use primitives::{
1516
config::Config,
1617
Channel, ToETHChecksum, ValidatorId,
1718
};
19+
use reqwest::Client;
1820
use serde::{Deserialize, Serialize};
1921
use serde_hex::{SerHexOpt, StrictPfx};
2022
use serde_json::Value;
@@ -34,10 +36,8 @@ use web3::{
3436
lazy_static! {
3537
static ref ADEXCORE_ABI: &'static [u8] =
3638
include_bytes!("../../lib/protocol-eth/abi/AdExCore.json");
37-
static ref IDENTITY_ABI: &'static [u8] =
38-
include_bytes!("../../lib/protocol-eth/abi/Identity.json");
3939
static ref CHANNEL_STATE_ACTIVE: U256 = 1.into();
40-
static ref PRIVILEGE_LEVEL_NONE: U256 = 0.into();
40+
static ref PRIVILEGE_LEVEL_NONE: u8 = 0;
4141
}
4242

4343
#[derive(Debug, Clone)]
@@ -49,6 +49,7 @@ pub struct EthereumAdapter {
4949
wallet: Option<SafeAccount>,
5050
event_loop: Arc<EventLoopHandle>,
5151
web3: Web3<Http>,
52+
relayer: RelayerClient,
5253
}
5354

5455
// Enables EthereumAdapter to be able to
@@ -78,6 +79,8 @@ impl EthereumAdapter {
7879
.map_err(|_| map_error("failed to init http transport"))?;
7980
let event_loop = Arc::new(eloop);
8081
let web3 = web3::Web3::new(transport);
82+
let relayer = RelayerClient::new(&config.ethereum_adapter_relayer)
83+
.map_err(|_| map_error("Client for Relayer couldn't be built"))?;
8184

8285
Ok(Self {
8386
address,
@@ -87,6 +90,7 @@ impl EthereumAdapter {
8790
config: config.to_owned(),
8891
event_loop,
8992
web3,
93+
relayer,
9094
})
9195
}
9296
}
@@ -219,31 +223,17 @@ impl Adapter for EthereumAdapter {
219223

220224
let sess = match &verified.payload.identity {
221225
Some(identity) => {
222-
let contract_address: Address = identity.into();
223-
let contract =
224-
Contract::from_json(self.web3.eth(), contract_address, &IDENTITY_ABI)
225-
.map_err(|_| map_error("failed to init identity contract"))?;
226-
227-
let privilege_level: U256 = contract
228-
.query(
229-
"privileges",
230-
(Token::Address(Address::from_slice(verified.from.inner())),),
231-
None,
232-
Options::default(),
233-
None,
234-
)
235-
.compat()
236-
.await
237-
.map_err(|_| map_error("failed query priviledge level on contract"))?;
238-
239-
if privilege_level == *PRIVILEGE_LEVEL_NONE {
226+
let privilege = self.relayer.get_privilege(identity).await?;
227+
228+
if privilege > *PRIVILEGE_LEVEL_NONE {
240229
return Err(AdapterError::Authorization(
241230
"insufficient privilege".to_string(),
242231
));
243-
}
244-
Session {
245-
era: verified.payload.era,
246-
uid: identity.into(),
232+
} else {
233+
Session {
234+
era: verified.payload.era,
235+
uid: identity.into(),
236+
}
247237
}
248238
}
249239
None => Session {
@@ -276,6 +266,49 @@ impl Adapter for EthereumAdapter {
276266
}
277267
}
278268

269+
#[derive(Debug, Clone)]
270+
struct RelayerClient {
271+
client: Client,
272+
relayer_url: String,
273+
}
274+
275+
impl RelayerClient {
276+
pub fn new(relayer_url: &str) -> Result<Self, reqwest::Error> {
277+
let client = Client::builder().build()?;
278+
279+
Ok(Self {
280+
relayer_url: relayer_url.to_string(),
281+
client,
282+
})
283+
}
284+
285+
pub async fn get_privilege(&self, identity: &[u8; 20]) -> Result<u8, AdapterError> {
286+
use reqwest::Response;
287+
use std::collections::HashMap;
288+
289+
let relay_url = format!(
290+
"{}/identity/by-owner/{}",
291+
self.relayer_url,
292+
hex::encode(identity)
293+
);
294+
295+
let identities_owned: HashMap<[u8; 20], u8> = self
296+
.client
297+
.get(&relay_url)
298+
.send()
299+
.and_then(|res: Response| res.json())
300+
.await
301+
.map_err(|_| map_error("Fetching privileges failed"))?;
302+
303+
let privilege = identities_owned
304+
.get(identity)
305+
.copied()
306+
.unwrap_or_else(|| 0_u8);
307+
308+
Ok(privilege)
309+
}
310+
}
311+
279312
fn hash_message(message: &str) -> [u8; 32] {
280313
let eth = "\x19Ethereum Signed Message:\n";
281314
let message_length = message.len();
@@ -377,7 +410,7 @@ pub fn ewt_verify(
377410
let payload: Payload = serde_json::from_str(&payload_string)?;
378411

379412
let verified_payload = VerifyPayload {
380-
from: ValidatorId::try_from(&format!("{:?}", address))?,
413+
from: ValidatorId::from(address.as_fixed_bytes()),
381414
payload,
382415
};
383416

@@ -604,13 +637,10 @@ mod test {
604637
.await
605638
.expect("open channel");
606639

607-
let contract_addr = <[u8; 20]>::from_hex(&format!("{:?}", adex_contract.address())[2..])
608-
.expect("failed to deserialize contract addr");
609-
640+
let contract_addr = adex_contract.address().to_fixed_bytes();
610641
let channel_id = eth_channel.hash(&contract_addr).expect("hash hex");
611642
// set id to proper id
612-
valid_channel.id = ChannelId::from_hex(hex::encode(channel_id))
613-
.expect("prep_db: failed to deserialize channel id");
643+
valid_channel.id = ChannelId::from(channel_id);
614644

615645
// eth adapter
616646
let mut eth_adapter = setup_eth_adapter(Some(contract_addr));
@@ -623,68 +653,4 @@ mod test {
623653

624654
assert_eq!(result, true, "should validate valid channel correctly");
625655
}
626-
627-
#[tokio::test]
628-
async fn should_generate_session_from_token_with_identity() {
629-
// setup test payload
630-
let mut eth_adapter = setup_eth_adapter(None);
631-
eth_adapter.unlock().expect("should unlock eth adapter");
632-
633-
// part of address used in initializing ganache-cli
634-
let leader_account: Address = "Df08F82De32B8d460adbE8D72043E3a7e25A3B39"
635-
.parse()
636-
.expect("failed to parse leader account");
637-
638-
let eth_adapter_address: Address = eth_adapter
639-
.whoami()
640-
.to_hex_non_prefix_string()
641-
.parse()
642-
.expect("failed to parse eth adapter address");
643-
644-
let identity_bytecode = include_str!("../test/resources/identitybytecode.json");
645-
646-
// deploy identity contract
647-
let identity_contract = Contract::deploy(eth_adapter.web3.eth(), &IDENTITY_ABI)
648-
.expect("invalid token token contract")
649-
.confirmations(0)
650-
.options(Options::with(|opt| {
651-
opt.gas_price = Some(1.into());
652-
opt.gas = Some(6_721_975.into());
653-
}))
654-
.execute(
655-
identity_bytecode,
656-
(
657-
Token::Array(vec![Token::Address(eth_adapter_address)]),
658-
Token::Array(vec![Token::Uint(1.into())]),
659-
),
660-
leader_account,
661-
)
662-
.expect("Correct parameters are passed to the constructor.")
663-
.compat()
664-
.await
665-
.expect("failed to initialize identity contract");
666-
667-
// identity contract address
668-
let identity = <[u8; 20]>::from_hex(&format!("{:?}", identity_contract.address())[2..])
669-
.expect("failed to deserialize address");
670-
671-
let payload = Payload {
672-
id: eth_adapter.whoami().to_checksum(),
673-
era: 100_000,
674-
address: format!("{:?}", leader_account),
675-
identity: Some(identity),
676-
};
677-
678-
let wallet = eth_adapter.wallet.clone();
679-
let response = ewt_sign(&wallet.unwrap(), &eth_adapter.keystore_pwd, &payload)
680-
.expect("failed to generate ewt signature");
681-
682-
// verify since its with identity
683-
let session = eth_adapter
684-
.session_from_token(&response)
685-
.await
686-
.expect("failed generate session");
687-
688-
assert_eq!(session.uid.inner(), &identity);
689-
}
690656
}

0 commit comments

Comments
 (0)