cardano_serialization_lib/chain_crypto/algorithms/
legacy_daedalus.rs

1use crate::chain_crypto::key::{
2    AsymmetricKey, AsymmetricPublicKey, PublicKeyError, SecretKeyError, SecretKeySizeStatic,
3};
4use crate::chain_crypto::sign::{
5    SignatureError, SigningAlgorithm, Verification, VerificationAlgorithm,
6};
7
8use cryptoxide::digest::Digest;
9use cryptoxide::hmac::Hmac;
10use cryptoxide::mac::Mac;
11use cryptoxide::sha2::Sha512;
12
13use super::ed25519 as ei;
14use cryptoxide::ed25519;
15use ed25519_bip32::{XPrv, XPub, XPRV_SIZE, XPUB_SIZE};
16use rand_os::rand_core::{CryptoRng, RngCore};
17
18const CHAIN_CODE_SIZE: usize = 32;
19const SEED_SIZE: usize = 64;
20
21/// Legacy Daedalus algorithm
22pub struct LegacyDaedalus;
23
24#[derive(Clone)]
25pub struct LegacyPriv([u8; XPRV_SIZE]);
26
27impl AsRef<[u8]> for LegacyPriv {
28    fn as_ref(&self) -> &[u8] {
29        &self.0[..]
30    }
31}
32
33impl LegacyPriv {
34    pub fn from_xprv(xprv: &XPrv) -> Self {
35        let mut buf = [0; XPRV_SIZE];
36        buf[0..XPRV_SIZE].clone_from_slice(xprv.as_ref());
37        LegacyPriv(buf)
38    }
39
40    pub fn inner_key(&self) -> [u8; ed25519::EXTENDED_KEY_LENGTH] {
41        let mut buf = [0; ed25519::EXTENDED_KEY_LENGTH];
42        buf.clone_from_slice(&self.0.as_ref()[0..ed25519::EXTENDED_KEY_LENGTH]);
43        buf
44    }
45
46    pub fn chaincode(&self) -> [u8; CHAIN_CODE_SIZE] {
47        let mut buf = [0; CHAIN_CODE_SIZE];
48        buf.clone_from_slice(&self.0.as_ref()[ed25519::EXTENDED_KEY_LENGTH..XPRV_SIZE]);
49        buf
50    }
51}
52
53impl AsymmetricPublicKey for LegacyDaedalus {
54    type Public = XPub;
55    const PUBLIC_BECH32_HRP: &'static str = "legacy_xpub";
56    const PUBLIC_KEY_SIZE: usize = XPUB_SIZE;
57    fn public_from_binary(data: &[u8]) -> Result<Self::Public, PublicKeyError> {
58        let xpub = XPub::from_slice(data)?;
59        Ok(xpub)
60    }
61}
62
63impl AsymmetricKey for LegacyDaedalus {
64    type Secret = LegacyPriv;
65    type PubAlg = LegacyDaedalus;
66
67    const SECRET_BECH32_HRP: &'static str = "legacy_xprv";
68
69    fn generate<T: RngCore + CryptoRng>(mut rng: T) -> Self::Secret {
70        let mut seed = [0u8; SEED_SIZE];
71        rng.fill_bytes(&mut seed);
72        let mut mac = Hmac::new(Sha512::new(), &seed);
73
74        let mut iter = 1;
75        let mut out = [0u8; XPRV_SIZE];
76
77        loop {
78            let s = format!("Root Seed Chain {}", iter);
79            mac.reset();
80            mac.input(s.as_bytes());
81            let mut block = [0u8; 64];
82            mac.raw_result(&mut block);
83            mk_ed25519_extended(&mut out[0..64], &block[0..32]);
84
85            if (out[31] & 0x20) == 0 {
86                out[64..96].clone_from_slice(&block[32..64]);
87                break;
88            }
89            iter = iter + 1;
90        }
91
92        LegacyPriv(out)
93    }
94
95    fn compute_public(key: &Self::Secret) -> <Self as AsymmetricPublicKey>::Public {
96        let ed25519e = key.inner_key();
97        let pubkey = ed25519::extended_to_public(&ed25519e);
98        let chaincode = key.chaincode();
99
100        let mut buf = [0; XPUB_SIZE];
101        buf[0..ed25519::PUBLIC_KEY_LENGTH].clone_from_slice(&pubkey);
102        buf[ed25519::PUBLIC_KEY_LENGTH..XPUB_SIZE].clone_from_slice(&chaincode);
103
104        XPub::from_bytes(buf)
105    }
106
107    fn secret_from_binary(data: &[u8]) -> Result<Self::Secret, SecretKeyError> {
108        // Note: we do NOT verify that the bytes match proper bip32 format
109        // this is because legacy Daedalus wallets do not match the format
110        if data.len() != XPRV_SIZE {
111            return Err(SecretKeyError::SizeInvalid);
112        }
113        let mut buf = [0; XPRV_SIZE];
114        buf[0..XPRV_SIZE].clone_from_slice(data);
115        Ok(LegacyPriv(buf))
116    }
117}
118
119impl SecretKeySizeStatic for LegacyDaedalus {
120    const SECRET_KEY_SIZE: usize = XPRV_SIZE;
121}
122
123type XSig = ed25519_bip32::Signature<u8>;
124
125impl VerificationAlgorithm for LegacyDaedalus {
126    type Signature = XSig;
127
128    const SIGNATURE_SIZE: usize = ed25519_bip32::SIGNATURE_SIZE;
129    const SIGNATURE_BECH32_HRP: &'static str = "legacy_xsig";
130
131    fn signature_from_bytes(data: &[u8]) -> Result<Self::Signature, SignatureError> {
132        let xsig = XSig::from_slice(data)?;
133        Ok(xsig)
134    }
135
136    fn verify_bytes(
137        pubkey: &Self::Public,
138        signature: &Self::Signature,
139        msg: &[u8],
140    ) -> Verification {
141        pubkey.verify(msg, signature).into()
142    }
143}
144
145impl SigningAlgorithm for LegacyDaedalus {
146    fn sign(key: &Self::Secret, msg: &[u8]) -> XSig {
147        let buf = key.inner_key();
148        let sig = ei::Sig(ed25519::signature_extended(msg, &buf));
149        ed25519_bip32::Signature::from_bytes(sig.0)
150    }
151}
152
153fn mk_ed25519_extended(extended_out: &mut [u8], secret: &[u8]) {
154    assert!(extended_out.len() == 64);
155    assert!(secret.len() == 32);
156    let mut hasher = Sha512::new();
157    hasher.input(secret);
158    hasher.result(extended_out);
159    extended_out[0] &= 248;
160    extended_out[31] &= 63;
161    extended_out[31] |= 64;
162}
163
164#[cfg(test)]
165mod test {
166    use super::*;
167
168    use crate::chain_crypto::key::KeyPair;
169    use crate::chain_crypto::sign::test::{keypair_signing_ko, keypair_signing_ok};
170
171    #[quickcheck]
172    fn sign_ok(input: (KeyPair<LegacyDaedalus>, Vec<u8>)) -> bool {
173        keypair_signing_ok(input)
174    }
175    #[quickcheck]
176    fn sign_ko(input: (KeyPair<LegacyDaedalus>, KeyPair<LegacyDaedalus>, Vec<u8>)) -> bool {
177        keypair_signing_ko(input)
178    }
179}