-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathpython_bindings.rs
More file actions
1453 lines (1314 loc) · 47.5 KB
/
python_bindings.rs
File metadata and controls
1453 lines (1314 loc) · 47.5 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 std::{borrow::Cow, env, ffi::CString, str};
use crate::constants::{BT_WALLET_HOTKEY, BT_WALLET_NAME, BT_WALLET_PATH};
use crate::errors::{ConfigurationError, KeyFileError, PasswordError, WalletError};
use crate::keyfile;
use crate::keyfile::Keyfile as RustKeyfile;
use crate::keypair::Keypair as RustKeypair;
use crate::wallet::Wallet as RustWallet;
use pyo3::exceptions::{PyException, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyBytes, PyModule, PyString, PyType};
use pyo3::wrap_pyfunction;
#[pyclass(subclass)]
#[derive(Clone)]
struct Config {
inner: crate::config::Config,
}
#[pymethods]
impl Config {
#[new]
#[pyo3(signature = (name=None, hotkey=None, path=None))]
fn new(name: Option<String>, hotkey: Option<String>, path: Option<String>) -> Self {
Config {
inner: crate::config::Config::new(name, hotkey, path),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
#[getter]
fn name(&self) -> String {
self.inner.name()
}
#[getter]
fn path(&self) -> String {
self.inner.path()
}
#[getter]
fn hotkey(&self) -> String {
self.inner.hotkey()
}
}
#[pyclass(name = "Keyfile", subclass)]
#[derive(Clone)]
struct PyKeyfile {
inner: RustKeyfile,
}
#[pymethods]
impl PyKeyfile {
#[new]
#[pyo3(signature = (path=None, name=None, should_save_to_env=false))]
fn new(path: Option<String>, name: Option<String>, should_save_to_env: bool) -> Self {
PyKeyfile {
inner: RustKeyfile::new(path.unwrap_or_default(), name, should_save_to_env)
.expect("Failed to create keyfile"),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
fn __repr__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
#[getter]
fn path(&self) -> String {
self.inner.path.clone()
}
fn exists_on_device(&self) -> PyResult<bool> {
self.inner
.exists_on_device()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
fn is_readable(&self) -> PyResult<bool> {
self.inner
.is_readable()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
fn is_writable(&self) -> PyResult<bool> {
self.inner
.is_writable()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
fn is_encrypted(&self) -> PyResult<bool> {
self.inner
.is_encrypted()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
#[pyo3(signature = (print_result=true, no_prompt=false))]
fn check_and_update_encryption(&self, print_result: bool, no_prompt: bool) -> PyResult<bool> {
self.inner
.check_and_update_encryption(print_result, no_prompt)
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
#[pyo3(signature = (password=None))]
fn encrypt(&self, password: Option<String>) -> PyResult<()> {
self.inner
.encrypt(password)
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
#[pyo3(signature = (password=None))]
fn decrypt(&self, password: Option<String>) -> PyResult<()> {
self.inner
.decrypt(password)
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
fn env_var_name(&self) -> PyResult<String> {
self.inner
.env_var_name()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
#[pyo3(signature = (password=None))]
fn save_password_to_env(&self, password: Option<String>) -> PyResult<String> {
self.inner
.save_password_to_env(password)
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
fn remove_password_from_env(&self) -> PyResult<bool> {
self.inner
.remove_password_from_env()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
#[getter(data)]
fn data_py(&self) -> PyResult<Option<Cow<[u8]>>> {
self.inner
.data()
.map(|vec| Some(Cow::Owned(vec)))
.or_else(|_e| Ok(None))
}
fn make_dirs(&self) -> PyResult<()> {
self.inner
.make_dirs()
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))
}
/// Returns the keypair from path, decrypts data if the file is encrypted.
#[getter(keypair)]
pub fn keypair_py(&self) -> PyResult<PyKeypair> {
self.get_keypair(None)
}
#[pyo3(signature = (password=None))]
fn get_keypair(&self, password: Option<String>) -> PyResult<PyKeypair> {
self.inner
.get_keypair(password)
.map(|inner| PyKeypair { inner })
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyo3(signature = (keypair, encrypt=true, overwrite=false, password=None))]
fn set_keypair(
&self,
keypair: PyKeypair,
encrypt: bool,
overwrite: bool,
password: Option<String>,
) -> PyResult<()> {
self.inner
.set_keypair(keypair.inner, encrypt, overwrite, password)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
}
#[pyclass(name = "Keypair", subclass)]
#[derive(Clone)]
pub struct PyKeypair {
inner: RustKeypair,
}
#[pymethods]
impl PyKeypair {
#[new]
#[pyo3(signature = (ss58_address=None, public_key=None, private_key=None, ss58_format=42, seed_hex=None, crypto_type=1))]
fn new(
ss58_address: Option<String>,
public_key: Option<String>,
private_key: Option<String>,
ss58_format: u8,
seed_hex: Option<Vec<u8>>,
crypto_type: u8,
) -> PyResult<Self> {
let keypair = RustKeypair::new(
ss58_address,
public_key,
private_key,
ss58_format,
seed_hex,
crypto_type,
)
.map_err(|e| PyErr::new::<PyValueError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
fn __repr__(&self) -> PyResult<String> {
self.__str__()
}
#[staticmethod]
#[pyo3(signature = (n_words=12))]
fn generate_mnemonic(n_words: usize) -> PyResult<String> {
RustKeypair::generate_mnemonic(n_words).map_err(|e| PyErr::new::<PyValueError, _>(e))
}
#[staticmethod]
fn create_from_mnemonic(mnemonic: &str) -> PyResult<Self> {
let keypair = RustKeypair::create_from_mnemonic(mnemonic)
.map_err(|e| PyErr::new::<PyValueError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
/// Creates Keypair from a seed for python
#[staticmethod]
fn create_from_seed(py: Python, seed: &str) -> PyResult<Py<Self>> {
let vec_seed = hex::decode(seed.trim_start_matches("0x"))
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))?;
let keypair = RustKeypair::create_from_seed(vec_seed)
.map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))?;
Py::new(py, PyKeypair { inner: keypair })
}
#[staticmethod]
fn create_from_private_key(private_key: &str) -> PyResult<Self> {
let keypair = RustKeypair::create_from_private_key(private_key)
.map_err(|e| PyErr::new::<PyValueError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
#[staticmethod]
fn create_from_encrypted_json(json_data: &str, passphrase: &str) -> PyResult<Self> {
let keypair = RustKeypair::create_from_encrypted_json(json_data, passphrase)
.map_err(|e| PyErr::new::<PyValueError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
#[staticmethod]
fn create_from_uri(uri: &str) -> PyResult<Self> {
let keypair =
RustKeypair::create_from_uri(uri).map_err(|e| PyErr::new::<PyValueError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
#[pyo3(signature = (data))]
fn sign(&self, data: Py<PyAny>, py: Python) -> PyResult<Cow<[u8]>> {
// Convert data to bytes (data can be a string, hex, or bytes)
let data_bound = data.bind(py);
let data_bytes = if let Ok(s) = data_bound.extract::<String>() {
if s.starts_with("0x") {
hex::decode(s.trim_start_matches("0x")).map_err(|e| {
PyErr::new::<PyConfigurationError, _>(format!("Invalid hex string: {}", e))
})?
} else {
s.into_bytes()
}
} else if let Ok(bytes) = data_bound.extract::<Vec<u8>>() {
bytes
} else if let Ok(scale_data) = data_bound.getattr("data") {
let scale_data_bytes: Vec<u8> = scale_data.extract()?;
scale_data_bytes
} else {
return Err(PyErr::new::<PyConfigurationError, _>(
"Keypair::sign: Unsupported data format. Expected str or bytes.",
));
};
self.inner
.sign(data_bytes)
.map(Cow::from)
.map_err(|e| PyErr::new::<PyConfigurationError, _>(e))
}
#[pyo3(signature = (data, signature))]
fn verify(&self, data: Py<PyAny>, signature: Py<PyAny>, py: Python) -> PyResult<bool> {
// Convert data to bytes (data can be a string, hex, or bytes)
let data_bound = data.bind(py);
let data_bytes = if let Ok(s) = data_bound.extract::<String>() {
if s.starts_with("0x") {
hex::decode(s.trim_start_matches("0x")).map_err(|e| {
PyErr::new::<PyValueError, _>(format!("Invalid hex string: {:?}", e))
})?
} else {
s.into_bytes()
}
} else if let Ok(bytes) = data_bound.extract::<Vec<u8>>() {
bytes
} else if let Ok(scale_data) = data_bound.getattr("data") {
let scale_data_bytes: Vec<u8> = scale_data.extract()?;
scale_data_bytes
} else {
return Err(PyErr::new::<PyConfigurationError, _>(
"Keypair::verify: Unsupported data format. Expected str or bytes.",
));
};
// Convert signature to bytes
let signature_bound = signature.bind(py);
let signature_bytes = if let Ok(s) = signature_bound.extract::<String>() {
if s.starts_with("0x") {
hex::decode(s.trim_start_matches("0x")).map_err(|e| {
PyErr::new::<PyValueError, _>(format!("Invalid hex string: {:?}", e))
})?
} else {
return Err(PyErr::new::<PyValueError, _>(
"Invalid signature format. Expected hex string.",
));
}
} else if let Ok(bytes) = signature_bound.extract::<Vec<u8>>() {
bytes
} else {
return Err(PyErr::new::<PyValueError, _>(
"Unsupported signature format. Expected str or bytes.",
));
};
self.inner
.verify(data_bytes, signature_bytes)
.map_err(|e| PyErr::new::<PyValueError, _>(e))
}
#[getter]
fn ss58_address(&self) -> Option<String> {
self.inner.ss58_address()
}
#[getter]
fn public_key(&self) -> PyResult<Option<Cow<[u8]>>> {
self.inner
.public_key()
.map(|opt| opt.map(Cow::from))
.map_err(|e| PyErr::new::<PyValueError, _>(e))
}
#[getter]
fn ss58_format(&self) -> u8 {
self.inner.ss58_format()
}
#[getter]
fn crypto_type(&self) -> u8 {
self.inner.crypto_type()
}
#[setter]
fn set_crypto_type(&mut self, crypto_type: u8) {
self.inner.set_crypto_type(crypto_type)
}
}
// Error type bindings
#[pyclass(name = "KeyFileError", extends = PyException)]
#[derive(Debug)]
pub struct PyKeyFileError {
inner: KeyFileError,
}
#[pymethods]
impl PyKeyFileError {
#[new]
fn new(msg: String) -> Self {
PyKeyFileError {
inner: KeyFileError::Generic(msg),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
}
impl<'py> IntoPyObject<'py> for KeyFileError {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(Bound::new(py, PyKeyFileError { inner: self })?.into_any())
}
}
#[pyclass(name = "ConfigurationError", extends = PyException)]
#[derive(Debug)]
pub struct PyConfigurationError {
inner: ConfigurationError,
}
#[pymethods]
impl PyConfigurationError {
#[new]
fn new(msg: String) -> Self {
PyConfigurationError {
inner: ConfigurationError::Message(msg),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
}
#[pyclass(name = "PasswordError", extends = PyException)]
#[derive(Debug)]
pub struct PyPasswordError {
inner: PasswordError,
}
#[pymethods]
impl PyPasswordError {
#[new]
fn new(msg: String) -> Self {
PyPasswordError {
inner: PasswordError::Message(msg),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
}
#[pyclass(name = "WalletError", extends = PyException)]
#[derive(Debug)]
pub struct PyWalletError {
inner: WalletError,
}
#[pymethods]
impl PyWalletError {
#[new]
fn new(msg: String) -> Self {
PyWalletError {
inner: WalletError::InvalidInput(msg),
}
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
}
impl<'py> IntoPyObject<'py> for WalletError {
type Target = PyAny;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
Ok(Bound::new(py, PyWalletError { inner: self })?.into_any())
}
}
// Define the Python module using PyO3
#[pymodule]
fn bittensor_wallet(module: Bound<'_, PyModule>) -> PyResult<()> {
// Add classes to the main module
module.add_class::<Config>()?;
module.add_class::<PyKeyfile>()?;
module.add_class::<PyKeypair>()?;
module.add_class::<Wallet>()?;
// Add submodules to the main module
register_config_module(&module)?;
register_errors_module(&module)?;
register_keyfile_module(&module)?;
register_keypair_module(&module)?;
register_utils_module(&module)?;
register_wallet_module(&module)?;
// Add cargo package versions
module.add("__version__", env!("CARGO_PKG_VERSION"))?;
Ok(())
}
// Define the submodule registration functions
fn register_config_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let config_module = PyModule::new(main_module.py(), "config")?;
config_module.add_class::<Config>()?;
main_module.add_submodule(&config_module)
}
fn register_errors_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let errors_module = PyModule::new(main_module.py(), "errors")?;
// Register the WalletError exception
errors_module.add_class::<PyWalletError>()?;
errors_module.add_class::<PyConfigurationError>()?;
errors_module.add_class::<PyKeyFileError>()?;
errors_module.add_class::<PyPasswordError>()?;
main_module.add_submodule(&errors_module)
}
#[pyfunction(name = "serialized_keypair_to_keyfile_data")]
#[pyo3(signature = (keypair))]
fn py_serialized_keypair_to_keyfile_data(py: Python, keypair: &PyKeypair) -> PyResult<Py<PyAny>> {
keyfile::serialized_keypair_to_keyfile_data(&keypair.inner)
.map(|bytes| PyBytes::new(py, &bytes).unbind().into_any())
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "deserialize_keypair_from_keyfile_data")]
fn py_deserialize_keypair_from_keyfile_data(keyfile_data: &[u8]) -> PyResult<PyKeypair> {
keyfile::deserialize_keypair_from_keyfile_data(keyfile_data)
.map(|inner| PyKeypair { inner })
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "validate_password")]
fn py_validate_password(password: &str) -> PyResult<bool> {
keyfile::validate_password(password).map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "ask_password")]
fn py_ask_password(validation_required: bool) -> PyResult<String> {
keyfile::ask_password(validation_required).map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "legacy_encrypt_keyfile_data")]
#[pyo3(signature = (keyfile_data, password=None))]
fn py_legacy_encrypt_keyfile_data(
keyfile_data: &[u8],
password: Option<String>,
) -> PyResult<Vec<u8>> {
keyfile::legacy_encrypt_keyfile_data(keyfile_data, password)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "get_password_from_environment")]
fn py_get_password_from_environment(env_var_name: String) -> PyResult<Option<String>> {
keyfile::get_password_from_environment(env_var_name)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "encrypt_keyfile_data")]
#[pyo3(signature = (keyfile_data, password=None))]
fn py_encrypt_keyfile_data(keyfile_data: &[u8], password: Option<String>) -> PyResult<Cow<[u8]>> {
keyfile::encrypt_keyfile_data(keyfile_data, password)
.map(Cow::from)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
#[pyfunction(name = "decrypt_keyfile_data")]
#[pyo3(signature = (keyfile_data, password=None, password_env_var=None))]
fn py_decrypt_keyfile_data(
keyfile_data: &[u8],
password: Option<String>,
password_env_var: Option<String>,
) -> PyResult<Cow<[u8]>> {
keyfile::decrypt_keyfile_data(keyfile_data, password, password_env_var)
.map(Cow::from)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))
}
// keyfile module with functions
fn register_keyfile_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let keyfile_module = PyModule::new(main_module.py(), "keyfile")?;
keyfile_module.add_function(wrap_pyfunction!(
py_serialized_keypair_to_keyfile_data,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
py_deserialize_keypair_from_keyfile_data,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(py_validate_password, &keyfile_module)?)?;
keyfile_module.add_function(wrap_pyfunction!(py_ask_password, &keyfile_module)?)?;
keyfile_module.add_function(wrap_pyfunction!(
keyfile::keyfile_data_is_encrypted_nacl,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
keyfile::keyfile_data_is_encrypted_ansible,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
keyfile::keyfile_data_is_encrypted_legacy,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
keyfile::keyfile_data_is_encrypted,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
keyfile::keyfile_data_encryption_method,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
py_legacy_encrypt_keyfile_data,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(
py_get_password_from_environment,
&keyfile_module
)?)?;
keyfile_module.add_function(wrap_pyfunction!(py_encrypt_keyfile_data, &keyfile_module)?)?;
keyfile_module.add_function(wrap_pyfunction!(py_decrypt_keyfile_data, &keyfile_module)?)?;
keyfile_module.add_class::<PyKeyfile>()?;
main_module.add_submodule(&keyfile_module)
}
fn register_keypair_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let keypair_module = PyModule::new(main_module.py(), "keypair")?;
keypair_module.add_class::<PyKeypair>()?;
main_module.add_submodule(&keypair_module)
}
#[pyfunction(name = "get_ss58_format")]
fn py_get_ss58_format(ss58_address: &str) -> PyResult<u16> {
crate::utils::get_ss58_format(ss58_address).map_err(|e| PyErr::new::<PyValueError, _>(e))
}
#[pyfunction(name = "is_valid_ed25519_pubkey")]
fn py_is_valid_ed25519_pubkey(public_key: &Bound<'_, PyAny>) -> PyResult<bool> {
Python::attach(|_py| {
if public_key.is_instance_of::<PyString>() {
Ok(crate::utils::is_string_valid_ed25519_pubkey(
public_key.extract()?,
))
} else if public_key.is_instance_of::<PyBytes>() {
Ok(crate::utils::are_bytes_valid_ed25519_pubkey(
public_key.extract()?,
))
} else {
Err(PyErr::new::<PyValueError, _>(
"'public_key' must be a string or bytes",
))
}
})
}
#[pyfunction(name = "is_valid_bittensor_address_or_public_key")]
fn py_is_valid_bittensor_address_or_public_key(address: &Bound<'_, PyAny>) -> bool {
Python::attach(|_py| {
if address.is_instance_of::<PyString>() {
let Ok(address_str) = address.extract() else {
return false;
};
crate::utils::is_valid_bittensor_address_or_public_key(address_str)
} else if address.is_instance_of::<PyBytes>() {
let Ok(address_bytes) = address.extract() else {
return false;
};
let Ok(address_str) = str::from_utf8(address_bytes) else {
return false;
};
crate::utils::is_valid_bittensor_address_or_public_key(address_str)
} else {
false
}
})
}
fn register_utils_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let utils_module = PyModule::new(main_module.py(), "utils")?;
utils_module.add_function(wrap_pyfunction!(
crate::utils::is_valid_ss58_address,
&utils_module
)?)?;
utils_module.add_function(wrap_pyfunction!(py_get_ss58_format, &utils_module)?)?;
utils_module.add_function(wrap_pyfunction!(
crate::utils::is_valid_ss58_address,
&utils_module
)?)?;
utils_module.add_function(wrap_pyfunction!(py_is_valid_ed25519_pubkey, &utils_module)?)?;
utils_module.add_function(wrap_pyfunction!(
py_is_valid_bittensor_address_or_public_key,
&utils_module
)?)?;
utils_module.add("SS58_FORMAT", crate::utils::SS58_FORMAT)?;
main_module.add_submodule(&utils_module)
}
fn register_wallet_module(main_module: &Bound<'_, PyModule>) -> PyResult<()> {
let wallet_module = PyModule::new(main_module.py(), "wallet")?;
wallet_module.add_function(wrap_pyfunction!(
crate::wallet::display_mnemonic_msg,
&wallet_module
)?)?;
wallet_module.add_class::<Wallet>()?;
main_module.add_submodule(&wallet_module)
}
fn get_attribute_string(
py: Python,
obj: &Bound<PyAny>,
attr_name: &str,
) -> PyResult<Option<String>> {
match obj.getattr(attr_name) {
Ok(attr) => {
if attr.is_none() {
Ok(None)
} else {
let value: String = attr.extract()?;
Ok(Some(value))
}
}
Err(e) => {
if e.is_instance_of::<pyo3::exceptions::PyAttributeError>(py) {
Ok(None)
} else {
Err(e)
}
}
}
}
// Implement the Python wrappers for the Rust structs
// For example, the Wallet class:
#[pyclass(subclass)]
pub struct Wallet {
pub inner: RustWallet,
}
#[pymethods]
impl Wallet {
#[new]
#[pyo3(signature = (name=None, hotkey=None, path=None, config=None))]
fn new(
name: Option<String>,
hotkey: Option<String>,
path: Option<String>,
config: Option<Py<PyAny>>,
py: Python,
) -> PyResult<Self> {
// parse python config object if passed
let (conf_name, conf_hotkey, conf_path) = if let Some(config_obj) = config {
let config_ref = config_obj.bind(py);
// parse python config.wallet object if exist in config object
match config_ref.getattr("wallet") {
Ok(wallet_obj) if !wallet_obj.is_none() => {
let wallet_ref = wallet_obj.as_ref();
// assign values instead of default ones
(
get_attribute_string(py, wallet_ref, "name")?,
get_attribute_string(py, wallet_ref, "hotkey")?,
get_attribute_string(py, wallet_ref, "path")?,
)
}
// check if config.wallet itself was passed as config
_ => (
get_attribute_string(py, config_ref, "name")?,
get_attribute_string(py, config_ref, "hotkey")?,
get_attribute_string(py, config_ref, "path")?,
),
}
} else {
(None, None, None)
};
let config = crate::config::Config::new(conf_name, conf_hotkey, conf_path);
let rust_wallet = RustWallet::new(name, hotkey, path, Some(config));
Ok(Wallet { inner: rust_wallet })
}
fn __str__(&self) -> PyResult<String> {
Ok(self.inner.to_string())
}
fn __repr__(&self) -> PyResult<String> {
self.__str__()
}
/// Accept specific arguments from parser.
#[classmethod]
#[pyo3(signature = (parser, prefix = None))]
pub fn add_args(
_: &Bound<'_, PyType>,
parser: &Bound<'_, PyAny>,
prefix: Option<String>,
py: Python,
) -> PyResult<Py<PyAny>> {
let default_name =
env::var("BT_WALLET_NAME").unwrap_or_else(|_| BT_WALLET_NAME.to_string());
let default_hotkey =
env::var("BT_WALLET_HOTKEY").unwrap_or_else(|_| BT_WALLET_HOTKEY.to_string());
let default_path =
env::var("BT_WALLET_PATH").unwrap_or_else(|_| BT_WALLET_PATH.to_string());
let prefix_str = if let Some(value) = prefix {
format!("\"{value}\"")
} else {
"None".to_string()
};
let code = format!(
r#"
prefix = {prefix_str}
prefix_str = "" if prefix is None else prefix + "."
try:
parser.add_argument(
"--" + prefix_str + "wallet.name",
required=False,
default="{default_name}",
help="The name of the wallet to unlock for running bittensor "
"(name mock is reserved for mocking this wallet)",
)
parser.add_argument(
"--" + prefix_str + "wallet.hotkey",
required=False,
default="{default_hotkey}",
help="The name of the wallet's hotkey.",
)
parser.add_argument(
"--" + prefix_str + "wallet.path",
required=False,
default="{default_path}",
help="The path to your bittensor wallets",
)
except argparse.ArgumentError:
pass"#,
);
let code_cstr = CString::new(code).map_err(|e| PyErr::new::<PyValueError, _>(e.to_string()))?;
let dict = [("parser", parser.as_any())].into_py_dict(py)?;
py.run(
&code_cstr,
Some(&dict),
None,
)?;
Ok(parser.clone().unbind())
}
// Wallet methods
#[pyo3(text_signature = "($self)")]
fn to_string(&self) -> String {
self.inner.to_string()
}
#[pyo3(text_signature = "($self)")]
fn debug_string(&self) -> String {
format!("{:?}", self.inner)
}
#[pyo3(
signature = (coldkey_use_password=Some(true), hotkey_use_password=Some(false), save_coldkey_to_env=Some(false), save_hotkey_to_env=Some(false), coldkey_password=None, hotkey_password=None, overwrite=Some(false), suppress=Some(false))
)]
fn create_if_non_existent(
&mut self,
coldkey_use_password: Option<bool>,
hotkey_use_password: Option<bool>,
save_coldkey_to_env: Option<bool>,
save_hotkey_to_env: Option<bool>,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: Option<bool>,
suppress: Option<bool>,
) -> PyResult<Self> {
let result = self
.inner
.create_if_non_existent(
coldkey_use_password.unwrap_or(true),
hotkey_use_password.unwrap_or(false),
save_coldkey_to_env.unwrap_or(false),
save_hotkey_to_env.unwrap_or(false),
coldkey_password,
hotkey_password,
overwrite.unwrap_or(false),
suppress.unwrap_or(false),
)
.map_err(|e| match e {
WalletError::InvalidInput(_) | WalletError::KeyGeneration(_) => {
PyErr::new::<PyValueError, _>(e.to_string())
}
_ => PyErr::new::<PyKeyFileError, _>(format!("Failed to create wallet: {:?}", e)),
})?;
Ok(Wallet { inner: result })
}
/// 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.
#[pyo3(signature = (coldkey_use_password=true, hotkey_use_password=false, save_coldkey_to_env=false, save_hotkey_to_env=false, coldkey_password=None, hotkey_password=None, overwrite=false, suppress=false))]
pub fn create(
&mut self,
coldkey_use_password: Option<bool>,
hotkey_use_password: Option<bool>,
save_coldkey_to_env: Option<bool>,
save_hotkey_to_env: Option<bool>,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: Option<bool>,
suppress: Option<bool>,
) -> PyResult<Self> {
let result = self
.inner
.create(
coldkey_use_password.unwrap_or(true),
hotkey_use_password.unwrap_or(false),
save_coldkey_to_env.unwrap_or(false),
save_hotkey_to_env.unwrap_or(false),
coldkey_password,
hotkey_password,
overwrite.unwrap_or(false),
suppress.unwrap_or(false),
)
.map_err(|e| match e {
WalletError::InvalidInput(_) | WalletError::KeyGeneration(_) => {
PyErr::new::<PyValueError, _>(e.to_string())
}
_ => PyErr::new::<PyKeyFileError, _>(format!("Failed to create wallet: {:?}", e)),
})?;
Ok(Wallet { inner: result })
}
#[pyo3(
signature = (coldkey_use_password=Some(true), hotkey_use_password=Some(false), save_coldkey_to_env=Some(false), save_hotkey_to_env=Some(false), coldkey_password=None, hotkey_password=None, overwrite=Some(false), suppress=Some(false))
)]
fn recreate(
&mut self,
coldkey_use_password: Option<bool>,
hotkey_use_password: Option<bool>,
save_coldkey_to_env: Option<bool>,
save_hotkey_to_env: Option<bool>,
coldkey_password: Option<String>,
hotkey_password: Option<String>,
overwrite: Option<bool>,
suppress: Option<bool>,
) -> PyResult<Self> {
let result = self
.inner
.recreate(
coldkey_use_password.unwrap_or(true),
hotkey_use_password.unwrap_or(false),
save_coldkey_to_env.unwrap_or(false),
save_hotkey_to_env.unwrap_or(false),
coldkey_password,
hotkey_password,
overwrite.unwrap_or(false),
suppress.unwrap_or(false),
)
.map_err(|e| match e {
WalletError::InvalidInput(_) | WalletError::KeyGeneration(_) => {
PyErr::new::<PyValueError, _>(e.to_string())
}
_ => PyErr::new::<PyKeyFileError, _>(format!("Failed to recreate wallet: {:?}", e)),
})?;
Ok(Wallet { inner: result })
}
#[pyo3(signature = (password=None))]
fn get_coldkey(&self, password: Option<String>) -> PyResult<PyKeypair> {
let keypair = self
.inner
.get_coldkey(password)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
#[pyo3(signature = (password=None))]
fn get_coldkeypub(&self, password: Option<String>) -> PyResult<PyKeypair> {
let keypair = self
.inner
.get_coldkeypub(password)
.map_err(|e| PyErr::new::<PyKeyFileError, _>(e))?;
Ok(PyKeypair { inner: keypair })
}
#[pyo3(signature = (password=None))]
fn get_hotkey(&self, password: Option<String>) -> PyResult<PyKeypair> {