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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::{collections::BTreeMap, sync::Arc};
use cubist_config::network::CredConfig;
use ethers::providers::{Http, Middleware, Provider, ProviderError};
use ethers::signers::LocalWallet;
use ethers::types::{transaction::eip2718::TypedTransaction, Signature};
use ethers::types::{BlockNumber, TransactionRequest, U256};
use ethers::utils::rlp::Rlp;
use ethers::{
abi::Address,
prelude::k256::ecdsa::SigningKey,
signers::{coins_bip39::English, MnemonicBuilder, Signer, Wallet},
};
use futures::{SinkExt, TryStreamExt};
use hyper::Uri;
use secrecy::ExposeSecret;
use serde::Deserialize;
use serde_json::{json, to_value, Value};
use crate::jrpc::IdReq;
use crate::{
connector::{connect, ConcretePair},
jrpc::{self, response, ErrorCode},
FatalErr, JrpcRequest, JsonRpcErr, Pair,
};
use super::switch;
fn to_wallets(cred: &CredConfig) -> Result<Vec<LocalWallet>, FatalErr> {
fn to_fatal(e: cubist_config::ConfigError) -> FatalErr {
FatalErr::ReadSecretError(format!("{e}"))
}
match cred {
CredConfig::Mnemonic(m) => {
let mn = m.seed.load().map_err(to_fatal)?;
let mut builder =
MnemonicBuilder::<English>::default().phrase(mn.expose_secret().as_str());
let mut out = Vec::with_capacity(m.account_count as usize);
for i in 0..m.account_count {
builder = builder.derivation_path(format!("{}{i}", m.derivation_path).as_str())?;
out.push(builder.build()?);
}
Ok(out)
}
CredConfig::Keystore(ks) => {
let password = ks.password.load().map_err(to_fatal)?;
let wallet =
Wallet::<SigningKey>::decrypt_keystore(&ks.file, password.expose_secret())?;
Ok(vec![wallet])
}
CredConfig::PrivateKey(pk) => {
let private_key = pk.hex.load().map_err(to_fatal)?;
let wallet = LocalWallet::from_str(private_key.expose_secret())?;
Ok(vec![wallet])
}
}
}
pub fn build_wallets<'a>(
creds: impl Iterator<Item = &'a CredConfig>,
) -> Result<Vec<LocalWallet>, FatalErr> {
let wallets = creds
.map(to_wallets)
.collect::<Result<Vec<_>, _>>()?
.into_iter()
.flatten()
.collect();
Ok(wallets)
}
#[derive(Debug, Clone)]
pub struct EthProxyConfig {
pub creds: Vec<CredConfig>,
pub onchain_uri: Option<Uri>,
pub chain_id: u32,
}
const ETH_SEND_TRANSACTION: &str = "eth_sendTransaction";
enum CredMethod {
Accounts,
SignTransaction,
}
impl CredMethod {
fn from_str(s: &str) -> Option<Self> {
match s {
"eth_accounts" => Some(Self::Accounts),
"eth_signTransaction" => Some(Self::SignTransaction),
_ => None,
}
}
}
#[derive(Debug)]
pub struct Accounts {
pub(crate) wallets: BTreeMap<Address, LocalWallet>,
}
impl Accounts {
pub fn from_cfg(cfg: &EthProxyConfig) -> Result<Self, FatalErr> {
Ok(Self {
wallets: build_wallets(cfg.creds.iter())?
.into_iter()
.map(|w| (w.address().to_owned(), w.with_chain_id(cfg.chain_id)))
.collect(),
})
}
}
pub struct CredProxy {
provider: Option<Provider<Http>>,
nonce_counter: HashMap<Address, AtomicU64>,
accounts: Accounts,
}
impl CredProxy {
pub fn from_cfg(cfg: &EthProxyConfig) -> Result<Self, FatalErr> {
let accounts = Accounts::from_cfg(cfg)?;
let uri = cfg.onchain_uri.clone().map(|uri| {
let scheme = match &uri.scheme_str() {
Some("http" | "ws") => "http".parse().unwrap(),
_ => "https".parse().unwrap(),
};
let mut parts = uri.into_parts();
parts.scheme = Some(scheme);
Uri::from_parts(parts).unwrap()
});
let provider = uri
.as_ref()
.map(Uri::to_string)
.map(Provider::try_from)
.transpose()?;
let nonce_counter = accounts
.wallets
.iter()
.map(|(addr, _)| (*addr, AtomicU64::new(0)))
.collect();
Ok(Self {
accounts,
provider,
nonce_counter,
})
}
pub fn wrap(
self: &Arc<CredProxy>,
endpoint: impl Pair<Value, JrpcRequest> + 'static,
) -> impl Pair<Value, JrpcRequest> {
let (handled, pass) = switch(endpoint, |res| {
res.as_ref()
.ok()
.map(|req| CredMethod::from_str(&req.method).is_some())
.unwrap_or(false)
});
let pair = self.handler_pair();
tokio::spawn(async move {
if let Err(e) = connect(handled, pair).await {
tracing::debug!("Shutting down credential handler with error: {e}")
}
});
let proxy = self.clone();
pass.and_then(move |req: JrpcRequest| {
let proxy = proxy.clone();
async move {
if req.method != ETH_SEND_TRANSACTION {
tracing::debug!("passing through: {req}");
return Ok(req);
}
tracing::debug!("Converting sendTransaction to sendRawTransaction: {req}...");
let send = proxy.eth_send_transaction(req).await;
tracing::debug!("Converted transaction");
send
}
})
}
fn handler_pair(self: &Arc<CredProxy>) -> impl Pair<JrpcRequest, Value> {
let ref_self = self.clone();
ConcretePair::pipe()
.sink_err_into()
.and_then(move |req: JrpcRequest| {
let ref_self = ref_self.clone();
async move {
match CredMethod::from_str(&req.method)
.expect("cred_handler should only be invoked with cred methods")
{
CredMethod::Accounts => ref_self.eth_accounts(req),
CredMethod::SignTransaction => ref_self.eth_sign_transaction(req).await,
}
}
})
}
async fn nonce_for_account(&self, a: Address) -> Result<U256, ProviderError> {
let next_available = &self.nonce_counter[&a];
let load_and_increment = || Ok(next_available.fetch_add(1u64, Ordering::SeqCst).into());
if next_available.load(Ordering::SeqCst) > 0 {
return load_and_increment();
}
let provider = if let Some(provider) = &self.provider {
provider
} else {
return Ok(0.into());
};
let trx_count = provider
.get_transaction_count(a, Some(BlockNumber::Pending.into()))
.await?;
if trx_count >= U256::from(u64::MAX) {
return Ok(trx_count);
}
let trx_count64 = trx_count.as_u64();
let winner = next_available
.compare_exchange(0, trx_count64 + 1, Ordering::SeqCst, Ordering::SeqCst)
.is_ok();
if winner {
return Ok(trx_count);
}
load_and_increment()
}
fn eth_accounts(&self, req: JrpcRequest) -> Result<Value, JsonRpcErr> {
let accounts: Vec<_> = self
.accounts
.wallets
.values()
.map(Signer::address)
.collect();
response(req.id, json!(accounts))
}
async fn sign_transaction(
&self,
id: IdReq,
mut transaction: TypedTransaction,
) -> Result<(Signature, TypedTransaction), JsonRpcErr> {
let from_address = *transaction.from().ok_or_else(|| {
jrpc::error(
ErrorCode::InvalidParams,
"'from' field is required",
id.clone(),
"",
)
})?;
let wallet = self.accounts.wallets.get(&from_address).ok_or_else(|| {
jrpc::error(
ErrorCode::InvalidRequest,
format!("No wallet found for sender '{}'", from_address),
id.clone(),
"",
)
})?;
tracing::debug!("Setting chain id to: {}", wallet.chain_id());
transaction.set_chain_id(wallet.chain_id());
match transaction.nonce() {
None => {
tracing::debug!("Setting nonce for trx {:?}", transaction);
transaction.set_nonce(
self.nonce_for_account(from_address)
.await
.map_err(|e| jrpc::error(ErrorCode::InternalError, e, id.clone(), ""))?,
);
}
Some(nonce) => {
let nonce64 = nonce.as_u64();
let _ = self.nonce_counter[&from_address].compare_exchange(
nonce64,
nonce64 + 1,
Ordering::SeqCst,
Ordering::SeqCst,
);
}
}
if let Some(provider) = &self.provider {
provider
.fill_transaction(&mut transaction, None)
.await
.map_err(|e| {
jrpc::error(
ErrorCode::GasEstimationError,
"Unable to estimate gas prices".to_string(),
id.clone(),
e,
)
})?;
}
tracing::debug!("Signing trx {:?}", transaction);
let sig = wallet.sign_transaction(&transaction).await.map_err(|e| {
jrpc::error(
ErrorCode::InternalError,
"Failed to sign transaction",
id.clone(),
e,
)
})?;
Ok((sig, transaction))
}
async fn eth_send_transaction(&self, req: JrpcRequest) -> Result<JrpcRequest, JsonRpcErr> {
let param_value = req.params.unwrap_or(Value::Null);
let params: SignTransactionParams = serde_json::from_value(param_value)?;
let (sig, transaction) = self
.sign_transaction(req.id.clone(), params.transaction.into())
.await?;
let signed = transaction.rlp_signed(&sig);
tracing::debug!(
"Re-decoded: {:?}",
TypedTransaction::decode_signed(&Rlp::new(&signed))
);
Ok(JrpcRequest::with_params(
req.id,
"eth_sendRawTransaction",
to_value(vec![signed])?,
))
}
async fn eth_sign_transaction(&self, req: JrpcRequest) -> Result<Value, JsonRpcErr> {
let param_value = req.params.unwrap_or(Value::Null);
let params: SignTransactionParams = serde_json::from_value(param_value)?;
let (sig, _) = self
.sign_transaction(req.id.clone(), params.transaction.into())
.await?;
response(req.id, json!(sig))
}
}
#[derive(Debug, Deserialize)]
struct SignTransactionParams {
transaction: TransactionRequest,
}
#[cfg(test)]
mod test {
use std::{str::FromStr, sync::Arc};
use super::{CredConfig, CredProxy, EthProxyConfig};
use crate::{
connector::passthru_pair, jrpc::no_response, transformer::eth_creds::ETH_SEND_TRANSACTION,
JrpcRequest, JsonRpcErr, Pair,
};
use cubist_config::network::{
KeystoreConfig, MnemonicConfig, PrivateKeyConfig, DEFAULT_ETH_DERIVATION_PATH_PREFIX,
};
use ethers::{
core::rand::thread_rng,
signers::{Signer, Wallet},
types::{
transaction::eip2718::TypedTransaction, Address, Bytes, Eip1559TransactionRequest,
Signature, TransactionRequest,
},
utils::rlp::Rlp,
};
use futures::{FutureExt, SinkExt, StreamExt};
use rstest::rstest;
use serde_json::{from_value, to_value, Value};
use tempfile::tempdir;
pub const MNEMONIC: &str = "test test test test test test test test test test test junk";
#[rstest]
#[case::dp(true)]
#[case::nodp(false)]
fn mnemonic_accounts(#[case] use_dp: bool) {
let proxy = CredProxy::from_cfg(&EthProxyConfig {
onchain_uri: None,
chain_id: 1,
creds: vec![CredConfig::Mnemonic(MnemonicConfig {
seed: MNEMONIC.to_string().into(),
account_count: 2,
derivation_path: if use_dp {
String::from("m/1'/2'/3'/4/")
} else {
DEFAULT_ETH_DERIVATION_PATH_PREFIX.to_string()
},
})],
})
.unwrap();
let request = JrpcRequest::new(1, "eth_accounts");
let accounts = proxy.eth_accounts(request).unwrap();
assert_eq!(
accounts["result"][0],
if use_dp {
"0x5bd47977365798dd4b58711e2a5a20da7824618f"
} else {
"0x70997970c51812dc3a010c7d01b50e0d17dc79c8"
}
)
}
#[test]
fn keystore_account() {
let password = "hunter2".to_string();
let name = "keyfile.json".to_string();
let tmpdir = tempdir()
.expect("Failed to create temporary directory")
.into_path();
let (wallet, _) = Wallet::new_keystore(
tmpdir.clone(),
&mut thread_rng(),
password.clone(),
Some(&name),
)
.expect("Failed to create wallet");
let proxy = CredProxy::from_cfg(&EthProxyConfig {
onchain_uri: None,
chain_id: 1,
creds: vec![CredConfig::Keystore(KeystoreConfig {
file: tmpdir.join(name),
password: password.into(),
})],
})
.expect("Failed to create proxy");
let request = JrpcRequest::new(1, "eth_accounts");
let accounts = proxy.eth_accounts(request).unwrap();
assert_eq!(
accounts["result"][0].as_str().expect("Expected string"),
format!("0x{}", hex::encode(wallet.address().as_fixed_bytes()))
)
}
fn io_pair() -> (
impl Pair<JrpcRequest, Value, JsonRpcErr>,
impl Pair<Value, JrpcRequest, JsonRpcErr>,
) {
let config = EthProxyConfig {
onchain_uri: None,
chain_id: 1048576,
creds: vec![CredConfig::PrivateKey(PrivateKeyConfig {
hex: "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef"
.to_string()
.into(),
})],
};
let (testin, testout) = passthru_pair::<JrpcRequest, Value, JsonRpcErr>();
let proxy = Arc::new(CredProxy::from_cfg(&config).unwrap());
let testout = proxy.wrap(testout);
(Box::pin(testin), Box::pin(testout))
}
const FIRST_ACCOUNT: &str = "0xc96aaa54e2d44c299564da76e1cd3184a2386b8d";
async fn test_transaction<T: Into<TypedTransaction>>(
testin: &mut (impl Pair<JrpcRequest, Value> + Unpin),
testout: &mut (impl Pair<Value, JrpcRequest> + Unpin),
transaction: T,
) {
let transaction: TypedTransaction = transaction.into();
let req = JrpcRequest::with_params(
1,
"eth_signTransaction",
vec![to_value(transaction.clone()).unwrap()],
);
testin.send(Ok(req)).await.unwrap();
let signature: Signature =
from_value(dbg!(testin.next().await).unwrap().unwrap()["result"].clone()).unwrap();
assert!(testout.next().now_or_never().is_none());
assert!(testin.next().now_or_never().is_none());
let req = JrpcRequest::with_params(
1,
ETH_SEND_TRANSACTION,
vec![to_value(transaction.clone()).unwrap()],
);
testin.send(Ok(req)).await.unwrap();
let send_raw = testout.next().await.unwrap().unwrap();
assert_eq!(send_raw.method, "eth_sendRawTransaction");
let raw_bytes: Bytes = from_value(dbg!(send_raw.params).unwrap()[0].clone()).unwrap();
let (raw_transaction, raw_signature) =
TypedTransaction::decode_signed(&Rlp::new(&raw_bytes)).unwrap();
match (&transaction, &raw_transaction) {
(
TypedTransaction::Legacy(TransactionRequest {
from: in_from,
value: in_value,
..
}),
TypedTransaction::Legacy(TransactionRequest {
from: out_from,
value: out_value,
..
}),
) => {
assert_eq!(signature, raw_signature);
assert_eq!(in_from, out_from);
assert_eq!(in_value, out_value);
}
(
TypedTransaction::Eip1559(Eip1559TransactionRequest {
from: _in_from,
value: in_value,
..
}),
TypedTransaction::Eip1559(Eip1559TransactionRequest {
from: _out_from,
value: out_value,
..
}),
) => {
assert_eq!(in_value, out_value);
}
(_, _) => panic!(
"Transactions {:?} and {:?} are not matching",
transaction, raw_transaction
),
};
assert!(testout.next().now_or_never().is_none());
assert!(testin.next().now_or_never().is_none());
}
#[tokio::test]
async fn test_error() {
let (mut testin, mut testout) = io_pair();
let err = no_response(Some(Value::Null));
testin.send(Err(err)).await.unwrap();
assert!(matches!(
testout.next().await,
Some(Err(JsonRpcErr::Jrpc(_)))
));
assert!(testout.next().now_or_never().is_none());
assert!(testin.next().now_or_never().is_none());
}
#[tokio::test]
async fn test_accounts() {
let (mut testin, mut testout) = io_pair();
let req = JrpcRequest::new(1, "eth_accounts");
testin.send(Ok(req)).await.unwrap();
assert_eq!(
testin.next().await.unwrap().unwrap()["result"][0],
FIRST_ACCOUNT,
);
assert!(testout.next().now_or_never().is_none());
assert!(testin.next().now_or_never().is_none());
}
#[tokio::test]
async fn test_legacy() {
let (mut testin, mut testout) = io_pair();
let transaction = TransactionRequest::new()
.from(Address::from_str(FIRST_ACCOUNT).unwrap())
.value(42);
test_transaction(&mut testin, &mut testout, transaction).await;
}
#[tokio::test]
async fn test_other() {
let (mut testin, mut testout) = io_pair();
let req = JrpcRequest::new(2, "noop");
testin.send(Ok(req)).await.unwrap();
let resp = testout.next().await.unwrap().unwrap();
assert_eq!((resp.method.as_str(), resp.id), ("noop", 2.into()));
assert!(testout.next().now_or_never().is_none());
assert!(testin.next().now_or_never().is_none());
}
}