forked from latent-to/btwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet.rs
More file actions
1120 lines (1024 loc) · 43.9 KB
/
wallet.rs
File metadata and controls
1120 lines (1024 loc) · 43.9 KB
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 colored::Colorize;
use std::path::PathBuf;
use std::{env, fmt};
use crate::config::Config;
use crate::constants::{BT_WALLET_HOTKEY, BT_WALLET_NAME, BT_WALLET_PATH};
use crate::errors::*;
use crate::keyfile::Keyfile;
use crate::keypair::Keypair;
use crate::utils::{self, is_valid_bittensor_address_or_public_key};
/// Display the mnemonic and a warning message to keep the mnemonic safe.
///
/// Arguments:
/// mnemonic (str): The mnemonic phrase to display.
/// key_type (str): The type of key e.g. "coldkey" or "hotkey".
#[cfg_attr(feature = "python-bindings", pyo3::pyfunction)]
pub fn display_mnemonic_msg(mnemonic: String, key_type: &str) {
utils::print(format!("{}", "\nIMPORTANT: Store this mnemonic in a secure (preferable offline place), as anyone who has possession of this mnemonic can use it to regenerate the key and access your tokens.\n".red()));
utils::print(format!(
"\nThe mnemonic to the new {} is: {}",
key_type.blue(),
mnemonic.green()
));
utils::print(format!(
"\nYou can use the mnemonic to recreate the key with `{}` in case it gets lost.\n",
"btcli".green()
));
}
#[derive(Clone)]
pub struct Wallet {
pub name: String,
pub path: String,
pub hotkey: String,
_path: PathBuf,
_coldkey: Option<Keypair>,
_coldkeypub: Option<Keypair>,
_hotkey: Option<Keypair>,
_hotkeypub: Option<Keypair>,
}
impl fmt::Display for Wallet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"Wallet (Name: '{:}', Hotkey: '{:}', Path: '{:}')",
self.name, self.hotkey, self.path
)
}
}
impl fmt::Debug for Wallet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"name: '{:?}', hotkey: '{:?}', path: '{:?}'",
self.name, self.hotkey, self.path
)
}
}
impl Wallet {
/// Initialize the bittensor wallet object containing a hot and coldkey.
///
/// Arguments:
/// name (Optional[str]): The name of the wallet. Defaults to "default".
/// hotkey (Optional[str]): The name of hotkey. Defaults to "default".
/// path (Optional[str]): The path to wallets. Defaults to "~/.bittensor/wallets/".
/// config (Optional[Config]): Optional configuration.
///
/// Returns:
/// `Wallet` - A new Wallet instance.
pub fn new(
name: Option<String>,
hotkey: Option<String>,
path: Option<String>,
config: Option<Config>,
) -> Self {
let final_name = name
.or(config.as_ref().map(|conf| conf.name()))
.unwrap_or(BT_WALLET_NAME.to_string());
let final_hotkey = hotkey
.or(config.as_ref().map(|conf| conf.hotkey()))
.unwrap_or(BT_WALLET_HOTKEY.to_string());
let final_path = path
.or(config.as_ref().map(|conf| conf.path()))
.unwrap_or(BT_WALLET_PATH.to_string());
let expanded_path = PathBuf::from(shellexpand::tilde(&final_path).to_string());
Wallet {
name: final_name,
hotkey: final_hotkey,
path: final_path,
_path: expanded_path,
_coldkey: None,
_coldkeypub: None,
_hotkey: None,
_hotkeypub: None,
}
}
/// Get default config
pub fn config() -> Config {
Config::new(None, None, None)
}
/// Print help information
pub fn help() -> Config {
unimplemented!()
}
// TODO: What are the prefixes for ?
pub fn add_args(parser: clap::Command, _prefix: Option<&str>) -> clap::Command {
let default_name =
env::var("BT_WALLET_NAME").unwrap_or_else(|_| BT_WALLET_NAME.to_string());
let default_name_static: &'static str = Box::leak(default_name.into_boxed_str());
let parser = parser.arg(
clap::Arg::new("wallet.name")
.long("wallet.name")
.default_value(default_name_static)
.help("The name of the wallet to unlock for running Bittensor"),
);
let default_hotkey =
env::var("BT_WALLET_HOTKEY").unwrap_or_else(|_| BT_WALLET_HOTKEY.to_string());
let default_hotkey_static: &'static str = Box::leak(default_hotkey.into_boxed_str());
let parser = parser.arg(
clap::Arg::new("wallet.hotkey")
.long("wallet.hotkey")
.default_value(default_hotkey_static)
.help("The name of the wallet's hotkey"),
);
let default_path =
env::var("BT_WALLET_PATH").unwrap_or_else(|_| BT_WALLET_PATH.to_string());
let default_path_static: &'static str = Box::leak(default_path.into_boxed_str());
let parser = parser.arg(
clap::Arg::new("wallet.path")
.long("wallet.path")
.default_value(default_path_static)
.help("The path to your Bittensor wallets"),
);
parser
}
/// Checks for existing coldkeypub, hotkeypub, hotkeys, and creates them if non-existent.
///
/// Arguments:
/// coldkey_use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// hotkey_use_password (bool): Whether to use a password for hotkey. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save a coldkey password to local env. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save a hotkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``. If `coldkey_password` is passed, then `coldkey_use_password` is automatically ``True``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``. If `hotkey_password` is passed, then `hotkey_use_password` is automatically ``True``.
/// overwrite (bool): Whether to overwrite an existing keys. Defaults to ``False``.
/// suppress (bool): If ``True``, suppresses the display of the keys mnemonic message. Defaults to ``False``.
///
/// Returns:
/// `Wallet` - The wallet instance with created keys.
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn create_if_non_existent(
&mut self,
coldkey_use_password: bool,
hotkey_use_password: bool,
save_coldkey_to_env: bool,
save_hotkey_to_env: bool,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: bool,
suppress: bool,
) -> Result<Self, WalletError> {
self.create(
coldkey_use_password,
hotkey_use_password,
save_coldkey_to_env,
save_hotkey_to_env,
coldkey_password,
hotkey_password,
overwrite,
suppress,
)
}
/// Checks for existing coldkeypub and hotkeys, and creates them if non-existent.
///
/// Arguments:
/// coldkey_use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// hotkey_use_password (bool): Whether to use a password for hotkey. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save a coldkey password to local env. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save a hotkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``. If `coldkey_password` is passed, then `coldkey_use_password` is automatically ``True``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``. If `hotkey_password` is passed, then `hotkey_use_password` is automatically ``True``.
/// overwrite (bool): Whether to overwrite an existing keys. Defaults to ``False``.
/// suppress (bool): If ``True``, suppresses the display of the keys mnemonic message. Defaults to ``False``.
///
/// Returns:
/// Wallet instance with created keys.
///
/// Raises:
/// WalletError: If key generation or file operations fail.
#[allow(clippy::bool_comparison)]
pub fn create(
&mut self,
coldkey_use_password: bool,
hotkey_use_password: bool,
save_coldkey_to_env: bool,
save_hotkey_to_env: bool,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: bool,
suppress: bool,
) -> Result<Self, WalletError> {
if overwrite
|| (!self.coldkey_file()?.exists_on_device()?
&& !self.coldkeypub_file()?.exists_on_device()?)
{
self.create_new_coldkey(
12,
coldkey_use_password,
overwrite,
suppress,
save_coldkey_to_env,
coldkey_password,
)?;
} else {
println!("ColdKey for the wallet '{}' already exists.", self.name);
}
if overwrite
|| !self.hotkey_file()?.exists_on_device()?
&& !self.hotkeypub_file()?.exists_on_device()?
{
self.create_new_hotkey(
12,
hotkey_use_password,
overwrite,
suppress,
save_hotkey_to_env,
hotkey_password,
)?;
} else {
println!("HotKey for the wallet '{}' already exists.", self.name);
}
Ok(self.clone())
}
/// Checks for existing coldkeypub and hotkeys, and recreates them if non-existent.
///
/// Arguments:
/// coldkey_use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// hotkey_use_password (bool): Whether to use a password for hotkey. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save a coldkey password to local env. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save a hotkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``. If `coldkey_password` is passed, then `coldkey_use_password` is automatically ``True``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``. If `hotkey_password` is passed, then `hotkey_use_password` is automatically ``True``.
/// overwrite (bool): Whether to overwrite an existing keys. Defaults to ``False``.
/// suppress (bool): If ``True``, suppresses the display of the keys mnemonic message. Defaults to ``False``.
///
/// Returns:
/// Wallet instance with created keys.
///
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn recreate(
&mut self,
coldkey_use_password: bool,
hotkey_use_password: bool,
save_coldkey_to_env: bool,
save_hotkey_to_env: bool,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: bool,
suppress: bool,
) -> Result<Self, WalletError> {
self.create_new_coldkey(
12,
coldkey_use_password,
overwrite,
suppress,
save_coldkey_to_env,
coldkey_password,
)?;
self.create_new_hotkey(
12,
hotkey_use_password,
overwrite,
suppress,
save_hotkey_to_env,
hotkey_password,
)?;
Ok(self.clone())
}
/// Returns the hotkey file.
pub fn hotkey_file(&self) -> Result<Keyfile, KeyFileError> {
self.create_hotkey_file(false)
}
/// Creates a new hotkey file for the keypair.
///
/// Arguments:
/// save_hotkey_to_env (bool): Whether to save hotkey password to local env. Defaults to ``False``.
///
/// Returns:
/// `Keyfile` - The created hotkey file.
/// Raises:
/// KeyFileError: If file creation fails.
pub fn create_hotkey_file(&self, save_hotkey_to_env: bool) -> Result<Keyfile, KeyFileError> {
// concatenate wallet path
let wallet_path = self._path.join(&self.name);
// concatenate hotkey path
let hotkey_path = wallet_path.join("hotkeys").join(&self.hotkey);
Keyfile::new(
hotkey_path.to_string_lossy().into_owned(),
Some(self.hotkey.clone()),
save_hotkey_to_env,
)
}
/// Returns the coldkey file.
pub fn coldkey_file(&self) -> Result<Keyfile, KeyFileError> {
self.create_coldkey_file(false)
}
/// Creates a new coldkey file for the keypair.
///
/// Arguments:
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
///
/// Returns:
/// `Keyfile` - The created coldkey file.
/// Raises:
/// KeyFileError: If file creation fails.
pub fn create_coldkey_file(&self, save_coldkey_to_env: bool) -> Result<Keyfile, KeyFileError> {
// concatenate wallet path
let wallet_path = PathBuf::from(&self._path).join(&self.name);
// concatenate coldkey path
let coldkey_path = wallet_path.join("coldkey");
Keyfile::new(
coldkey_path.to_string_lossy().into_owned(),
Some("coldkey".to_string()),
save_coldkey_to_env,
)
}
/// Returns the hotkeypub file.
pub fn hotkeypub_file(&self) -> Result<Keyfile, KeyFileError> {
// concatenate wallet path
let wallet_path = self._path.join(&self.name);
let hotkeypub_name = format!("{}pub.txt", self.hotkey);
// concatenate hotkeypub path
let hotkeypub_path = wallet_path.join("hotkeys").join(&hotkeypub_name);
Keyfile::new(
hotkeypub_path.to_string_lossy().into_owned(),
Some(hotkeypub_name),
false,
)
}
/// Returns the coldkeypub file.
pub fn coldkeypub_file(&self) -> Result<Keyfile, KeyFileError> {
// concatenate wallet path
let wallet_path = self._path.join(&self.name);
// concatenate hotkey path
let coldkeypub_path = wallet_path.join("coldkeypub.txt");
Keyfile::new(
coldkeypub_path.to_string_lossy().into_owned(),
Some("coldkeypub.txt".to_string()),
false,
)
}
/// Returns the coldkey from wallet.path/wallet.name/coldkey or raises an error.
pub fn coldkey_property(&self) -> Result<Keypair, KeyFileError> {
if let Some(coldkey) = &self._coldkey {
Ok(coldkey.clone())
} else {
let coldkey_file = self.coldkey_file()?;
coldkey_file.get_keypair(None)
}
}
/// Returns the coldkeypub from wallet.path/wallet.name/coldkeypub.txt or raises an error.
pub fn coldkeypub_property(&self) -> Result<Keypair, KeyFileError> {
let coldkeypub_file = self.coldkeypub_file()?;
coldkeypub_file.get_keypair(None)
}
/// Returns the hotkey from wallet.path/wallet.name/hotkeys/wallet.hotkey or raises an error.
pub fn hotkey_property(&self) -> Result<Keypair, KeyFileError> {
if let Some(hotkey) = &self._hotkey {
Ok(hotkey.clone())
} else {
let hotkey_file = self.hotkey_file()?;
hotkey_file.get_keypair(None)
}
}
/// Returns the hotkeypub from wallet.path/wallet.name/hotkeypub.txt or raises an error.
pub fn hotkeypub_property(&self) -> Result<Keypair, KeyFileError> {
let hotkeypub_file = self.hotkeypub_file()?;
hotkeypub_file.get_keypair(None)
}
/// Returns the name of the wallet
pub fn get_name(&self) -> String {
self.name.clone()
}
/// Returns the path of the wallet
pub fn get_path(&self) -> String {
self.path.clone()
}
/// Returns the hotkey name
pub fn get_hotkey_str(&self) -> String {
self.hotkey.clone()
}
/// Sets the coldkey for the wallet.
///
/// Arguments:
/// keypair (Keypair): The keypair to set as coldkey.
/// encrypt (bool): Whether to encrypt the key. Defaults to ``True``.
/// overwrite (bool): Whether to overwrite if key exists. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``.
///
/// Raises:
/// KeyFileError: If file operations fail.
pub fn set_coldkey(
&mut self,
keypair: Keypair,
encrypt: bool,
overwrite: bool,
save_coldkey_to_env: bool,
coldkey_password: Option<String>,
) -> Result<(), KeyFileError> {
self._coldkey = Some(keypair.clone());
match self.create_coldkey_file(save_coldkey_to_env) {
Ok(keyfile) => keyfile
.set_keypair(keypair, encrypt, overwrite, coldkey_password)
.map_err(|e| KeyFileError::Generic(e.to_string())),
Err(e) => Err(KeyFileError::Generic(e.to_string())),
}
}
/// Sets the coldkeypub for the wallet.
///
/// Arguments:
/// keypair (Keypair): The keypair to set as coldkeypub.
/// encrypt (bool): Whether to encrypt the key. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite if key exists. Defaults to ``False``.
///
/// Raises:
/// KeyFileError: If file operations fail.
pub fn set_coldkeypub(
&mut self,
keypair: Keypair,
encrypt: bool,
overwrite: bool,
) -> Result<(), KeyFileError> {
let ss58_address = keypair
.ss58_address()
.ok_or_else(|| KeyFileError::Generic("Failed to get ss58_address".to_string()))?;
let coldkeypub_keypair = Keypair::new(Some(ss58_address), None, None, 42, None, 1)
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
self._coldkeypub = Some(coldkeypub_keypair.clone());
self.coldkeypub_file()
.map_err(|e| KeyFileError::Generic(e.to_string()))?
.set_keypair(coldkeypub_keypair, encrypt, overwrite, None)
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
Ok(())
}
/// Sets the hotkey for the wallet.
///
/// Arguments:
/// keypair (Keypair): The keypair to set as hotkey.
/// encrypt (bool): Whether to encrypt the key. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite if key exists. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save hotkey password to local env. Defaults to ``False``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``.
///
/// Raises:
/// KeyFileError: If file operations fail.
pub fn set_hotkey(
&mut self,
keypair: Keypair,
encrypt: bool,
overwrite: bool,
save_hotkey_to_env: bool,
hotkey_password: Option<String>,
) -> Result<(), KeyFileError> {
self._hotkey = Some(keypair.clone());
self.create_hotkey_file(save_hotkey_to_env)
.map_err(|e| KeyFileError::Generic(e.to_string()))?
.set_keypair(keypair, encrypt, overwrite, hotkey_password)
}
/// Sets the hotkeypub for the wallet.
///
/// Arguments:
/// keypair (Keypair): The keypair to set as hotkeypub.
/// encrypt (bool): Whether to encrypt the key. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite if key exists. Defaults to ``False``.
///
/// Raises:
/// KeyFileError: If file operations fail.
pub fn set_hotkeypub(
&mut self,
keypair: Keypair,
encrypt: bool,
overwrite: bool,
) -> Result<(), KeyFileError> {
let ss58_address = keypair
.ss58_address()
.ok_or_else(|| KeyFileError::Generic("Failed to get ss58_address".to_string()))?;
let hotkeypub_keypair = Keypair::new(Some(ss58_address), None, None, 42, None, 1)
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
self._hotkeypub = Some(hotkeypub_keypair.clone());
self.hotkeypub_file()
.map_err(|e| KeyFileError::Generic(e.to_string()))?
.set_keypair(hotkeypub_keypair, encrypt, overwrite, None)
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
Ok(())
}
/// Gets the coldkey from the wallet.
///
/// Arguments:
/// password (Optional[str]): Password for decryption. Defaults to ``None``. If not provided, asks for user input.
///
/// Returns:
/// `Keypair` - The coldkey keypair.
/// Raises:
/// KeyFileError: If the coldkey file doesn't exist or decryption fails.
pub fn get_coldkey(&self, password: Option<String>) -> Result<Keypair, KeyFileError> {
self.coldkey_file()?.get_keypair(password)
}
/// Gets the coldkeypub from the wallet.
///
/// Arguments:
/// password (Optional[str]): Password for decryption. Defaults to ``None``. If not provided, asks for user input.
///
/// Returns:
/// `Keypair` - The coldkeypub keypair.
/// Raises:
/// KeyFileError: If the coldkeypub file doesn't exist or decryption fails.
pub fn get_coldkeypub(&self, password: Option<String>) -> Result<Keypair, KeyFileError> {
self.coldkeypub_file()?.get_keypair(password)
}
/// Gets the hotkey from the wallet.
///
/// Arguments:
/// password (Optional[str]): Password for decryption. Defaults to ``None``. If not provided, asks for user input.
///
/// Returns:
/// `Keypair` - The hotkey keypair.
/// Raises:
/// KeyFileError: If the hotkey file doesn't exist or decryption fails.
pub fn get_hotkey(&self, password: Option<String>) -> Result<Keypair, KeyFileError> {
self.hotkey_file()?.get_keypair(password)
}
/// Gets the hotkeypub from the wallet.
///
/// Arguments:
/// password (Optional[str]): Password for decryption. Defaults to ``None``. If not provided, asks for user input.
///
/// Returns:
/// `Keypair` - The hotkeypub keypair.
/// Raises:
/// KeyFileError: If the hotkeypub file doesn't exist or decryption fails.
pub fn get_hotkeypub(&self, password: Option<String>) -> Result<Keypair, KeyFileError> {
self.hotkeypub_file()?.get_keypair(password)
}
/// Creates coldkey from uri string, optionally encrypts it with the user-provided password.
///
/// Arguments:
/// uri (str): The URI string to create the coldkey from.
/// use_password (bool): Whether to use a password for coldkey. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``True``.
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``.
///
/// Returns:
/// `Wallet` - The wallet instance with created coldkey.
/// Raises:
/// KeyFileError: If key creation or file operations fail.
pub fn create_coldkey_from_uri(
&mut self,
uri: String,
use_password: bool,
overwrite: bool,
suppress: bool,
save_coldkey_to_env: bool,
coldkey_password: Option<String>,
) -> Result<Wallet, KeyFileError> {
let keypair = Keypair::create_from_uri(uri.as_str())
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
if !suppress {
if let Some(m) = keypair.mnemonic() {
display_mnemonic_msg(m, "coldkey");
}
}
self.set_coldkey(
keypair.clone(),
use_password,
overwrite,
save_coldkey_to_env,
coldkey_password,
)?;
self.set_coldkeypub(keypair, false, overwrite)?;
Ok(self.clone())
}
/// Creates hotkey from uri string, optionally encrypts it with the user-provided password.
///
/// Arguments:
/// uri (str): The URI string to create the hotkey from.
/// use_password (bool): Whether to use a password for hotkey. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``True``.
/// save_hotkey_to_env (bool): Whether to save hotkey password to local env. Defaults to ``False``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``.
///
/// Returns:
/// `Wallet` - The wallet instance with created hotkey.
/// Raises:
/// KeyFileError: If key creation or file operations fail.
pub fn create_hotkey_from_uri(
&mut self,
uri: String,
use_password: bool,
overwrite: bool,
suppress: bool,
save_hotkey_to_env: bool,
hotkey_password: Option<String>,
) -> Result<Wallet, KeyFileError> {
let keypair = Keypair::create_from_uri(uri.as_str())
.map_err(|e| KeyFileError::Generic(e.to_string()))?;
if !suppress {
if let Some(m) = keypair.mnemonic() {
display_mnemonic_msg(m, "hotkey");
}
}
self.set_hotkey(
keypair.clone(),
use_password,
overwrite,
save_hotkey_to_env,
hotkey_password,
)?;
self.set_hotkeypub(keypair, false, overwrite)?;
Ok(self.clone())
}
/// Unlocks the coldkey.
pub fn unlock_coldkey(&mut self) -> Result<Keypair, KeyFileError> {
if self._coldkey.is_none() {
let coldkey_file = self.coldkey_file()?;
self._coldkey = Some(coldkey_file.get_keypair(None)?);
}
let _coldkey = self
._coldkey
.clone()
.ok_or_else(|| KeyFileError::Generic("Coldkey file doesn't exist.".to_string()))?;
Ok(_coldkey)
}
/// Unlocks the coldkeypub.
pub fn unlock_coldkeypub(&mut self) -> Result<Keypair, KeyFileError> {
if self._coldkeypub.is_none() {
let coldkeypub_file = self.coldkeypub_file()?;
self._coldkeypub = Some(coldkeypub_file.get_keypair(None)?);
}
let _coldkeypub = self
._coldkeypub
.clone()
.ok_or_else(|| KeyFileError::Generic("Coldkey file doesn't exist.".to_string()))?;
Ok(_coldkeypub)
}
/// Unlocks the hotkey.
pub fn unlock_hotkey(&mut self) -> Result<Keypair, KeyFileError> {
if self._hotkey.is_none() {
let hotkey_file = self.hotkey_file()?;
self._hotkey = Some(hotkey_file.get_keypair(None)?);
}
let _hotkey = self
._hotkey
.clone()
.ok_or_else(|| KeyFileError::Generic("Hotkey doesn't exist.".to_string()))?;
Ok(_hotkey)
}
/// Unlocks the hotkeypub.
pub fn unlock_hotkeypub(&mut self) -> Result<Keypair, KeyFileError> {
if self._hotkeypub.is_none() {
let hotkeypub_file = self.hotkeypub_file()?;
self._hotkeypub = Some(hotkeypub_file.get_keypair(None)?);
}
let _hotkeypub = self
._hotkeypub
.clone()
.ok_or_else(|| KeyFileError::Generic("Hotkeypub file doesn't exist.".to_string()))?;
Ok(_hotkeypub)
}
/// Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.
///
/// Arguments:
/// n_words (int): The number of words in the mnemonic. Defaults to 12.
/// use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``. If `coldkey_password` is passed, then `use_password` is automatically ``True``.
///
/// Returns:
/// `Wallet` - The wallet instance with created coldkey.
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn new_coldkey(
&mut self,
n_words: usize,
use_password: bool,
overwrite: bool,
suppress: bool,
save_coldkey_to_env: bool,
coldkey_password: Option<String>,
) -> Result<Wallet, WalletError> {
self.create_new_coldkey(
n_words,
use_password,
overwrite,
suppress,
save_coldkey_to_env,
coldkey_password,
)
}
/// Creates a new coldkey, optionally encrypts it with the user-provided password and saves to disk.
///
/// Arguments:
/// n_words (int): The number of words in the mnemonic. Defaults to 12.
/// use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``. If `coldkey_password` is passed, then `use_password` is automatically ``True``.
///
/// Returns:
/// `Wallet` - The wallet instance with created coldkey.
/// Raises:
/// WalletError: If key generation or file operations fail.
fn create_new_coldkey(
&mut self,
n_words: usize,
mut use_password: bool,
overwrite: bool,
suppress: bool,
save_coldkey_to_env: bool,
coldkey_password: Option<String>,
) -> Result<Self, WalletError> {
let mnemonic = Keypair::generate_mnemonic(n_words)
.map_err(|e| WalletError::KeyGeneration(e.to_string()))?;
let keypair = Keypair::create_from_mnemonic(&mnemonic)
.map_err(|e| WalletError::KeyGeneration(e.to_string()))?;
if !suppress {
display_mnemonic_msg(mnemonic, "coldkey");
}
// If password is provided, force password usage
if coldkey_password.is_some() {
use_password = true;
}
self.set_coldkey(
keypair.clone(),
use_password,
overwrite,
save_coldkey_to_env,
coldkey_password,
)?;
self.set_coldkeypub(keypair.clone(), false, overwrite)?;
Ok(self.clone())
}
/// Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.
///
/// Arguments:
/// n_words (int): The number of words in the mnemonic. Defaults to 12.
/// use_password (bool): Whether to use a password for hotkey. Defaults to ``True``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save hotkey password to local env. Defaults to ``False``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``. If `hotkey_password` is passed, then `use_password` is automatically ``True``.
///
/// Returns:
/// `Wallet` - The wallet instance with created hotkey.
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn new_hotkey(
&mut self,
n_words: usize,
use_password: bool,
overwrite: bool,
suppress: bool,
save_hotkey_to_env: bool,
hotkey_password: Option<String>,
) -> Result<Self, WalletError> {
self.create_new_hotkey(
n_words,
use_password,
overwrite,
suppress,
save_hotkey_to_env,
hotkey_password,
)
}
/// Creates a new hotkey, optionally encrypts it with the user-provided password and saves to disk.
///
/// Arguments:
/// n_words (int): The number of words in the mnemonic. Defaults to 12.
/// use_password (bool): Whether to use a password for hotkey. Defaults to ``False``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``False``.
/// save_hotkey_to_env (bool): Whether to save hotkey password to local env. Defaults to ``False``.
/// hotkey_password (Optional[str]): Hotkey password for encryption. Defaults to ``None``. If `hotkey_password` is passed, then `use_password` is automatically ``True``.
///
/// Returns:
/// `Wallet` - The wallet instance with created hotkey.
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn create_new_hotkey(
&mut self,
n_words: usize,
mut use_password: bool,
overwrite: bool,
suppress: bool,
save_hotkey_to_env: bool,
hotkey_password: Option<String>,
) -> Result<Wallet, WalletError> {
let mnemonic = Keypair::generate_mnemonic(n_words)
.map_err(|e| WalletError::KeyGeneration(e.to_string()))?;
let keypair = Keypair::create_from_mnemonic(&mnemonic)
.map_err(|e| WalletError::KeyGeneration(e.to_string()))?;
if !suppress {
display_mnemonic_msg(mnemonic, "hotkey");
}
// if hotkey_password is passed then hotkey_use_password always is true
use_password = hotkey_password.is_some() || use_password;
self.set_hotkey(
keypair.clone(),
use_password,
overwrite,
save_hotkey_to_env,
hotkey_password,
)?;
self.set_hotkeypub(keypair.clone(), false, overwrite)?;
Ok(self.clone())
}
/// Regenerates the coldkey from the passed mnemonic or seed, or JSON encrypts it with the user's password and saves the file.
///
/// Arguments:
/// mnemonic (Optional[str]): Mnemonic phrase to regenerate the coldkey from. Defaults to ``None``.
/// seed (Optional[str]): Seed hex to regenerate the coldkey from. Defaults to ``None``.
/// json (Optional[tuple]): Tuple of (JSON data, passphrase) to regenerate the coldkey from. Defaults to ``None``.
/// use_password (bool): Whether to use a password for coldkey. Defaults to ``True``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
/// suppress (bool): Whether to suppress mnemonic display. Defaults to ``False``.
/// save_coldkey_to_env (bool): Whether to save coldkey password to local env. Defaults to ``False``.
/// coldkey_password (Optional[str]): Coldkey password for encryption. Defaults to ``None``.
///
/// Returns:
/// `Wallet` - The wallet instance with regenerated coldkey.
/// Raises:
/// WalletError: If key generation or file operations fail.
#[allow(clippy::too_many_arguments)]
pub fn regenerate_coldkey(
&mut self,
mnemonic: Option<String>,
seed: Option<String>,
json: Option<(String, String)>,
use_password: bool,
overwrite: bool,
suppress: bool,
save_coldkey_to_env: bool,
coldkey_password: Option<String>,
) -> Result<Self, WalletError> {
let keypair = if let Some(mnemonic) = mnemonic {
// mnemonic
let keypair = Keypair::create_from_mnemonic(&mnemonic)
.map_err(|e| WalletError::KeyGeneration(e.to_string()))?;
if !suppress {
display_mnemonic_msg(mnemonic, "coldkey");
}
keypair
} else if let Some(seed) = seed {
// seed
Keypair::create_from_seed(hex::decode(seed.trim_start_matches("0x")).unwrap())
.map_err(|e| KeyFileError::Generic(e.to_string()))?
} else if let Some((json_data, passphrase)) = json {
// json_data + passphrase
Keypair::create_from_encrypted_json(&json_data, &passphrase)
.map_err(|e| KeyFileError::Generic(e.to_string()))?
} else {
return Err(WalletError::InvalidInput(
"Must pass either mnemonic, seed, or json.".to_string(),
));
};
self.set_coldkey(
keypair.clone(),
use_password,
overwrite,
save_coldkey_to_env,
coldkey_password,
)?;
self.set_coldkeypub(keypair.clone(), false, overwrite)?;
Ok(self.clone())
}
/// Regenerates the coldkeypub from the passed ss58_address or public_key and saves the file.
/// Requires either ss58_address or public_key to be passed.
///
/// Arguments:
/// ss58_address (Optional[str]): SS58 address to regenerate the coldkeypub from. Defaults to ``None``.
/// public_key (Optional[str]): Public key hex to regenerate the coldkeypub from. Defaults to ``None``.
/// overwrite (bool): Whether to overwrite existing keys. Defaults to ``False``.
///
/// Returns:
/// `Wallet` - The wallet instance with regenerated coldkeypub.
/// Raises:
/// WalletError: If key generation or file operations fail.
pub fn regenerate_coldkeypub(
&mut self,
ss58_address: Option<String>,
public_key: Option<String>,
overwrite: bool,
) -> Result<Self, WalletError> {
if ss58_address.is_none() && public_key.is_none() {
return Err(WalletError::InvalidInput(
"Either ss58_address or public_key must be passed.".to_string(),
));
}
let address_to_string = ss58_address
.as_ref()
.or(public_key.as_ref())
.ok_or_else(|| WalletError::InvalidInput("No address provided".to_string()))?;
if !is_valid_bittensor_address_or_public_key(address_to_string) {
return Err(WalletError::InvalidInput(format!(
"Invalid {}.",
if ss58_address.is_some() {
"ss58_address"