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
use chain_path_derivation::{
    Derivation, DerivationPath, DerivationRange, SoftDerivation, SoftDerivationRange,
};
use ed25519_bip32::{DerivationScheme, Signature, XPrv, XPub};
use std::fmt::{self, Debug, Display};

/// convenient wrapper around the `Key`.
///
pub struct Key<K, P> {
    key: K,
    path: DerivationPath<P>,
    derivation_scheme: DerivationScheme,
}

pub struct KeyRange<'a, K, DR, P, Q> {
    key: &'a Key<K, P>,
    range: DR,
    _marker: std::marker::PhantomData<Q>,
}

impl<'a, K, DR, P, Q> KeyRange<'a, K, DR, P, Q> {
    pub(crate) fn new(key: &'a Key<K, P>, range: DR) -> Self {
        Self {
            key,
            range,
            _marker: std::marker::PhantomData,
        }
    }
}

impl<K, P> Key<K, P> {
    /// create a `Key` with the given component
    ///
    /// does not guarantee that the derivation path is actually the one
    /// that lead to this key derivation.
    #[inline]
    pub fn new_unchecked(
        key: K,
        path: DerivationPath<P>,
        derivation_scheme: DerivationScheme,
    ) -> Self {
        Self {
            key,
            path,
            derivation_scheme,
        }
    }

    /// get the derivation path that lead to this key
    pub fn path(&self) -> &DerivationPath<P> {
        &self.path
    }

    pub fn coerce_unchecked<Q>(self) -> Key<K, Q> {
        Key {
            path: self.path.coerce_unchecked(),
            key: self.key,
            derivation_scheme: self.derivation_scheme,
        }
    }
}

impl<P> Key<XPrv, P> {
    /// retrieve the associated public key of the given private key
    ///
    #[inline]
    pub fn public(&self) -> Key<XPub, P> {
        Key {
            key: self.key.public(),
            path: self.path.clone(),
            derivation_scheme: self.derivation_scheme,
        }
    }

    /// create a signature for the given message and associate the given type `T`
    /// to the signature type.
    ///
    #[inline]
    pub fn sign<T, B>(&self, message: B) -> Signature<T>
    where
        B: AsRef<[u8]>,
    {
        self.key.sign(message.as_ref())
    }

    /// verify the signature with the private key for the given message
    #[inline]
    pub fn verify<T, B>(&self, message: B, signature: &Signature<T>) -> bool
    where
        B: AsRef<[u8]>,
    {
        self.key.verify(message.as_ref(), signature)
    }

    /// get key's chain code
    #[inline]
    pub fn chain_code(&self) -> [u8; 32] {
        *self.key.chain_code()
    }

    /// derive the private key against the given derivation index and scheme
    ///
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub(crate) fn derive_unchecked<Q>(&self, derivation: Derivation) -> Key<XPrv, Q> {
        let derivation_scheme = self.derivation_scheme;
        let key = self.key.derive(derivation_scheme, *derivation);
        let path = self.path.append_unchecked(derivation).coerce_unchecked();
        Key {
            key,
            path,
            derivation_scheme,
        }
    }

    /// derive the private key against the given derivation index and scheme
    ///
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub(crate) fn derive_path_unchecked<'a, Q, I>(&'a self, derivation_path: I) -> Key<XPrv, Q>
    where
        I: IntoIterator<Item = &'a Derivation>,
    {
        let derivation_scheme = self.derivation_scheme;

        let mut key = self.key.clone();
        let mut path = self.path.clone().coerce_unchecked::<Q>();

        for derivation in derivation_path {
            key = key.derive(derivation_scheme, **derivation);
            path = path.append_unchecked(*derivation);
        }

        Key {
            key,
            path,
            derivation_scheme,
        }
    }
}

impl<P> Key<XPub, P> {
    /// verify the signature with the public key for the given message
    #[inline]
    pub fn verify<T, B>(&self, message: B, signature: &Signature<T>) -> bool
    where
        B: AsRef<[u8]>,
    {
        self.key.verify(message.as_ref(), signature)
    }

    /// get the public key content without revealing the chaincode.
    #[inline]
    pub fn public_key_slice(&self) -> &[u8] {
        self.key.public_key_slice()
    }

    pub fn public_key(&self) -> &XPub {
        &self.key
    }

    pub fn pk(&self) -> chain_crypto::PublicKey<chain_crypto::Ed25519> {
        if let Ok(pk) = chain_crypto::PublicKey::from_binary(self.public_key_slice()) {
            pk
        } else {
            unsafe { std::hint::unreachable_unchecked() }
        }
    }

    /// derive the private key against the given derivation index and scheme
    #[must_use = "this returns the result of the operation, without modifying the original"]
    pub(crate) fn derive_unchecked<Q>(&self, derivation: SoftDerivation) -> Key<XPub, Q> {
        let derivation_scheme = self.derivation_scheme;
        let key = if let Ok(key) = self.key.derive(derivation_scheme, *derivation) {
            key
        } else {
            // cannot happen because we already enforced the derivation index
            // to be a soft derivation.
            unsafe { std::hint::unreachable_unchecked() }
        };
        let path = self
            .path
            .append_unchecked(derivation.into())
            .coerce_unchecked();
        Key {
            key,
            path,
            derivation_scheme,
        }
    }
}

impl<P> Key<chain_crypto::SecretKey<chain_crypto::Ed25519Extended>, P> {
    /// create a signature for the given message and associate the given type `T`
    /// to the signature type.
    ///
    #[inline]
    pub fn sign<T, B>(&self, message: B) -> Signature<T>
    where
        B: AsRef<[u8]>,
    {
        Signature::from_slice(self.key.sign(&message.as_ref()).as_ref()).unwrap()
    }

    pub fn pk(&self) -> chain_crypto::PublicKey<chain_crypto::Ed25519> {
        self.key.to_public()
    }
}

impl<'a, P, Q> Iterator for KeyRange<'a, XPub, SoftDerivationRange, P, Q> {
    type Item = Key<XPub, Q>;

    fn next(&mut self) -> Option<Self::Item> {
        self.range
            .next()
            .map(|next| self.key.derive_unchecked(next))
    }
}

impl<'a, P, Q> Iterator for KeyRange<'a, XPrv, DerivationRange, P, Q> {
    type Item = Key<XPrv, Q>;

    fn next(&mut self) -> Option<Self::Item> {
        self.range
            .next()
            .map(|next| self.key.derive_unchecked(next))
    }
}

impl<K, P> AsRef<K> for Key<K, P> {
    fn as_ref(&self) -> &K {
        &self.key
    }
}

impl<K: Clone, P> Clone for Key<K, P> {
    fn clone(&self) -> Self {
        Self {
            key: self.key.clone(),
            path: self.path.clone(),
            derivation_scheme: self.derivation_scheme,
        }
    }
}

impl<K, P> Debug for Key<K, P>
where
    K: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct(&format!(
            "Key<{}, {}>",
            std::any::type_name::<K>(),
            std::any::type_name::<P>()
        ))
        .field("path", &self.path.to_string())
        .field("key", &self.key)
        .field("scheme", &self.derivation_scheme)
        .finish()
    }
}

impl<P> Display for Key<XPrv, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "<private-key> ({path} - {scheme:?})",
            path = self.path,
            scheme = self.derivation_scheme
        ))
    }
}

impl<P> Display for Key<XPub, P> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "{key} ({path} - {scheme:?})",
            key = self.key,
            path = self.path,
            scheme = self.derivation_scheme,
        ))
    }
}