/
handler.rs
1479 lines (1285 loc) · 53 KB
/
handler.rs
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use bytes::BytesMut;
use prost::Message;
use serde_json::Value;
use std::fs;
use std::io::Read;
use std::path::Path;
use std::str::FromStr;
use tcx_eos::encode_eos_wif;
use tcx_eth2::transaction::{SignBlsToExecutionChangeParam, SignBlsToExecutionChangeResult};
use tcx_keystore::keystore::IdentityNetwork;
use tcx_migration::legacy_ipfs;
use tcx_common::{FromHex, ToHex};
use tcx_primitive::{
private_key_without_version, PrivateKey, Secp256k1PrivateKey, Sr25519PrivateKey,
TypedPrivateKey, TypedPublicKey,
};
use tcx_btc_kin::WIFDisplay;
use tcx_keystore::{
fingerprint_from_mnemonic, fingerprint_from_private_key, identity, Keystore, KeystoreGuard,
SignatureParameters, Signer,
};
use tcx_keystore::{Account, HdKeystore, Metadata, PrivateKeystore, Source};
use anyhow::{anyhow, ensure};
use tcx_crypto::{XPUB_COMMON_IV, XPUB_COMMON_KEY_128};
use tcx_filecoin::KeyInfo;
use crate::api::derive_accounts_param::Derivation;
use crate::api::{
self, export_private_key_param, AccountResponse, BackupResult, CreateKeystoreParam,
DecryptDataFromIpfsParam, DecryptDataFromIpfsResult, DeriveAccountsParam, DeriveAccountsResult,
DeriveSubAccountsParam, DeriveSubAccountsResult, DerivedKeyResult, EncryptDataToIpfsParam,
EncryptDataToIpfsResult, ExistsJsonParam, ExistsKeystoreResult, ExistsMnemonicParam,
ExistsPrivateKeyParam, ExportJsonParam, ExportJsonResult, ExportMnemonicParam,
ExportMnemonicResult, ExportPrivateKeyParam, ExportPrivateKeyResult, GeneralResult,
GetExtendedPublicKeysParam, GetExtendedPublicKeysResult, GetPublicKeysParam,
GetPublicKeysResult, ImportJsonParam, ImportMnemonicParam, ImportPrivateKeyParam,
ImportPrivateKeyResult, KeystoreResult, MnemonicToPublicKeyParam, MnemonicToPublicKeyResult,
ScanKeystoresResult, SignAuthenticationMessageParam, SignAuthenticationMessageResult,
SignHashesParam, SignHashesResult, WalletKeyParam,
};
use crate::api::{EthBatchPersonalSignParam, EthBatchPersonalSignResult};
use crate::api::{InitTokenCoreXParam, SignParam};
use crate::error_handling::Result;
use crate::filemanager::{
cache_keystore, clean_keystore, flush_keystore, KEYSTORE_BASE_DIR, LEGACY_WALLET_FILE_DIR,
WALLET_FILE_DIR, WALLET_V1_DIR, WALLET_V2_DIR,
};
use crate::filemanager::{delete_keystore_file, KEYSTORE_MAP};
use crate::IS_DEBUG;
use base58::FromBase58;
use tcx_keystore::tcx_ensure;
use tcx_constants::coin_info::coin_info_from_param;
use tcx_constants::{CoinInfo, CurveType};
use tcx_crypto::aes::cbc::encrypt_pkcs7;
use tcx_crypto::KDF_ROUNDS;
use tcx_eth::signer::batch_personal_sign;
use tcx_keystore::{MessageSigner, TransactionSigner};
use tcx_primitive::Ss58Codec;
use tcx_substrate::{decode_substrate_keystore, encode_substrate_keystore, SubstrateKeystore};
use tcx_migration::migration::LegacyKeystore;
use tcx_primitive::TypedDeterministicPublicKey;
use tcx_tezos::{encode_tezos_private_key, parse_tezos_private_key};
use crate::macros::{impl_to_key, use_chains};
use crate::migration::{
read_all_identity_wallet_ids, remove_all_identity_wallets, remove_old_keystore_by_id,
};
use_chains!(
tcx_btc_kin::bitcoin,
tcx_btc_kin::omni,
tcx_btc_kin::bitcoincash,
tcx_filecoin::filecoin,
tcx_eos::eos,
tcx_ckb::nervos,
tcx_eth::ethereum,
tcx_atom::cosmos,
tcx_substrate::polkadot,
tcx_tezos::tezos,
tcx_tron::tron,
);
pub fn encode_message(msg: impl Message) -> Result<Vec<u8>> {
let mut buf = BytesMut::with_capacity(msg.encoded_len());
msg.encode(&mut buf)?;
Ok(buf.to_vec())
}
fn derive_account(keystore: &mut Keystore, derivation: &Derivation) -> Result<Account> {
let mut coin_info = coin_info_from_param(
&derivation.chain_type,
&derivation.network,
&derivation.seg_wit,
&derivation.curve,
)?;
coin_info.derivation_path = derivation.path.to_owned();
derive_account_internal(&coin_info, keystore)
}
pub fn encrypt_xpub(xpub: &str) -> Result<String> {
let key = tcx_crypto::XPUB_COMMON_KEY_128.read();
let iv = tcx_crypto::XPUB_COMMON_IV.read();
let key_bytes = Vec::from_hex(&*key)?;
let iv_bytes = Vec::from_hex(&*iv)?;
let encrypted = encrypt_pkcs7(xpub.as_bytes(), &key_bytes, &iv_bytes)?;
Ok(base64::encode(encrypted))
}
fn key_data_from_any_format_pk(pk: &str) -> Result<Vec<u8>> {
let decoded = Vec::from_hex_auto(pk);
if let Ok(bytes) = decoded {
if bytes.len() <= 64 {
Ok(bytes)
} else {
// import filecoin
Ok(KeyInfo::from_lotus(&bytes)?.decode_private_key()?)
}
} else {
private_key_without_version(pk)
}
}
fn fingerprint_from_any_format_pk(pk: &str) -> Result<String> {
let key_data = if pk.starts_with("edsk") {
parse_tezos_private_key(pk)?
} else {
key_data_from_any_format_pk(pk)?
};
fingerprint_from_private_key(&key_data)
}
fn import_private_key_internal(
param: &ImportPrivateKeyParam,
source: Option<Source>,
original: Option<String>,
) -> Result<ImportPrivateKeyResult> {
let mut founded_id: Option<String> = None;
{
let fingerprint = fingerprint_from_any_format_pk(¶m.private_key)?;
let map = KEYSTORE_MAP.read();
if let Some(founded) = map
.values()
.find(|keystore| keystore.fingerprint() == fingerprint)
{
founded_id = Some(founded.id());
}
}
if founded_id.is_some() && !param.overwrite {
return Err(anyhow!("{}", "address_already_exist"));
}
let decoded_ret = decode_private_key(¶m.private_key)?;
if !decoded_ret.network.is_empty() {
let expected_network = if param.network.is_empty() {
"MAINNET"
} else {
param.network.as_str()
};
if decoded_ret.network != expected_network {
return Err(anyhow!("{}", "private_key_network_mismatch"));
}
}
let private_key = decoded_ret.bytes.to_hex();
let meta_source = if let Some(source) = source {
source
} else {
decoded_ret.source
};
let original = if let Some(original) = original {
original
} else {
param.private_key.to_string()
};
let meta = Metadata {
name: param.name.to_string(),
password_hint: param.password_hint.to_string(),
source: meta_source,
identified_chain_types: Some(decoded_ret.chain_types.clone()),
..Metadata::default()
};
let pk_store = PrivateKeystore::from_private_key(
&private_key,
¶m.password,
decoded_ret.curve,
meta,
Some(original),
)?;
let mut keystore = Keystore::PrivateKey(pk_store);
if let Some(exist_kid) = founded_id {
keystore.set_id(&exist_kid)
}
flush_keystore(&keystore)?;
let meta = keystore.meta();
let identity = keystore.identity();
let wallet = ImportPrivateKeyResult {
id: keystore.id(),
name: meta.name.to_owned(),
source: meta_source.to_string(),
created_at: meta.timestamp,
identifier: identity.identifier.to_string(),
ipfs_id: identity.ipfs_id.to_string(),
identified_chain_types: decoded_ret.chain_types.to_owned(),
identified_network: decoded_ret.network.to_string(),
identified_curve: decoded_ret.curve.as_str().to_string(),
source_fingerprint: keystore.fingerprint().to_string(),
};
cache_keystore(keystore);
Ok(wallet)
}
struct DecodedPrivateKey {
bytes: Vec<u8>,
network: String,
curve: CurveType,
chain_types: Vec<String>,
source: Source,
}
fn decode_private_key(private_key: &str) -> Result<DecodedPrivateKey> {
let private_key_bytes: Vec<u8>;
let mut network = "".to_string();
let mut chain_types: Vec<String> = vec![];
let mut curve: CurveType = CurveType::SECP256k1;
let mut source: Source = Source::Private;
if private_key.starts_with("edsk") {
private_key_bytes = parse_tezos_private_key(private_key)?;
chain_types.push("TEZOS".to_string());
curve = CurveType::ED25519;
} else {
let decoded = Vec::from_hex_auto(private_key);
if let Ok(decoded_data) = decoded {
if decoded_data.len() == 32 {
private_key_bytes = decoded_data;
chain_types = vec![
"BITCOIN".to_string(),
"ETHEREUM".to_string(),
"BITCOINCASH".to_string(),
"LITECOIN".to_string(),
"EOS".to_string(),
"TRON".to_string(),
"FILECOIN".to_string(),
];
curve = CurveType::SECP256k1;
} else if decoded_data.len() == 64 {
let sr25519_key = Sr25519PrivateKey::from_slice(&decoded_data)?;
private_key_bytes = sr25519_key.to_bytes();
chain_types.push("KUSAMA".to_string());
chain_types.push("POLKADOT".to_string());
curve = CurveType::SR25519;
} else {
let key_info = KeyInfo::from_lotus(&decoded_data)?;
private_key_bytes = key_info.decode_private_key()?;
chain_types.push("FILECOIN".to_string());
if key_info.r#type != "secp256k1" {
curve = CurveType::BLS;
}
}
} else {
let data_len = private_key
.from_base58()
.map_err(|_| anyhow!("invalid_wif"))?
.len();
let (k1_pk, ver) = Secp256k1PrivateKey::from_ss58check_with_version(private_key)?;
private_key_bytes = k1_pk.0.to_bytes();
source = Source::Wif;
match ver[0] {
0xef => {
network = "TESTNET".to_string();
chain_types.push("BITCOIN".to_string());
chain_types.push("BITCOINCASH".to_string());
chain_types.push("LITECOIN".to_string());
}
0x80 => {
if data_len == 37 {
// EOS 1byte network + 32bytes private key + 4byte checksum = 37bytes
// EOS not use compressed suffix https://developers.eos.io/manuals/eos/v2.2/keosd/wallet-specification
network = "".to_string();
chain_types.push("EOS".to_string());
} else {
// EOS 1byte network + 32bytes private key + 1byte compressed suffix + 4byte checksum = 38bytes
network = "MAINNET".to_string();
chain_types.push("BITCOIN".to_string());
chain_types.push("BITCOINCASH".to_string());
}
}
0xb0 => {
network = "MAINNET".to_string();
chain_types.push("LITECOIN".to_string());
}
_ => return Err(anyhow!("unknow ver header when parse wif, ver: {}", ver[0])),
}
}
}
Ok(DecodedPrivateKey {
bytes: private_key_bytes,
network,
curve,
chain_types,
source,
})
}
fn exists_fingerprint(fingerprint: &str) -> Result<Vec<u8>> {
let map = &KEYSTORE_MAP.read();
let founded: Option<&Keystore> = map
.values()
.find(|keystore| keystore.fingerprint() == fingerprint);
let result: ExistsKeystoreResult;
if let Some(ks) = founded {
result = ExistsKeystoreResult {
is_exists: true,
id: ks.id(),
}
} else {
result = ExistsKeystoreResult {
is_exists: false,
id: "".to_owned(),
}
}
encode_message(result)
}
fn key_info_from_v3(keystore: &str, password: &str) -> Result<(Vec<u8>, String)> {
let ks: LegacyKeystore = serde_json::from_str(keystore)?;
ks.validate_v3(password)?;
let key = tcx_crypto::Key::Password(password.to_string());
let unlocker = ks.crypto.use_key(&key)?;
let private_key = unlocker.plaintext()?;
Ok((private_key, "Imported ETH".to_string()))
}
fn key_info_from_substrate_keystore(keystore: &str, password: &str) -> Result<(Vec<u8>, String)> {
let ks: SubstrateKeystore = serde_json::from_str(keystore)?;
ks.validate()?;
let pk = decode_substrate_keystore(&ks, password)?;
Ok((pk, ks.meta.name))
}
fn curve_to_chain_type(curve: &CurveType) -> Vec<String> {
match curve {
CurveType::SECP256k1 => vec![
"BITCOIN".to_string(),
"BITCOINCASH".to_string(),
"LITECOIN".to_string(),
"FILECOIN".to_string(),
"EOS".to_string(),
"TRON".to_string(),
"COSMOS".to_string(),
],
CurveType::ED25519 => vec!["TEZOS".to_string()],
CurveType::SR25519 => vec!["KUSAMA".to_string(), "POLKADOT".to_string()],
CurveType::BLS => vec!["FILECOIN".to_string()],
_ => vec![],
}
}
pub fn init_token_core_x(data: &[u8]) -> Result<()> {
let InitTokenCoreXParam {
file_dir,
xpub_common_key,
xpub_common_iv,
is_debug,
} = InitTokenCoreXParam::decode(data).unwrap();
*KEYSTORE_BASE_DIR.write() = file_dir.to_string();
let v2_dir = format!("{}/{}", file_dir, WALLET_V2_DIR);
fs::create_dir_all(&v2_dir)?;
*WALLET_FILE_DIR.write() = v2_dir.to_string();
*LEGACY_WALLET_FILE_DIR.write() = format!("{}/{}", file_dir, WALLET_V1_DIR);
*XPUB_COMMON_KEY_128.write() = xpub_common_key;
*XPUB_COMMON_IV.write() = xpub_common_iv;
if is_debug {
*IS_DEBUG.write() = is_debug;
if is_debug {
*KDF_ROUNDS.write() = 1;
}
}
scan_keystores()?;
Ok(())
}
pub fn scan_keystores() -> Result<ScanKeystoresResult> {
clean_keystore();
let file_dir = WALLET_FILE_DIR.read();
let p = Path::new(file_dir.as_str());
let walk_dir = std::fs::read_dir(p).expect("read dir");
let mut hd_keystores: Vec<KeystoreResult> = Vec::new();
let mut private_key_keystores: Vec<ImportPrivateKeyResult> = Vec::new();
for entry in walk_dir {
let entry = entry.expect("DirEntry");
let fp = entry.path();
if !fp
.file_name()
.expect("file_name")
.to_str()
.expect("file_name str")
.ends_with(".json")
{
continue;
}
let mut f = fs::File::open(fp).expect("open file");
let mut contents = String::new();
let _ = f.read_to_string(&mut contents);
let v: Value = serde_json::from_str(&contents).expect("read json from content");
let version = v["version"].as_i64().expect("version");
if version == HdKeystore::VERSION || version == PrivateKeystore::VERSION {
let keystore = Keystore::from_json(&contents)?;
if version == HdKeystore::VERSION {
let keystore_result = KeystoreResult {
id: keystore.id(),
name: keystore.meta().name.to_string(),
identifier: keystore.identity().identifier.to_string(),
ipfs_id: keystore.identity().ipfs_id.to_string(),
source: keystore.meta().source.to_string(),
created_at: keystore.meta().timestamp,
source_fingerprint: keystore.fingerprint().to_string(),
};
hd_keystores.push(keystore_result);
} else {
let curve = keystore
.get_curve()
.expect("pk keystore must contains curve");
let kestore_result = ImportPrivateKeyResult {
id: keystore.id(),
name: keystore.meta().name.to_string(),
identifier: keystore.identity().identifier.to_string(),
ipfs_id: keystore.identity().ipfs_id.to_string(),
source: keystore.meta().source.to_string(),
created_at: keystore.meta().timestamp,
source_fingerprint: keystore.fingerprint().to_string(),
identified_chain_types: curve_to_chain_type(&curve),
identified_network: keystore.meta().network.to_string(),
identified_curve: curve.as_str().to_string(),
};
private_key_keystores.push(kestore_result);
}
cache_keystore(keystore);
}
}
Ok(ScanKeystoresResult {
hd_keystores,
private_key_keystores,
})
}
pub fn create_keystore(data: &[u8]) -> Result<Vec<u8>> {
let param: CreateKeystoreParam =
CreateKeystoreParam::decode(data).expect("create_keystore param");
let meta = Metadata {
name: param.name,
password_hint: param.password_hint,
source: Source::NewMnemonic,
network: IdentityNetwork::from_str(¶m.network)?,
..Metadata::default()
};
let ks = HdKeystore::new(¶m.password, meta);
let keystore = Keystore::Hd(ks);
flush_keystore(&keystore)?;
let identity = keystore.identity();
let meta = keystore.meta();
let wallet = KeystoreResult {
id: keystore.id(),
name: meta.name.to_owned(),
source: Source::NewMnemonic.to_string(),
created_at: meta.timestamp,
identifier: identity.identifier.to_string(),
ipfs_id: identity.ipfs_id.to_string(),
source_fingerprint: keystore.fingerprint().to_string(),
};
let ret = encode_message(wallet)?;
cache_keystore(keystore);
Ok(ret)
}
pub fn import_mnemonic(data: &[u8]) -> Result<Vec<u8>> {
let param: ImportMnemonicParam =
ImportMnemonicParam::decode(data).expect("import_mnemonic param");
let mut founded_id: Option<String> = None;
{
let fingerprint = fingerprint_from_mnemonic(¶m.mnemonic)?;
let map = KEYSTORE_MAP.read();
if let Some(founded) = map
.values()
.find(|keystore| keystore.fingerprint() == fingerprint)
{
founded_id = Some(founded.id());
}
}
if founded_id.is_some() && !param.overwrite {
return Err(anyhow!("{}", "address_already_exist"));
}
let meta = Metadata {
name: param.name,
password_hint: param.password_hint,
source: Source::Mnemonic,
..Metadata::default()
};
let ks = HdKeystore::from_mnemonic(¶m.mnemonic, ¶m.password, meta)?;
let mut keystore = Keystore::Hd(ks);
if let Some(id) = founded_id {
keystore.set_id(&id);
}
flush_keystore(&keystore)?;
let meta = keystore.meta();
let identity = keystore.identity();
let wallet = KeystoreResult {
id: keystore.id(),
name: meta.name.to_owned(),
source: Source::Mnemonic.to_string(),
created_at: meta.timestamp,
identifier: identity.identifier.to_string(),
ipfs_id: identity.ipfs_id.to_string(),
source_fingerprint: keystore.fingerprint().to_string(),
};
let ret = encode_message(wallet)?;
cache_keystore(keystore);
Ok(ret)
}
impl_to_key!(crate::api::derive_accounts_param::Key);
pub fn derive_accounts(data: &[u8]) -> Result<Vec<u8>> {
let param: DeriveAccountsParam =
DeriveAccountsParam::decode(data).expect("derive_accounts param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
let mut account_responses: Vec<AccountResponse> = vec![];
for derivation in param.derivations {
let account = derive_account(guard.keystore_mut(), &derivation)?;
let mut coin_info = coin_info_from_param(
&derivation.chain_type,
&derivation.network,
&derivation.seg_wit,
&derivation.curve,
)?;
if !derivation.path.is_empty() {
coin_info.derivation_path = derivation.path;
}
let enc_xpub = if account.ext_pub_key.is_empty() {
Ok("".to_string())
} else {
encrypt_xpub(&account.ext_pub_key.to_string())
}?;
let account_rsp = AccountResponse {
chain_type: derivation.chain_type.to_owned(),
address: account.address.to_owned(),
path: account.derivation_path.to_owned(),
curve: account.curve.as_str().to_string(),
public_key: encode_public_key_internal(&account.public_key, &coin_info)?,
extended_public_key: account.ext_pub_key.to_string(),
encrypted_extended_public_key: enc_xpub,
seg_wit: derivation.seg_wit.to_string(),
};
account_responses.push(account_rsp);
}
let accounts_rsp = DeriveAccountsResult {
accounts: account_responses,
};
encode_message(accounts_rsp)
}
impl_to_key!(crate::api::export_mnemonic_param::Key);
pub(crate) fn export_mnemonic(data: &[u8]) -> Result<Vec<u8>> {
let param: ExportMnemonicParam =
ExportMnemonicParam::decode(data).expect("export_mnemonic param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
tcx_ensure!(
guard.keystore().derivable(),
anyhow!("{}", "private_keystore_cannot_export_mnemonic")
);
let export_result = ExportMnemonicResult {
id: guard.keystore().id(),
mnemonic: guard.keystore().export()?,
};
encode_message(export_result)
}
pub fn import_private_key(data: &[u8]) -> Result<Vec<u8>> {
let param: ImportPrivateKeyParam =
ImportPrivateKeyParam::decode(data).expect("import_private_key param");
let rsp = import_private_key_internal(¶m, None, None)?;
let ret = encode_message(rsp)?;
Ok(ret)
}
impl_to_key!(crate::api::export_private_key_param::Key);
pub(crate) fn export_private_key(data: &[u8]) -> Result<Vec<u8>> {
let param: ExportPrivateKeyParam =
ExportPrivateKeyParam::decode(data).expect("export_private_key param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
let curve = CurveType::from_str(¶m.curve);
let private_key_bytes = guard
.keystore_mut()
.get_private_key(curve, ¶m.path)?
.to_bytes();
let value = if ["POLKADOT", "KUSAMA"].contains(¶m.chain_type.as_str()) {
Ok(private_key_bytes.to_0x_hex())
} else if ["TRON", "ETHEREUM"].contains(¶m.chain_type.as_str()) {
Ok(private_key_bytes.to_hex())
} else if "FILECOIN".contains(param.chain_type.as_str()) {
Ok(KeyInfo::from_private_key(curve, &private_key_bytes)?
.to_json()?
.to_hex())
} else if "TEZOS".contains(param.chain_type.as_str()) {
Ok(encode_tezos_private_key(&private_key_bytes.to_hex())?)
} else if "EOS".contains(¶m.chain_type) {
encode_eos_wif(&private_key_bytes)
} else {
// private_key prefix is only about chain type and network
let coin_info = coin_info_from_param(¶m.chain_type, ¶m.network, "", "")?;
let typed_pk = TypedPrivateKey::from_slice(CurveType::SECP256k1, &private_key_bytes)?;
typed_pk.fmt(&coin_info)
}?;
let export_result = ExportPrivateKeyResult {
id: guard.keystore().id(),
private_key: value,
};
encode_message(export_result)
}
pub(crate) fn verify_password(data: &[u8]) -> Result<Vec<u8>> {
let param: WalletKeyParam = WalletKeyParam::decode(data).expect("verify_password param");
let map = KEYSTORE_MAP.read();
let keystore: &Keystore = match map.get(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
if keystore.verify_password(¶m.key.clone().unwrap().into()) {
let rsp = GeneralResult {
is_success: true,
error: "".to_owned(),
};
encode_message(rsp)
} else {
Err(anyhow!("{}", "password_incorrect"))
}
}
impl_to_key!(crate::api::wallet_key_param::Key);
pub(crate) fn delete_keystore(data: &[u8]) -> Result<Vec<u8>> {
let param: WalletKeyParam = WalletKeyParam::decode(data).expect("delete_keystore param");
let mut map = KEYSTORE_MAP.write();
let keystore: &Keystore = match map.get(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
if keystore.verify_password(¶m.key.clone().unwrap().into()) {
delete_keystore_file(¶m.id)?;
map.remove(¶m.id);
// Used to delete all duplicated mnemonic keystore
if let Some(file_ids) = remove_old_keystore_by_id(¶m.id.clone()) {
for file_id in file_ids {
map.remove(&file_id);
}
}
// Used to delete all identity keystore if is deleting identity wallet
if let Some(all_identity_wallets) = read_all_identity_wallet_ids() {
if all_identity_wallets.wallet_ids.contains(¶m.id) {
if let Some(file_ids) = remove_all_identity_wallets() {
for file_id in file_ids {
map.remove(&file_id);
}
}
}
}
let rsp = GeneralResult {
is_success: true,
error: "".to_owned(),
};
encode_message(rsp)
} else {
Err(anyhow!("{}", "password_incorrect"))
}
}
pub(crate) fn exists_private_key(data: &[u8]) -> Result<Vec<u8>> {
let param: ExistsPrivateKeyParam =
ExistsPrivateKeyParam::decode(data).expect("exists_private_key param");
let fingerprint = fingerprint_from_any_format_pk(¶m.private_key)?;
exists_fingerprint(&fingerprint)
}
pub(crate) fn exists_mnemonic(data: &[u8]) -> Result<Vec<u8>> {
let param: ExistsMnemonicParam =
ExistsMnemonicParam::decode(data).expect("exists_mnemonic param");
let key_hash = fingerprint_from_mnemonic(¶m.mnemonic)?;
exists_fingerprint(&key_hash)
}
impl_to_key!(crate::api::sign_param::Key);
pub(crate) fn sign_tx(data: &[u8]) -> Result<Vec<u8>> {
let param: SignParam = SignParam::decode(data).expect("sign_tx param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
sign_transaction_internal(¶m, guard.keystore_mut())
}
impl_to_key!(crate::api::sign_hashes_param::Key);
pub(crate) fn sign_hashes(data: &[u8]) -> Result<Vec<u8>> {
let param: SignHashesParam = SignHashesParam::decode(data).expect("sign_hashes param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
let signatures = param
.data_to_sign
.iter()
.map(|data_to_sign| -> Result<String> {
let hash = Vec::from_hex_auto(&data_to_sign.hash)?;
let sig = guard.keystore_mut().sign_hash(
&hash,
&data_to_sign.path,
&data_to_sign.curve,
&data_to_sign.sig_alg,
)?;
Ok(sig.to_0x_hex())
})
.collect::<Vec<Result<String>>>();
let signatures = signatures.into_iter().collect::<Result<Vec<String>>>()?;
encode_message(SignHashesResult { signatures })
}
impl_to_key!(crate::api::get_public_keys_param::Key);
pub(crate) fn get_public_keys(data: &[u8]) -> Result<Vec<u8>> {
let param: GetPublicKeysParam =
GetPublicKeysParam::decode(data).expect("get_public_keys param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
let public_keys: Vec<TypedPublicKey> = param
.derivations
.iter()
.map(|derivation| {
guard
.keystore_mut()
.get_public_key(CurveType::from_str(&derivation.curve), &derivation.path)
.expect("PublicKeyProcessed")
})
.collect();
let mut public_key_strs: Vec<String> = vec![];
for idx in 0..param.derivations.len() {
let pub_key = &public_keys[idx];
let derivation = ¶m.derivations[idx];
let coin_info = CoinInfo {
coin: derivation.chain_type.to_string(),
derivation_path: derivation.path.to_string(),
curve: CurveType::from_str(&derivation.curve),
..Default::default()
};
let public_key_str_ret = encode_public_key_internal(&pub_key, &coin_info);
let pub_key_str = public_key_str_ret?;
public_key_strs.push(pub_key_str);
}
encode_message(GetPublicKeysResult {
public_keys: public_key_strs,
})
}
impl_to_key!(crate::api::get_extended_public_keys_param::Key);
pub(crate) fn get_extended_public_keys(data: &[u8]) -> Result<Vec<u8>> {
let param: GetExtendedPublicKeysParam =
GetExtendedPublicKeysParam::decode(data).expect("get_extended_public_keys param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
let extended_public_keys = param
.derivations
.iter()
.map(|derivation| {
let extended_public_key = guard
.keystore_mut()
.get_deterministic_public_key(
CurveType::from_str(&derivation.curve),
&derivation.path,
)
.expect("GetExtendedPublicKeysParam");
extended_public_key.to_string()
})
.collect();
encode_message(GetExtendedPublicKeysResult {
extended_public_keys,
})
}
pub(crate) fn sign_message(data: &[u8]) -> Result<Vec<u8>> {
let param: SignParam = SignParam::decode(data).expect("sign_message param");
let mut map = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let mut guard = KeystoreGuard::unlock(keystore, param.key.clone().unwrap().into())?;
sign_message_internal(¶m, guard.keystore_mut())
}
pub fn get_derived_key(data: &[u8]) -> Result<Vec<u8>> {
let param: WalletKeyParam = WalletKeyParam::decode(data).expect("get_derived_key param");
let mut map: parking_lot::lock_api::RwLockWriteGuard<
'_,
parking_lot::RawRwLock,
std::collections::HashMap<String, Keystore>,
> = KEYSTORE_MAP.write();
let keystore: &mut Keystore = match map.get_mut(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
let Some(api::wallet_key_param::Key::Password(password)) = param.key else {
return Err(anyhow!("{}", "get_derived_key need password"));
};
let dk = keystore.get_derived_key(&password)?;
let ret = DerivedKeyResult {
id: param.id.to_owned(),
derived_key: dk,
};
encode_message(ret)
}
pub(crate) fn import_json(data: &[u8]) -> Result<Vec<u8>> {
let param: ImportJsonParam = ImportJsonParam::decode(data).expect("import_json param");
if let Ok(parse_v3_result) = key_info_from_v3(¶m.json, ¶m.password) {
let (sec_key_bytes, name) = parse_v3_result;
// network is required when import wif
let pk_import_param = ImportPrivateKeyParam {
private_key: sec_key_bytes.to_hex(),
password: param.password.to_string(),
name,
password_hint: "".to_string(),
network: "".to_string(),
overwrite: param.overwrite,
};
let mut ret = import_private_key_internal(
&pk_import_param,
Some(Source::KeystoreV3),
Some(param.json.to_string()),
)?;
ret.identified_chain_types = vec!["ETHEREUM".to_string()];
ret.identified_curve = CurveType::SECP256k1.as_str().to_string();
ret.identified_network = "".to_string();
encode_message(ret)
} else if let Ok(parse_substrate_result) =
key_info_from_substrate_keystore(¶m.json, ¶m.password)
{
let (sec_key_bytes, name) = parse_substrate_result;
let pk_import_param = ImportPrivateKeyParam {
private_key: sec_key_bytes.to_hex(),
password: param.password.to_string(),
name,
password_hint: "".to_string(),
network: "".to_string(),
overwrite: param.overwrite,
};
let mut ret = import_private_key_internal(
&pk_import_param,
Some(Source::SubstrateKeystore),
Some(param.json.to_string()),
)?;
ret.identified_chain_types = vec!["KUSAMA".to_string(), "POLKADOT".to_string()];
ret.identified_curve = CurveType::SR25519.as_str().to_string();
ret.identified_network = "".to_string();
return encode_message(ret);
} else {
return Err(anyhow!("unsupport_chain"));
}
}
pub(crate) fn export_json(data: &[u8]) -> Result<Vec<u8>> {
let param: ExportJsonParam = ExportJsonParam::decode(data).expect("export_json param");
let meta: Metadata;
{
let map = KEYSTORE_MAP.read();
let keystore: &Keystore = match map.get(¶m.id) {
Some(keystore) => Ok(keystore),
_ => Err(anyhow!("{}", "wallet_not_found")),
}?;
// !!! Warning !!! HDKeystore only can export raw sr25519 key,
// but polkadotjs fixtures needs a Ed25519 expanded secret key.
// they will generate difference account address