rtao-upstream-core 0.490.0

Unofficial republish of bittensor-core from RaoFoundation/subtensor v490 with rtao's reviewed core patch (the Ed25519 erasure repair and the injectable Ledger transport), for rtao; not affiliated with or endorsed by its authors.
Documentation
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
//! Substrate `sp-core` key primitives (absorbed from `py-sp-core`).
//!
//! Keypair derivation, signing, verification, sealed-box encryption, and
//! SS58 codec — built against the same `sp-core` revision as the runtime, so
//! client crypto can never drift from the chain's.

// Client-side code: slicing and arithmetic on locally validated buffers is
// the norm here, and this crate never runs inside the runtime.
#![allow(clippy::indexing_slicing, clippy::arithmetic_side_effects)]

use ed25519_zebra::{SigningKey, VerificationKey};
#[cfg(feature = "host")]
use sodiumoxide::crypto::box_;
#[cfg(feature = "host")]
use sodiumoxide::crypto::sealedbox;
#[cfg(feature = "host")]
use sodiumoxide::crypto::sign::ed25519 as sign_ed25519;
use sp_core::crypto::{
    AccountId32, CryptoType, DeriveError, DeriveJunction, Pair as PairT, SecretStringError,
    Ss58Codec,
};
use sp_core::{ed25519, sr25519, ByteArray};
use zeroize::Zeroizing;

use crate::error::CoreError;

mod base58;
mod hashed;
pub use hashed::{verify_hashed_authorization, HashedKeypair};
mod falcon;
mod mldsa;
pub use mldsa::{verify_mldsa_authorization, MldsaKeypair, ROLE_TRANSACTION};
mod receiving;
pub use receiving::{
    decode_hashed_receiving_address, decode_mldsa_receiving_address,
    encode_hashed_receiving_address, encode_mldsa_receiving_address,
};
#[cfg(feature = "host")]
mod encrypted_json;

/// Crypto type codes, matching the py-substrate-interface / btwallet convention.
pub const CRYPTO_ED25519: u8 = 0;
pub const CRYPTO_SR25519: u8 = 1;
pub const CRYPTO_ECDSA: u8 = 2;
/// Length of a compressed secp256k1 public key.
pub const ECDSA_PUBLIC_KEY_LEN: usize = sp_core::ecdsa::PUBLIC_KEY_SERIALIZED_SIZE;
/// Raw signature lengths per crypto type (without a MultiSignature variant byte).
pub const ED25519_SIGNATURE_LEN: usize = ed25519::SIGNATURE_SERIALIZED_SIZE;
pub const SR25519_SIGNATURE_LEN: usize = sr25519::SIGNATURE_SERIALIZED_SIZE;
pub const ECDSA_SIGNATURE_LEN: usize = sp_core::ecdsa::SIGNATURE_SERIALIZED_SIZE;
/// Versioned rotating commitment wrapper; initially wraps sr25519.
pub const CRYPTO_HASHED: u8 = 4;
pub const CRYPTO_HASHED_ED25519: u8 = 6;
/// SDK identifier; distinct from the ML-DSA wire algorithm value 4.
pub const CRYPTO_MLDSA65: u8 = 7;
/// Fixed-key ML-DSA-65. Preserve code 7 and all original rotating identities.
pub const CRYPTO_MLDSA65_FIXED: u8 = 8;

pub const CRYPTO_FALCON512: u8 = 9;
pub const CRYPTO_FALCON512_HASHED: u8 = 10;
pub const CRYPTO_FALCON1024: u8 = 11;
pub const CRYPTO_FALCON1024_HASHED: u8 = 12;

pub fn is_falcon_crypto(crypto_type: u8) -> bool {
    matches!(
        crypto_type,
        CRYPTO_FALCON512 | CRYPTO_FALCON512_HASHED | CRYPTO_FALCON1024 | CRYPTO_FALCON1024_HASHED
    )
}

pub fn is_pq_crypto(crypto_type: u8) -> bool {
    is_mldsa_crypto(crypto_type) || is_falcon_crypto(crypto_type)
}

pub fn is_fixed_pq_crypto(crypto_type: u8) -> bool {
    matches!(
        crypto_type,
        CRYPTO_MLDSA65_FIXED | CRYPTO_FALCON512 | CRYPTO_FALCON1024
    )
}

pub fn pq_profile(crypto_type: u8) -> Option<u8> {
    match crypto_type {
        CRYPTO_MLDSA65 => Some(4),
        CRYPTO_MLDSA65_FIXED => Some(5),
        CRYPTO_FALCON512_HASHED => Some(6),
        CRYPTO_FALCON512 => Some(7),
        CRYPTO_FALCON1024_HASHED => Some(8),
        CRYPTO_FALCON1024 => Some(9),
        _ => None,
    }
}

pub fn is_mldsa_crypto(crypto_type: u8) -> bool {
    matches!(crypto_type, CRYPTO_MLDSA65 | CRYPTO_MLDSA65_FIXED)
}

pub fn is_hashed_crypto(crypto_type: u8) -> bool {
    matches!(crypto_type, CRYPTO_HASHED | CRYPTO_HASHED_ED25519)
}

pub fn is_rotating_crypto(crypto_type: u8) -> bool {
    is_hashed_crypto(crypto_type)
        || matches!(
            crypto_type,
            CRYPTO_MLDSA65 | CRYPTO_FALCON512_HASHED | CRYPTO_FALCON1024_HASHED
        )
}

/// Compose account mode with a signing scheme; omitted mode preserves legacy codes.
pub fn account_crypto_type(crypto_type: u8, mode: Option<&str>) -> Result<u8, CoreError> {
    if is_falcon_crypto(crypto_type) {
        let (fixed, hashed) = if matches!(crypto_type, CRYPTO_FALCON512 | CRYPTO_FALCON512_HASHED) {
            (CRYPTO_FALCON512, CRYPTO_FALCON512_HASHED)
        } else {
            (CRYPTO_FALCON1024, CRYPTO_FALCON1024_HASHED)
        };
        return match mode {
            None => Ok(crypto_type),
            Some("hashed") => Ok(hashed),
            Some("standard") => Ok(fixed),
            _ => Err(crypto_err("account type must be standard or hashed")),
        };
    }
    if is_mldsa_crypto(crypto_type) {
        return match mode {
            None => Ok(crypto_type),
            Some("hashed") => Ok(CRYPTO_MLDSA65),
            Some("standard") => Ok(CRYPTO_MLDSA65_FIXED),
            _ => Err(crypto_err("account type must be standard or hashed")),
        };
    }
    let Some(mode) = mode else {
        return match crypto_type {
            CRYPTO_SR25519 | CRYPTO_ED25519 | CRYPTO_HASHED | CRYPTO_HASHED_ED25519 => {
                Ok(crypto_type)
            }
            _ => Err(crypto_err("unsupported signing scheme")),
        };
    };
    let scheme = match crypto_type {
        CRYPTO_SR25519 | CRYPTO_HASHED => CRYPTO_SR25519,
        CRYPTO_ED25519 | CRYPTO_HASHED_ED25519 => CRYPTO_ED25519,
        _ => return Err(crypto_err("unsupported signing scheme")),
    };
    match (mode, scheme) {
        ("standard", CRYPTO_SR25519) => Ok(CRYPTO_SR25519),
        ("standard", CRYPTO_ED25519) => Ok(CRYPTO_ED25519),
        ("hashed", CRYPTO_SR25519) => Ok(CRYPTO_HASHED),
        ("hashed", CRYPTO_ED25519) => Ok(CRYPTO_HASHED_ED25519),
        _ => Err(crypto_err("account type must be standard or hashed")),
    }
}

pub const DEFAULT_SS58_FORMAT: u16 = 42;

fn crypto_err(msg: impl Into<String>) -> CoreError {
    CoreError::Crypto(msg.into())
}

#[cfg(feature = "host")]
pub(crate) fn ensure_sodium() -> Result<(), CoreError> {
    sodiumoxide::init().map_err(|_| crypto_err("failed to initialize libsodium"))?;
    Ok(())
}

// sp-core's CryptoBytes has several AsRef impls; pin down the byte view.
fn as_bytes<T: AsRef<[u8]>>(value: &T) -> Vec<u8> {
    value.as_ref().to_vec()
}

/// Decode the 32-byte account identity. Hashed identities are commitments, not
/// signing public keys; the historical function name remains for compatibility.
pub fn public_key_from_ss58(ss58_address: &str) -> Result<[u8; 32], CoreError> {
    let account = AccountId32::from_ss58check(ss58_address)
        .map_err(|e| crypto_err(format!("invalid ss58 address: {e:?}")))?;
    Ok(account.into())
}

/// ss58 rendering, byte-identical to sp-core's `to_ss58check_with_version`
/// but ~6x faster (see `base58.rs`); every decoded account id goes through
/// here, thousands per storage-map page / metagraph payload.
pub fn ss58_from_public(public_key: [u8; 32], ss58_format: u16) -> String {
    // "SS58PRE" ++ prefix (1-2 bytes) ++ key (32) ++ checksum (2)
    let mut buf = [0u8; 7 + 2 + 32 + 2];
    buf[..7].copy_from_slice(b"SS58PRE");
    let ident = ss58_format & 0b0011_1111_1111_1111;
    let prefix_len = if ident < 64 {
        buf[7] = ident as u8;
        1
    } else {
        // Two-byte prefix encoding per the ss58 registry spec.
        buf[7] = (((ident & 0b0000_0000_1111_1100) >> 2) as u8) | 0b0100_0000;
        buf[8] = ((ident >> 8) as u8) | (((ident & 0b11) as u8) << 6);
        2
    };
    buf[7 + prefix_len..7 + prefix_len + 32].copy_from_slice(&public_key);
    let body_end = 7 + prefix_len + 32;
    let checksum = sp_core::hashing::blake2_512(&buf[..body_end]);
    buf[body_end] = checksum[0];
    buf[body_end + 1] = checksum[1];
    base58::base58_encode(&buf[7..body_end + 2])
}

/// Account id of a secp256k1 public key: `blake2_256(compressed_pubkey)`,
/// the `MultiSigner::Ecdsa` -> `AccountId32` mapping the chain uses.
pub fn account_id_from_ecdsa_public(public_key: &[u8]) -> Result<[u8; 32], CoreError> {
    let compressed = <[u8; ECDSA_PUBLIC_KEY_LEN]>::try_from(public_key).map_err(|_| {
        crypto_err(format!(
            "ecdsa public key must be {ECDSA_PUBLIC_KEY_LEN} bytes (compressed secp256k1)"
        ))
    })?;
    if !matches!(compressed[0], 0x02 | 0x03) {
        return Err(crypto_err(
            "ecdsa public key must be compressed (0x02/0x03 prefix)",
        ));
    }
    Ok(sp_core::hashing::blake2_256(&compressed))
}

/// SS58 address of a compressed secp256k1 public key.
pub fn ss58_from_ecdsa_public(public_key: &[u8], ss58_format: u16) -> Result<String, CoreError> {
    Ok(ss58_from_public(
        account_id_from_ecdsa_public(public_key)?,
        ss58_format,
    ))
}

fn verify_with_crypto(
    crypto_type: u8,
    public_key: &[u8; 32],
    message: &[u8],
    signature: &[u8],
) -> Result<bool, CoreError> {
    match crypto_type {
        CRYPTO_SR25519 => {
            let public = sr25519::Public::from_raw(*public_key);
            let sig = sr25519::Signature::from_slice(signature)
                .map_err(|_| crypto_err("invalid sr25519 signature length"))?;
            Ok(sr25519::Pair::verify(&sig, message, &public))
        }
        CRYPTO_ED25519 => {
            let public = ed25519::Public::from_raw(*public_key);
            let sig = ed25519::Signature::from_slice(signature)
                .map_err(|_| crypto_err("invalid ed25519 signature length"))?;
            Ok(ed25519::Pair::verify(&sig, message, &public))
        }
        CRYPTO_HASHED | CRYPTO_HASHED_ED25519 => Ok(hashed::verify_message(
            crypto_type,
            public_key,
            message,
            signature,
        )),
        other => Err(crypto_err(format!("unknown crypto type {other}"))),
    }
}

#[cfg(feature = "host")]
fn ed25519_to_x25519_pk(public_key: &[u8; 32]) -> Result<box_::PublicKey, CoreError> {
    ensure_sodium()?;
    let ed25519_pk = sign_ed25519::PublicKey::from_slice(public_key)
        .ok_or_else(|| crypto_err("invalid ed25519 public key"))?;
    sign_ed25519::to_curve25519_pk(&ed25519_pk)
        .map_err(|_| crypto_err("failed to convert ed25519 public key to x25519"))
}

fn ed25519_seed(pair: &Zeroizing<SigningKey>) -> &[u8] {
    let pair: &SigningKey = pair;
    pair.as_ref()
}

fn ed25519_public(pair: &Zeroizing<SigningKey>) -> [u8; 32] {
    let pair: &SigningKey = pair;
    VerificationKey::from(pair).into()
}

#[cfg(feature = "host")]
fn ed25519_x25519_from_pair(
    pair: &Zeroizing<SigningKey>,
) -> Result<(box_::PublicKey, box_::SecretKey), CoreError> {
    ensure_sodium()?;
    let seed = sign_ed25519::Seed::from_slice(ed25519_seed(pair))
        .ok_or_else(|| crypto_err("failed to derive x25519 keypair for decryption"))?;
    let (pk, sk) = sign_ed25519::keypair_from_seed(&seed);
    let x25519_pk = sign_ed25519::to_curve25519_pk(&pk)
        .map_err(|_| crypto_err("failed to derive x25519 keypair for decryption"))?;
    let x25519_sk = sign_ed25519::to_curve25519_sk(&sk)
        .map_err(|_| crypto_err("failed to derive x25519 keypair for decryption"))?;
    Ok((x25519_pk, x25519_sk))
}

struct WipingSeed(Zeroizing<[u8; 32]>);

impl Default for WipingSeed {
    fn default() -> Self {
        Self(Zeroizing::new([0; 32]))
    }
}

impl Clone for WipingSeed {
    fn clone(&self) -> Self {
        let mut clone = Self::default();
        clone.as_mut().copy_from_slice(self.as_ref());
        clone
    }
}

impl AsRef<[u8]> for WipingSeed {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl AsMut<[u8]> for WipingSeed {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0[..]
    }
}

const HDKD_PREIMAGE_LEN: usize = 1 + 11 + 32 + 32;

/// Internal Ed25519 derivation owner. Both its seed and expanded signing key
/// erase themselves on every return, error, panic, and final drop path.
struct WipingEd25519Pair {
    secret: Zeroizing<SigningKey>,
}

impl WipingEd25519Pair {
    fn into_secret(self) -> Zeroizing<SigningKey> {
        self.secret
    }

    fn seed(&self) -> WipingSeed {
        let mut seed = WipingSeed::default();
        seed.as_mut().copy_from_slice(ed25519_seed(&self.secret));
        seed
    }
}

impl CryptoType for WipingEd25519Pair {
    type Pair = Self;
}

impl PairT for WipingEd25519Pair {
    type Public = ed25519::Public;
    type Seed = WipingSeed;
    type Signature = ed25519::Signature;

    fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError> {
        let secret =
            SigningKey::try_from(seed).map_err(|_| SecretStringError::InvalidSeedLength)?;
        Ok(Self {
            secret: Zeroizing::new(secret),
        })
    }

    fn derive<Iter: Iterator<Item = DeriveJunction>>(
        &self,
        path: Iter,
        _seed: Option<Self::Seed>,
    ) -> Result<(Self, Option<Self::Seed>), DeriveError> {
        let mut seed = self.seed();
        for junction in path {
            match junction {
                DeriveJunction::Soft(_) => return Err(DeriveError::SoftKeyInPath),
                DeriveJunction::Hard(chain_code) => {
                    // The SCALE encoding of ("Ed25519HDKD", seed, chain_code):
                    // compact length 11 (0x2c), the label, then both arrays.
                    // A fixed wiping buffer replaces `using_encoded`, whose
                    // temporary heap Vec would hold the parent seed unwiped.
                    let mut preimage = Zeroizing::new([0u8; HDKD_PREIMAGE_LEN]);
                    preimage[0] = 0x2c;
                    preimage[1..12].copy_from_slice(b"Ed25519HDKD");
                    preimage[12..44].copy_from_slice(&seed.0[..]);
                    preimage[44..].copy_from_slice(&chain_code);
                    let derived = Zeroizing::new(sp_core::hashing::blake2_256(&preimage[..]));
                    seed.0.copy_from_slice(&derived[..]);
                }
            }
        }
        Ok((Self::from_seed(&seed), Some(seed)))
    }

    fn public(&self) -> Self::Public {
        ed25519::Public::from_raw(ed25519_public(&self.secret))
    }

    fn sign(&self, message: &[u8]) -> Self::Signature {
        Self::Signature::from_raw(self.secret.sign(message).to_bytes())
    }

    fn verify<M: AsRef<[u8]>>(
        signature: &Self::Signature,
        message: M,
        public: &Self::Public,
    ) -> bool {
        ed25519::Pair::verify(signature, message, public)
    }

    fn to_raw_vec(&self) -> Vec<u8> {
        ed25519_seed(&self.secret).to_vec()
    }
}

// Each Keypair holds exactly one variant; the size skew between ed25519 and
// public-only is irrelevant here.
#[allow(clippy::large_enum_variant)]
pub enum KeypairInner {
    Ed25519(Zeroizing<SigningKey>),
    Sr25519(sr25519::Pair),
    Hashed(HashedKeypair),
    Mldsa(MldsaKeypair),
    PublicOnly {
        public_key: [u8; 32],
        crypto_type: u8,
    },
}

impl KeypairInner {
    fn private_key_bytes(&self) -> Option<Vec<u8>> {
        match self {
            KeypairInner::Ed25519(pair) => Some(ed25519_seed(pair).to_vec()),
            KeypairInner::Sr25519(pair) => Some(pair.to_raw_vec()),
            KeypairInner::Hashed(pair) => pair.master_seed().map(|seed| seed.to_vec()),
            KeypairInner::Mldsa(pair) => pair.master_seed().map(|seed| seed.to_vec()),
            KeypairInner::PublicOnly { .. } => None,
        }
    }
}

/// A native keypair or a versioned hashed account backed by workspace crypto.
pub struct Keypair {
    inner: KeypairInner,
    ss58_format: u16,
    /// The BIP39 phrase this keypair was derived from, when known and
    /// sufficient on its own to re-derive the key (no derivation password).
    /// Written to keyfiles as ``secretPhrase`` for parity with the legacy
    /// btwallet format that third-party tools parse.
    mnemonic: Option<Zeroizing<String>>,
    /// The raw seed this keypair was derived from, when known. Written to
    /// keyfiles as ``secretSeed`` (legacy-format parity).
    seed: Option<Zeroizing<Vec<u8>>>,
}

impl Keypair {
    pub fn account_type(&self) -> &'static str {
        if is_rotating_crypto(self.crypto_type()) {
            "hashed"
        } else {
            "standard"
        }
    }

    pub fn signing_scheme(&self) -> &'static str {
        match self.crypto_type() {
            CRYPTO_HASHED | CRYPTO_SR25519 => "sr25519",
            CRYPTO_HASHED_ED25519 | CRYPTO_ED25519 => "ed25519",
            CRYPTO_MLDSA65 | CRYPTO_MLDSA65_FIXED => "mldsa65",
            CRYPTO_FALCON512 | CRYPTO_FALCON512_HASHED => "falcon512",
            CRYPTO_FALCON1024 | CRYPTO_FALCON1024_HASHED => "falcon1024",
            _ => "unknown",
        }
    }
    /// Public-only or full keypair from SS58 address and/or raw public key bytes.
    pub fn new(
        ss58_address: Option<&str>,
        public_key: Option<&[u8]>,
        crypto_type: u8,
        ss58_format: u16,
    ) -> Result<Self, CoreError> {
        match crypto_type {
            CRYPTO_SR25519
            | CRYPTO_ED25519
            | CRYPTO_HASHED
            | CRYPTO_HASHED_ED25519
            | CRYPTO_MLDSA65
            | CRYPTO_MLDSA65_FIXED
            | CRYPTO_FALCON512
            | CRYPTO_FALCON512_HASHED
            | CRYPTO_FALCON1024
            | CRYPTO_FALCON1024_HASHED => {}
            other => return Err(crypto_err(format!("unknown crypto type {other}"))),
        }

        let public_key = match (ss58_address, public_key) {
            (Some(addr), None) => public_key_from_ss58(addr)?,
            (None, Some(pk)) => <[u8; 32]>::try_from(pk)
                .map_err(|_| crypto_err("public key must be exactly 32 bytes"))?,
            (Some(addr), Some(pk)) => {
                let from_addr = public_key_from_ss58(addr)?;
                let from_pk = <[u8; 32]>::try_from(pk)
                    .map_err(|_| crypto_err("public key must be exactly 32 bytes"))?;
                if from_addr != from_pk {
                    return Err(crypto_err(
                        "ss58 address and public key refer to different accounts",
                    ));
                }
                from_pk
            }
            (None, None) => {
                return Err(crypto_err(
                    "no ss58 formatted address or public key provided",
                ));
            }
        };

        Ok(Self {
            inner: KeypairInner::PublicOnly {
                public_key,
                crypto_type,
            },
            ss58_format,
            mnemonic: None,
            seed: None,
        })
    }

    /// Derive a keypair from a BIP39 mnemonic (with optional password).
    pub fn from_mnemonic(
        mnemonic: &str,
        crypto_type: u8,
        password: Option<&str>,
    ) -> Result<Self, CoreError> {
        let (inner, seed) = match crypto_type {
            crypto if is_pq_crypto(crypto) => {
                let phrase = bip39::Mnemonic::parse_in(bip39::Language::English, mnemonic)
                    .map_err(|_| crypto_err("invalid post-quantum mnemonic"))?;
                if phrase.word_count() != 24 {
                    return Err(crypto_err(
                        "post-quantum wallets require a 24-word mnemonic with 256-bit entropy",
                    ));
                }
                let expanded = Zeroizing::new(phrase.to_seed(password.unwrap_or("")));
                let seed = Zeroizing::new(expanded[..32].to_vec());
                (
                    KeypairInner::Mldsa(MldsaKeypair::from_seed(&seed, crypto_type)?),
                    seed,
                )
            }
            CRYPTO_SR25519 => {
                let (pair, seed) = sr25519::Pair::from_phrase(mnemonic, password)
                    .map_err(|e| crypto_err(format!("invalid mnemonic: {e:?}")))?;
                (KeypairInner::Sr25519(pair), Zeroizing::new(seed.to_vec()))
            }
            CRYPTO_ED25519 => {
                let (pair, seed) = WipingEd25519Pair::from_phrase(mnemonic, password)
                    .map_err(|e| crypto_err(format!("invalid mnemonic: {e:?}")))?;
                (
                    KeypairInner::Ed25519(pair.into_secret()),
                    Zeroizing::new(seed.as_ref().to_vec()),
                )
            }
            CRYPTO_HASHED | CRYPTO_HASHED_ED25519 => {
                let (_, seed) = sr25519::Pair::from_phrase(mnemonic, password)
                    .map_err(|e| crypto_err(format!("invalid mnemonic: {e:?}")))?;
                (
                    KeypairInner::Hashed(HashedKeypair::from_seed(&seed, crypto_type)?),
                    Zeroizing::new(seed.to_vec()),
                )
            }
            other => return Err(crypto_err(format!("unknown crypto type {other}"))),
        };
        Ok(Self {
            inner,
            ss58_format: DEFAULT_SS58_FORMAT,
            // A phrase with a derivation password cannot re-derive the key on
            // its own, so only a passwordless phrase is kept (and written to
            // keyfiles); the derived seed is always sufficient.
            mnemonic: password
                .is_none()
                .then(|| Zeroizing::new(mnemonic.to_string())),
            seed: Some(seed),
        })
    }

    /// Derive a keypair from a 32-byte seed.
    pub fn from_seed(seed: &[u8], crypto_type: u8) -> Result<Self, CoreError> {
        let inner = match crypto_type {
            crypto if is_pq_crypto(crypto) => {
                KeypairInner::Mldsa(MldsaKeypair::from_seed(seed, crypto_type)?)
            }
            CRYPTO_SR25519 => KeypairInner::Sr25519(
                sr25519::Pair::from_seed_slice(seed)
                    .map_err(|e| crypto_err(format!("invalid seed: {e:?}")))?,
            ),
            CRYPTO_ED25519 => KeypairInner::Ed25519(
                WipingEd25519Pair::from_seed_slice(seed)
                    .map_err(|e| crypto_err(format!("invalid seed: {e:?}")))?
                    .into_secret(),
            ),
            CRYPTO_HASHED | CRYPTO_HASHED_ED25519 => {
                KeypairInner::Hashed(HashedKeypair::from_seed(seed, crypto_type)?)
            }
            other => return Err(crypto_err(format!("unknown crypto type {other}"))),
        };
        Ok(Self {
            inner,
            ss58_format: DEFAULT_SS58_FORMAT,
            mnemonic: None,
            seed: Some(Zeroizing::new(seed.to_vec())),
        })
    }

    /// Derive a keypair from a secret URI (e.g. "//Alice" or "<mnemonic>//hard/soft").
    pub fn from_uri(uri: &str, crypto_type: u8) -> Result<Self, CoreError> {
        if is_hashed_crypto(crypto_type) || is_pq_crypto(crypto_type) {
            return Err(crypto_err(
                "hashed and post-quantum wallets require a mnemonic or a 32-byte master seed; secret URIs are unsupported",
            ));
        }
        let inner = match crypto_type {
            CRYPTO_SR25519 => KeypairInner::Sr25519(
                sr25519::Pair::from_string(uri, None)
                    .map_err(|e| crypto_err(format!("invalid secret uri: {e:?}")))?,
            ),
            CRYPTO_ED25519 => KeypairInner::Ed25519(
                WipingEd25519Pair::from_string(uri, None)
                    .map_err(|e| crypto_err(format!("invalid secret uri: {e:?}")))?
                    .into_secret(),
            ),
            other => return Err(crypto_err(format!("unknown crypto type {other}"))),
        };
        // A URI may carry derivation junctions, so neither the phrase nor a
        // bare seed is retained.
        Ok(Self {
            inner,
            ss58_format: DEFAULT_SS58_FORMAT,
            mnemonic: None,
            seed: None,
        })
    }

    /// Derive a keypair from a hex-encoded private key or seed bytes.
    pub fn from_private_key(private_key: &str, crypto_type: u8) -> Result<Self, CoreError> {
        // Don't interpolate the hex error: it echoes offending secret characters.
        let private_key_vec = Zeroizing::new(
            hex::decode(private_key.trim_start_matches("0x"))
                .map_err(|_| crypto_err("invalid private_key hex string"))?,
        );

        if is_hashed_crypto(crypto_type) || is_pq_crypto(crypto_type) {
            return Self::from_seed(&private_key_vec, crypto_type);
        }

        let inner = match crypto_type {
            CRYPTO_SR25519 => {
                KeypairInner::Sr25519(sr25519::Pair::from_seed_slice(&private_key_vec).map_err(
                    |error| crypto_err(format!("invalid sr25519 private key: {error:?}")),
                )?)
            }
            CRYPTO_ED25519 => {
                let seed = if private_key_vec.len() >= 32 {
                    &private_key_vec[..32]
                } else {
                    return Err(crypto_err("ed25519 private key must be at least 32 bytes"));
                };
                KeypairInner::Ed25519(
                    WipingEd25519Pair::from_seed_slice(seed)
                        .map_err(|error| {
                            crypto_err(format!("invalid ed25519 private key: {error:?}"))
                        })?
                        .into_secret(),
                )
            }
            other => return Err(crypto_err(format!("unknown crypto type {other}"))),
        };

        Ok(Self {
            inner,
            ss58_format: DEFAULT_SS58_FORMAT,
            mnemonic: None,
            seed: None,
        })
    }

    /// Generate a fresh mnemonic with ``n_words`` (12/15/18/21/24).
    pub fn generate_mnemonic(n_words: usize) -> Result<String, CoreError> {
        use bip39::{Language, Mnemonic};

        if !matches!(n_words, 12 | 15 | 18 | 21 | 24) {
            return Err(crypto_err(format!(
                "unsupported mnemonic length {n_words}; expected 12, 15, 18, 21, or 24"
            )));
        }

        Mnemonic::generate_in(Language::English, n_words)
            .map(|mnemonic| mnemonic.to_string())
            .map_err(|error| crypto_err(format!("failed to generate mnemonic: {error}")))
    }

    /// Import a keypair from a PolkadotJS encrypted JSON keystore (v3).
    #[cfg(feature = "host")]
    pub fn from_encrypted_json(json_data: &str, passphrase: &str) -> Result<Self, CoreError> {
        encrypted_json::create_from_encrypted_json(json_data, passphrase)
    }

    pub fn crypto_type(&self) -> u8 {
        match &self.inner {
            KeypairInner::Ed25519(_) => CRYPTO_ED25519,
            KeypairInner::Sr25519(_) => CRYPTO_SR25519,
            KeypairInner::Hashed(key) => key.crypto_type(),
            KeypairInner::Mldsa(key) => match key.descriptor.algorithm {
                4 => CRYPTO_MLDSA65,
                5 => CRYPTO_MLDSA65_FIXED,
                6 => CRYPTO_FALCON512_HASHED,
                7 => CRYPTO_FALCON512,
                8 => CRYPTO_FALCON1024_HASHED,
                9 => CRYPTO_FALCON1024,
                _ => unreachable!("validated post-quantum profile"),
            },
            KeypairInner::PublicOnly { crypto_type, .. } => *crypto_type,
        }
    }

    /// Stable account identity. For hashed wallets, obtain the active signer
    /// separately with `hashed_public_key`, only when constructing its proof.
    pub fn public_key_bytes(&self) -> [u8; 32] {
        match &self.inner {
            KeypairInner::Ed25519(pair) => ed25519_public(pair),
            KeypairInner::Sr25519(pair) => pair.public().0,
            KeypairInner::Hashed(pair) => pair.account_id(),
            KeypairInner::Mldsa(pair) => pair.account_id(),
            KeypairInner::PublicOnly { public_key, .. } => *public_key,
        }
    }

    pub fn ss58_address(&self) -> String {
        ss58_from_public(self.public_key_bytes(), self.ss58_format)
    }

    pub fn ss58_format(&self) -> u16 {
        self.ss58_format
    }

    pub fn private_key_bytes(&self) -> Option<Vec<u8>> {
        self.inner.private_key_bytes()
    }

    /// The BIP39 phrase this keypair was derived from, when retained.
    pub fn mnemonic(&self) -> Option<&str> {
        self.mnemonic.as_deref().map(String::as_str)
    }

    /// The raw seed this keypair was derived from, when retained.
    pub fn seed_bytes(&self) -> Option<&[u8]> {
        self.seed.as_deref().map(Vec::as_slice)
    }

    #[cfg(feature = "host")]
    pub(crate) fn from_inner(inner: KeypairInner, ss58_format: u16) -> Self {
        Self {
            inner,
            ss58_format,
            mnemonic: None,
            seed: None,
        }
    }

    /// Sign a message; returns the raw 64-byte signature.
    pub fn sign(&self, message: &[u8]) -> Result<Vec<u8>, CoreError> {
        match &self.inner {
            KeypairInner::Ed25519(pair) => Ok(pair.sign(message).to_bytes().to_vec()),
            KeypairInner::Sr25519(pair) => Ok(as_bytes(&pair.sign(message))),
            KeypairInner::Hashed(_) => self.sign_hashed_message(message),
            KeypairInner::Mldsa(_) => Err(crypto_err(
                "post-quantum arbitrary message signing is not supported",
            )),
            KeypairInner::PublicOnly { .. } => {
                Err(crypto_err("no private key set to create signatures"))
            }
        }
    }

    /// Verify a signature. Matches btwallet's ``<Bytes>`` wrapping fallback.
    pub fn verify(&self, message: &[u8], signature: &[u8]) -> Result<bool, CoreError> {
        let public_key = self.public_key_bytes();
        let crypto_type = self.crypto_type();
        if verify_with_crypto(crypto_type, &public_key, message, signature)? {
            return Ok(true);
        }
        let wrapped = [b"<Bytes>", message, b"</Bytes>"].concat();
        verify_with_crypto(crypto_type, &public_key, &wrapped, signature)
    }

    /// Encrypt a message to this keypair's ed25519 public key (sealed box).
    #[cfg(feature = "host")]
    pub fn encrypt(&self, message: &[u8]) -> Result<Vec<u8>, CoreError> {
        if self.crypto_type() != CRYPTO_ED25519 {
            return Err(crypto_err(
                "encrypt/decrypt is only supported for ed25519 keypairs",
            ));
        }
        ensure_sodium()?;
        let x25519_pk = ed25519_to_x25519_pk(&self.public_key_bytes())?;
        Ok(sealedbox::seal(message, &x25519_pk))
    }

    /// Decrypt a sealed-box ciphertext with this ed25519 keypair's private key.
    #[cfg(feature = "host")]
    pub fn decrypt(&self, ciphertext: &[u8]) -> Result<Vec<u8>, CoreError> {
        if self.crypto_type() != CRYPTO_ED25519 {
            return Err(crypto_err(
                "encrypt/decrypt is only supported for ed25519 keypairs",
            ));
        }
        let KeypairInner::Ed25519(pair) = &self.inner else {
            return Err(crypto_err(
                "decryption requires a keypair with a private key",
            ));
        };
        ensure_sodium()?;
        let (x25519_pk, x25519_sk) = ed25519_x25519_from_pair(pair)?;
        sealedbox::open(ciphertext, &x25519_pk, &x25519_sk)
            .map_err(|_| crypto_err("decryption failed: invalid ciphertext or wrong key"))
    }

    /// Encrypt a message for a recipient SS58 address (ed25519 sealed box).
    #[cfg(feature = "host")]
    pub fn encrypt_for(
        ss58_address: &str,
        message: &[u8],
        crypto_type: u8,
    ) -> Result<Vec<u8>, CoreError> {
        let recipient = Self::new(Some(ss58_address), None, crypto_type, DEFAULT_SS58_FORMAT)?;
        recipient.encrypt(message)
    }
}

/// Verify exactly the supplied message bytes against an SS58 address.
///
/// Uses the same per-scheme verifier as [`verify`] (pinned Substrate
/// sr25519/ed25519 and the hashed-account message envelopes), without its
/// legacy `<Bytes>` wrapper retry. Invalid SS58 addresses, unsupported crypto
/// types and incorrect sr25519/ed25519 signature lengths return errors; other
/// signatures that do not verify return `Ok(false)`.
pub fn verify_strict(
    message: &[u8],
    signature: &[u8],
    ss58_address: &str,
    crypto_type: u8,
) -> Result<bool, CoreError> {
    let public_key = public_key_from_ss58(ss58_address)?;
    verify_with_crypto(crypto_type, &public_key, message, signature)
}

/// Verify a signature against an SS58 address without holding the secret key.
pub fn verify(
    message: &[u8],
    signature: &[u8],
    ss58_address: &str,
    crypto_type: u8,
) -> Result<bool, CoreError> {
    let public_key = public_key_from_ss58(ss58_address)?;
    if verify_with_crypto(crypto_type, &public_key, message, signature)? {
        return Ok(true);
    }
    let wrapped = [b"<Bytes>", message, b"</Bytes>"].concat();
    verify_with_crypto(crypto_type, &public_key, &wrapped, signature)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use sp_core::crypto::Ss58AddressFormat;

    use super::*;

    #[test]
    fn ss58_rendering_matches_sp_core() {
        let mut state = 0x243f_6a88_85a3_08d3u64;
        for format in [0u16, 2, 42, 63, 64, 255, 4096, 16383] {
            for i in 0..50u32 {
                let mut key = [0u8; 32];
                key[..4].copy_from_slice(&i.to_le_bytes());
                for b in &mut key[4..] {
                    state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
                    *b = (state >> 33) as u8;
                }
                assert_eq!(
                    ss58_from_public(key, format),
                    AccountId32::from(key)
                        .to_ss58check_with_version(Ss58AddressFormat::custom(format)),
                    "diverged for format {format}"
                );
            }
        }
    }

    #[test]
    fn alice_uri_matches_known_address() {
        let kp = Keypair::from_uri("//Alice", CRYPTO_SR25519).unwrap();
        assert_eq!(
            kp.ss58_address(),
            "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY"
        );
    }

    #[test]
    fn public_only_from_ss58_matches_full_key() {
        let full = Keypair::from_uri("//Alice", CRYPTO_SR25519).unwrap();
        let public = Keypair::new(Some(&full.ss58_address()), None, CRYPTO_SR25519, 42).unwrap();
        assert_eq!(public.ss58_address(), full.ss58_address());
        assert_eq!(public.public_key_bytes(), full.public_key_bytes());
    }

    #[test]
    fn sr25519_verify_roundtrip() {
        let kp = Keypair::from_uri("//Alice", CRYPTO_SR25519).unwrap();
        let message = b"hello";
        let sig = kp.sign(message).unwrap();
        assert!(kp.verify(message, &sig).unwrap());
    }

    #[test]
    fn ecdsa_ss58_matches_sp_core() {
        use sp_core::ecdsa;

        // sp-runtime's `MultiSigner::Ecdsa(pk).into_account()` is
        // `blake2_256(pk.as_ref())` over the 33-byte compressed key.
        let pair = ecdsa::Pair::from_string("//Alice", None).unwrap();
        let public = pair.public();
        let compressed: &[u8] = public.as_ref();
        assert_eq!(compressed.len(), ECDSA_PUBLIC_KEY_LEN);
        let expected = AccountId32::from(sp_core::hashing::blake2_256(compressed));
        let account = account_id_from_ecdsa_public(compressed).unwrap();
        assert_eq!(account, <[u8; 32]>::from(expected.clone()));
        for format in [0u16, 42, 4096] {
            assert_eq!(
                ss58_from_ecdsa_public(compressed, format).unwrap(),
                expected.to_ss58check_with_version(Ss58AddressFormat::custom(format))
            );
        }
    }

    #[test]
    fn ecdsa_ss58_rejects_non_compressed_keys() {
        assert!(account_id_from_ecdsa_public(&[0x02; 32]).is_err());
        assert!(account_id_from_ecdsa_public(&[0x04; 33]).is_err());
        assert!(account_id_from_ecdsa_public(&[0x04; 65]).is_err());
    }

    #[test]
    fn sr25519_verify_bytes_wrapping() {
        let kp = Keypair::from_uri("//Alice", CRYPTO_SR25519).unwrap();
        let sig = kp.sign(b"<Bytes>hello</Bytes>").unwrap();
        assert!(kp.verify(b"hello", &sig).unwrap());
    }

    #[test]
    fn ed25519_signing_object_has_a_wiping_owner_and_keeps_chain_bytes() {
        // The stored variant must be the wiping owner; this fails to compile
        // if `KeypairInner::Ed25519` reverts to a non-wiping pair type.
        fn stored(inner: &KeypairInner) -> Option<&Zeroizing<SigningKey>> {
            match inner {
                KeypairInner::Ed25519(secret) => Some(secret),
                _ => None,
            }
        }
        let keypair = Keypair::from_uri("//Alice", CRYPTO_ED25519).unwrap();
        assert!(stored(&keypair.inner).is_some());

        let seed = hex::decode("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
            .unwrap();
        let keypair = Keypair::from_seed(&seed, CRYPTO_ED25519).unwrap();
        assert_eq!(
            hex::encode(keypair.public_key_bytes()),
            "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"
        );
        assert_eq!(
            hex::encode(keypair.sign(b"").unwrap()),
            "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
        );
    }

    #[test]
    fn zeroize_clears_every_signing_key_secret() {
        use zeroize::Zeroize;
        let mut key = SigningKey::from([7u8; 32]);
        key.zeroize();
        // Zebra's derived Zeroize clears the seed, expanded scalar and nonce
        // prefix; the seed is the observable remainder.
        assert_eq!(<[u8; 32]>::from(key), [0u8; 32]);
    }

    #[test]
    fn hard_derivation_keeps_substrate_vectors() {
        let alice = Keypair::from_uri("//Alice", CRYPTO_ED25519).unwrap();
        assert_eq!(
            hex::encode(alice.public_key_bytes()),
            "88dc3417d5058ec4b4503e0c12ea1a0a89be200fe98922423d4334014fa6b0ee"
        );
        let bob = Keypair::from_uri("//Bob", CRYPTO_ED25519).unwrap();
        assert_eq!(
            hex::encode(bob.public_key_bytes()),
            "d17c2d7823ebf260fd138f2d7e27d114c0145d968b5ff5006125f2414fadae69"
        );
    }
}