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
use crate::{Error, Result};
use parity_scale_codec::Encode;
use serde::{Deserialize, Serialize};
use sp_core::{
    crypto::{Derive, DeriveJunction as SrDeriveJunction},
    sr25519::{Pair, Public, Signature as SrSignature},
    Pair as _,
};

extern crate alloc;
use alloc::vec::Vec;

pub const PUBLIC_KEY_LENGTH: usize = 32;
pub const SIGNATURE_LENGTH: usize = 64;

/// An Schnorrkel/Ristretto x25519 (“sr25519”) key pair.
pub struct KeyPair(Pair);

/// An Schnorrkel/Ristretto x25519 (“sr25519”) signature.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Signature(SrSignature);

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

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

#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct PublicKey(Public);

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

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

impl Signature {
    /// A new instance from the given slice that should be 64 bytes long.
    ///
    /// NOTE: No checking goes on to ensure this is a real signature.
    /// Only use it if you are certain that the array actually is a signature.

    pub fn from_slice(data: &[u8]) -> Result<Self> {
        Ok(Self(SrSignature::from_slice(data).ok_or(
            Error::InvalidArgumentError {
                alg: "bytes",
                expected: "a valid secret key byte array",
            },
        )?))
    }

    /// A new instance from the given 64-byte data.
    ///
    /// NOTE: No checking goes on to ensure this is a real signature.
    /// Only use it if you are certain that the array actually is a signature, or if you immediately verify the
    /// signature. All functions that verify signatures will fail if the Signature is not actually a valid
    /// signature.
    pub fn from_raw(data: [u8; SIGNATURE_LENGTH]) -> Self {
        Self(SrSignature::from_raw(data))
    }

    /// Gets the wrapped sp_core's [`SrSignature`] reference.
    pub fn inner(&self) -> &SrSignature {
        &self.0
    }
}

/// A since derivation junction description.
/// It is the single parameter used when creating a new secret key from an existing secret key.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub enum DeriveJunction {
    /// Soft (vanilla) derivation. Public keys have a correspondent derivation.
    Soft([u8; 32]),
    /// Hard (“hardened”) derivation. Public keys do not have a correspondent derivation.
    Hard([u8; 32]),
}

impl From<DeriveJunction> for SrDeriveJunction {
    fn from(j: DeriveJunction) -> SrDeriveJunction {
        match j {
            DeriveJunction::Soft(p) => SrDeriveJunction::Soft(p),
            DeriveJunction::Hard(p) => SrDeriveJunction::Hard(p),
        }
    }
}

impl From<SrDeriveJunction> for DeriveJunction {
    fn from(j: SrDeriveJunction) -> DeriveJunction {
        match j {
            SrDeriveJunction::Soft(p) => DeriveJunction::Soft(p),
            SrDeriveJunction::Hard(p) => DeriveJunction::Hard(p),
        }
    }
}

impl DeriveJunction {
    /// Create a new soft (vanilla) DeriveJunction from a given, encodable, value.
    ///
    /// If you need a hard junction, use `hard()`.
    pub fn soft<T: Encode>(index: T) -> Self {
        SrDeriveJunction::soft(index).into()
    }

    pub fn hard<T: Encode>(index: T) -> Self {
        SrDeriveJunction::hard(index).into()
    }
}

impl PublicKey {
    /// A new instance from the given 64-byte data.
    ///
    /// NOTE: No checking goes on to ensure this is a real public key.
    /// Only use it if you are certain that the array actually is a pubkey.
    pub fn from_raw(data: [u8; PUBLIC_KEY_LENGTH]) -> Self {
        Self(Public::from_raw(data))
    }

    /// Derive a child key from a series of given junctions.
    ///
    /// None if there are any hard junctions in there.
    pub fn derive<I: Iterator<Item = DeriveJunction>>(&self, path: I) -> Option<Self> {
        self.0.derive(path.map(Into::into)).map(Self)
    }

    /// Verify a signature on a message. Returns true if the signature is good.
    pub fn verify<M: AsRef<[u8]>>(&self, sig: &Signature, message: M) -> bool {
        Pair::verify(&sig.0, message, &self.0)
    }

    /// Gets the wrapped sp_core's [`Public`] reference.
    pub fn inner(&self) -> &Public {
        &self.0
    }
}

impl KeyPair {
    #[cfg(feature = "random")]
    #[cfg_attr(docsrs, doc(cfg(feature = "random")))]
    pub fn generate() -> crate::Result<Self> {
        let mut bs = [0u8; 32];
        crate::utils::rand::fill(&mut bs)?;
        Ok(Self::from_seed(&bs))
    }

    #[cfg(feature = "rand")]
    pub fn generate_with<R: rand::CryptoRng + rand::RngCore>(rng: &mut R) -> Self {
        let mut bs = [0_u8; 32];
        rng.fill_bytes(&mut bs);
        Self::from_seed(&bs)
    }

    /// Returns the KeyPair from the English BIP39 mnemonic or seed, or an error if it’s invalid.
    pub fn from_string(s: &str, password: Option<&str>) -> Result<Self> {
        let pair = Pair::from_string(s, password).map_err(|_| Error::InvalidArgumentError {
            alg: "KeyPair#from_string",
            expected: "a valid seed or english BIP39 mnemonic",
        })?;
        Ok(Self(pair))
    }

    /// Get the public key.
    pub fn public_key(&self) -> PublicKey {
        PublicKey(self.0.public())
    }

    /// Signs a message.
    pub fn sign(&self, message: &[u8]) -> Signature {
        Signature(self.0.sign(message))
    }

    /// Derive a child key from a series of given junctions.
    pub fn derive<I: Iterator<Item = DeriveJunction>>(&self, path: I, seed: Option<[u8; 32]>) -> Result<Self> {
        let (pair, _) = self.0.derive(path.map(Into::into), seed).unwrap();
        Ok(Self(pair))
    }

    /// Gets the seed as raw vec.
    pub fn seed(&self) -> Vec<u8> {
        self.0.to_raw_vec()
    }

    pub fn from_seed(seed: &[u8]) -> Self {
        Self(Pair::from_seed_slice(seed).expect("invalid seed length"))
    }
}

impl From<PublicKey> for [u8; 32] {
    fn from(x: PublicKey) -> [u8; 32] {
        <[u8; 32]>::from(x.0)
    }
}