1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
use failure::Error;
use hex::FromHex;
use std::time;
use std::str;
use tiny_keccak::Keccak;
use web3;
use web3::types::BlockNumber;
use web3::futures::Future;
use web3::contract::{Contract, Options};
use web3::types::{Address, U256, Log};
use web3::types::FilterBuilder;
use web3::transports::Http;
use web3::Web3;
use web3::contract::tokens::Tokenize;
use std::fs::File;
use std::io::prelude::*;
use serde_json;
use serde_json::{Value};
pub trait Keccak256<T> {
fn keccak256(&self) -> T where T: Sized;
}
impl Keccak256<[u8; 32]> for [u8] {
fn keccak256(&self) -> [u8; 32] {
let mut keccak = Keccak::new_keccak256();
let mut result = [0u8; 32];
keccak.update(self);
keccak.finalize(&mut result);
result
}
}
pub struct DeployParams{
pub deployer : Address,
pub abi : String,
pub gas_limit : U256,
pub bytecode : String,
pub poll_interval : u64,
pub confirmations : usize,
}
impl DeployParams{
pub fn new(deployer : String, abi : String,bytecode: String, gas_limit : String, poll_interval : u64, confirmations : usize)-> Self{
let gas : U256 = U256::from_dec_str(&gas_limit).unwrap();
let deployer_addr: Address = deployer
.parse()
.expect("unable to parse contract address");
DeployParams{
deployer : deployer_addr,
abi : abi,
gas_limit : gas,
bytecode : bytecode,
poll_interval : poll_interval,
confirmations : confirmations
}
}
}
pub fn load_contract_abi_bytecode(path: &str) -> Result<(String,String),Error>{
let mut f = File::open(path)
.expect("file not found.");
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect("canno't read file");
let contract_data : Value = serde_json::from_str(&contents)
.expect("unable to parse JSON built contract");
let abi = serde_json::to_string(&contract_data["abi"])
.expect("unable to find the abi key at the root of the JSON built contract");
let bytecode = serde_json::to_string(&contract_data["bytecode"])
.expect("unable to find the abi key at the root of the JSON built contract");
Ok((abi,bytecode))
}
pub fn connect( url : &str)->Result<(web3::transports::EventLoopHandle, Web3<Http>),Error>{
let (_eloop, http) = web3::transports::Http::new(url)
.expect("unable to create Web3 HTTP provider");
let w3 = web3::Web3::new(http);
Ok((_eloop, w3))
}
pub fn deployed_contract(web3: &Web3<Http>, contract_addr: Address , abi : &String)->Result<Contract<Http>,Error>{
let abi_str = abi.clone();
let contract = Contract::from_json(
web3.eth(),
contract_addr,
abi_str.as_bytes(),
).expect("unable to fetch the deployed contract on the Ethereum provider");
Ok(contract)
}
pub fn trunace_bytecode(bytecode : &String)->Result<Vec<u8>,Error>{
let b = bytecode.as_bytes();
let sliced = &b[3..b.len()-1];
let result = str::from_utf8(&sliced.to_vec()).unwrap().from_hex()?;
Ok(result)
}
pub fn deploy_contract<P>(web3 : &Web3<Http>, tx_params : DeployParams ,ctor_params : P)-> Result<Contract<Http>,Error>
where
P : Tokenize
{
let bytecode : Vec<u8> = trunace_bytecode(&tx_params.bytecode).expect("error parsing bytecode to bytes");
let deployer_addr = tx_params.deployer;
let mut options = Options::default();
options.gas = Some(tx_params.gas_limit);
let builder = Contract::deploy(
web3.eth(),
tx_params.abi.as_bytes(),
).unwrap()
.confirmations(tx_params.confirmations)
.poll_interval(time::Duration::from_secs(tx_params.poll_interval));
let contract = builder
.options(options)
.execute(
bytecode,
ctor_params,
deployer_addr,
)
.expect("Cannot deploy contract abi")
.wait()
.unwrap();
println!("deployed contract at address = {}",contract.address());
Ok(contract)
}
pub fn address_to_string_addr(addr : &Address)->String{
let mut addr = format!("{:?}", addr);
addr = addr[2..].to_string();
addr
}
pub fn to_keccak256(value : Vec<u8>)->[u8; 32]{
return value.as_slice().keccak256();
}
pub fn get_accounts(url: &str)->Result<Vec<Address>,Error>{
let ( _eloop,w3 ) =connect(url).unwrap();
let accounts = w3.eth().accounts().wait().unwrap();
Ok(accounts)
}
fn build_event_fuilder(event_name : String,contract_addr : Option<String>)->web3::types::Filter{
let with_addr = contract_addr.is_some();
let filter = FilterBuilder::default()
.topics(Some(vec![
event_name.as_bytes().keccak256().into(),
]),
None,
None,
None,
)
.from_block(BlockNumber::Earliest)
.to_block(BlockNumber::Latest);
if with_addr {
filter.address(vec![contract_addr.expect("[-] filter: error parsing ethereum address").parse().unwrap()]).build()
}else{
filter.build()
}
}
pub fn filter_blocks(contract_addr : Option<String> ,event_name : String ,url : String)->Result<Vec<Log>,Error>{
let (_eloop,w3) = connect(&url.as_str())
.expect("cannot connect to ethereum");
let filter = build_event_fuilder(event_name,contract_addr);
let logs = w3.eth().logs(filter).wait().expect("[-] error getting logs");
Ok(logs)
}
#[cfg(test)]
mod test {
use web3_utils;
use std::collections::HashMap;
use super::*;
use web3_utils::w3utils;
use std::env;
fn get_node_url()-> String {
env::var("NODE_URL").unwrap_or("http://localhost:8545".to_string())
}
fn get_contract(ctype : &String)->(String,String){
let path = env::current_dir().unwrap();
println!("The current directory is {}", path.display());
let EnigmaToken = "./src/tests/web3_tests/contracts/EnigmaToken.json";
let Enigma = "./src/tests/web3_tests/contracts/Enigma.json";
let Dummy = "./src/tests/web3_tests/contracts/Dummy.json";
let to_load = match ctype.as_ref() {
"EnigmaToken" => {
EnigmaToken
},
"Enigma"=> {
Enigma
},
"Dummy"=> {
Dummy
},
_ => {
""
}
};
assert_ne!(to_load,"" , "wrong contract type");
let (abi,bytecode) = w3utils::load_contract_abi_bytecode(to_load).unwrap();
(abi,bytecode)
}
fn get_deploy_params(accounts : &Vec<Address>,ctype : &str)->w3utils::DeployParams{
let deployer = w3utils::address_to_string_addr(&accounts[0]);
let gas_limit = "5999999";
let poll_interval : u64 = 1;
let confirmations : usize = 0;
let (abi,bytecode) = get_contract(&ctype.to_string());
w3utils::DeployParams::new(
deployer.to_string(),
abi,bytecode,
gas_limit.to_string(),
poll_interval,
confirmations)
}
fn connect()->(web3::transports::EventLoopHandle, Web3<Http>,Vec<Address>){
let uri = get_node_url();
let (eloop,w3) = w3utils::connect(&uri).unwrap();
let accounts = w3.eth().accounts().wait().unwrap();
(eloop,w3, accounts)
}
fn deploy_dummy(w3 : &Web3<Http>, accounts : &Vec<Address>)->Contract<Http>{
let tx = get_deploy_params(accounts,"Dummy");
let contract = w3utils::deploy_contract(&w3, tx,()).unwrap();
contract
}
#[test]
fn test_deploy_dummy_contract(){
let (eloop,w3,accounts) = connect();
let contract = deploy_dummy(&w3,&accounts);
let result = contract.query("mine", (), None, Options::default(), None);
let param : U256 = result.wait().unwrap();
assert_eq!(param.as_u64(), 1);
}
#[test]
fn test_deploy_enigma_contract(){
let account = String::from("627306090abab3a6e1400e9345bc60c78a8bef57");
let fake_input: Address = account.parse().expect("unable to parse account address");
let fake_input = (fake_input,fake_input);
let (eloop,w3,accounts) = connect();
let tx = get_deploy_params(&accounts,"Enigma");
w3utils::deploy_contract(&w3, tx,fake_input).unwrap();
}
#[test]
fn test_deployed_contract(){
let (eloop,w3,accounts) = connect();
let contract = deploy_dummy(&w3,&accounts);
let address = contract.address();
let (abi,bytecode) = get_contract(&String::from("Dummy"));
let contract = w3utils::deployed_contract(&w3, address , &abi).unwrap();
let result = contract.query("mine", (), None, Options::default(), None);
let param : U256 = result.wait().unwrap();
assert_eq!(param.as_u64(), 1);
}
}