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
use std::path::PathBuf;
use coins_bip39::{English, Mnemonic};
use k256::SecretKey;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::{
secret::{Secret, SecretUrl},
Target,
};
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema, Clone)]
#[serde(deny_unknown_fields)]
pub struct NetworkProfile {
#[serde(skip_serializing_if = "Option::is_none")]
pub ethereum: Option<EthereumConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub avalanche: Option<AvalancheConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub polygon: Option<PolygonConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ava_subnet: Option<AvalancheConfig>,
}
impl NetworkProfile {
pub fn get(&self, name: Target) -> Option<EndpointConfig> {
match name {
Target::Ethereum => self.ethereum.clone().map(EndpointConfig::Eth),
Target::Avalanche => self.avalanche.clone().map(EndpointConfig::Ava),
Target::Polygon => self.polygon.clone().map(EndpointConfig::Poly),
Target::AvaSubnet => self
.ava_subnet
.clone()
.map(AvalancheConfig::with_default_subnet)
.map(EndpointConfig::AvaSub),
}
}
}
#[derive(Clone, Debug)]
pub enum EndpointConfig {
Eth(EthereumConfig),
Ava(AvalancheConfig),
Poly(PolygonConfig),
AvaSub(AvalancheConfig),
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MnemonicConfig {
pub seed: Secret<Mnemonic<English>>,
#[serde(default = "one")]
pub account_count: u16,
#[serde(default = "default_derivation_path")]
pub derivation_path: String,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct KeystoreConfig {
pub file: PathBuf,
pub password: Secret,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PrivateKeyConfig {
pub hex: Secret<SecretKey>,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub enum CredConfig {
#[serde(rename = "mnemonic")]
Mnemonic(MnemonicConfig),
#[serde(rename = "keystore")]
Keystore(KeystoreConfig),
#[serde(rename = "private_key")]
PrivateKey(PrivateKeyConfig),
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ProxyConfig {
pub port: u16,
pub creds: Vec<CredConfig>,
pub chain_id: u32,
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CommonConfig {
pub url: SecretUrl,
#[serde(default = "default_true")]
pub autostart: bool,
pub proxy: Option<ProxyConfig>,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct SubnetInfo {
pub vm_name: String,
pub vm_id: String,
pub chain_id: u32,
pub blockchain_id: String,
}
impl Default for SubnetInfo {
fn default() -> Self {
Self {
vm_name: "cubisttestsubnet".into(),
vm_id: "koY1rHkeQ4E8mLjxQwVmq93e7F9utQejpSVFidEqZfFmGrWQ1".into(),
chain_id: 23456,
blockchain_id: "2FQZ2GMqphsQ8jpXa6ttFYBHZwso7LstGTDigQHPDh3ySHySNV".into(),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct AvalancheConfig {
#[serde(flatten)]
pub common: CommonConfig,
#[serde(default = "default_ava_nodes")]
pub num_nodes: u16,
#[serde(default)]
pub subnets: Vec<SubnetInfo>,
}
impl AvalancheConfig {
pub fn with_default_subnet(self) -> Self {
if self.subnets.is_empty() {
AvalancheConfig {
subnets: vec![Default::default()],
..self
}
} else {
self
}
}
const DEFAULT_AVALANCHE_CHAIN_ID: u32 = 43112;
pub fn eth_endpoint_and_chain_id(&self) -> (String, u32) {
let (blockchain_id, chain_id) = if let Some(sub) = self.subnets.first() {
(sub.blockchain_id.as_str(), sub.chain_id)
} else {
("C", Self::DEFAULT_AVALANCHE_CHAIN_ID)
};
(format!("ext/bc/{blockchain_id}/rpc"), chain_id)
}
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PolygonConfig {
#[serde(flatten)]
pub common: CommonConfig,
#[serde(default = "default_local_accounts")]
pub local_accounts: Vec<CredConfig>,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct EthereumConfig {
#[serde(flatten)]
pub common: CommonConfig,
#[serde(default = "default_mnemonic_config")]
pub bootstrap_mnemonic: MnemonicConfig,
}
pub const DEFAULT_ETH_DERIVATION_PATH_PREFIX: &str = "m/44'/60'/0'/0/";
fn default_derivation_path() -> String {
DEFAULT_ETH_DERIVATION_PATH_PREFIX.into()
}
fn default_mnemonic() -> String {
"test test test test test test test test test test test junk".into()
}
fn one() -> u16 {
1
}
fn default_ava_nodes() -> u16 {
5
}
fn default_true() -> bool {
true
}
fn default_mnemonic_config() -> MnemonicConfig {
MnemonicConfig {
seed: default_mnemonic().into(),
account_count: 1,
derivation_path: default_derivation_path(),
}
}
fn default_local_accounts() -> Vec<CredConfig> {
vec![CredConfig::Mnemonic(default_mnemonic_config())]
}
#[cfg(test)]
mod test {
use coins_bip39::{English, Mnemonic};
use serde_json::json;
use crate::secret::{
SecretKind, INVALID_MNEMONIC_ERR, INVALID_PRIVATE_KEY_ERR, INVALID_PRIVATE_KEY_HEX_ERR,
};
use super::{MnemonicConfig, PolygonConfig, PrivateKeyConfig, ProxyConfig};
use secrecy::ExposeSecret;
#[test]
fn serde_mnemonic_valid() {
let m: String = Mnemonic::<English>::new(&mut rand::thread_rng())
.to_phrase()
.unwrap();
let json = json!({ "seed": { "secret": m } });
let mc: MnemonicConfig = serde_json::from_value(json).unwrap();
let sec = mc.seed.load().unwrap();
assert_eq!(&m, sec.expose_secret());
}
#[test]
fn serde_mnemonic_invalid() {
let m: String = "blah blah truc".into();
let json = json!({ "seed": { "secret": m } });
match serde_json::from_value::<MnemonicConfig>(json) {
Ok(_) => panic!("String '{m}' is not a valid bip39 phrase and thus should be rejected"),
Err(e) => assert!(e.to_string().contains(INVALID_MNEMONIC_ERR), "{e}"),
};
}
#[test]
fn serde_proxy_config_invalid_mnemonic() {
let m: String = "blah blah truc".into();
let json = json!({
"port": 12345,
"creds": [{ "mnemonic": { "seed": { "secret": m } } }],
"chain_id": 23456,
});
match serde_json::from_value::<ProxyConfig>(json) {
Ok(_) => panic!("String '{m}' is not a valid bip39 phrase and thus should be rejected"),
Err(e) => assert!(e.to_string().contains(INVALID_MNEMONIC_ERR), "{e}"),
};
}
#[test]
fn serde_polygon_config_invalid_mnemonic() {
let m: String = "blah blah truc".into();
let json = json!({
"url": "http://localhost:12345",
"local_accounts": [{ "mnemonic": { "seed": { "secret": m } } }],
});
match serde_json::from_value::<PolygonConfig>(json) {
Ok(_) => panic!("String '{m}' is not a valid bip39 phrase and thus should be rejected"),
Err(e) => assert!(e.to_string().contains(INVALID_MNEMONIC_ERR), "{e}"),
};
}
#[test]
fn serde_mnemonic_cannot_load() {
let json = json!({ "seed": { "env": "missing_env_var_123_not_found" } });
let mc: MnemonicConfig = serde_json::from_value(json).unwrap();
assert!(matches!(mc.seed.inner, SecretKind::EnvVar { .. }));
}
#[test]
fn serde_private_key_invalid_hex() {
let key: String = "blah blah truc".into();
let json = json!({ "hex": { "secret": key } });
match serde_json::from_value::<PrivateKeyConfig>(json) {
Ok(_) => panic!("String '{key}' is not a valid hex string and thus should be rejected"),
Err(e) => assert!(e.to_string().contains(INVALID_PRIVATE_KEY_HEX_ERR)),
};
}
#[test]
fn serde_private_key_invalid_k2561() {
let key: String = "FEEDF00D".into();
let json = json!({ "hex": { "secret": key } });
match serde_json::from_value::<PrivateKeyConfig>(json) {
Ok(_) => panic!("String '{key}' is not a valid K-256 key and thus should be rejected"),
Err(e) => assert!(e.to_string().contains(INVALID_PRIVATE_KEY_ERR)),
};
}
#[test]
fn serde_private_key_valid_k2561() {
let key = "56289e99c94b6912bfc12adc093c9b51124f0dc54ac7a766b2bc5ccf558d8027";
let json = json!({ "hex": { "secret": key } });
let pk = serde_json::from_value::<PrivateKeyConfig>(json).unwrap();
assert!(matches!(pk.hex.inner, SecretKind::PlainText { .. }));
let loaded = pk.hex.load().unwrap();
assert_eq!(key, loaded.expose_secret());
}
}