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
// © 2024 Max Karou. All Rights Reserved.
// Licensed under Apache Version 2.0, or MIT License, at your discretion.
//
// Apache License: http://www.apache.org/licenses/LICENSE-2.0
// MIT License: http://opensource.org/licenses/MIT
//
// Usage of this file is permitted solely under a sanctioned license.

use ring::digest::Context;
use ring::digest::SHA256 as HashSha256;
use ring::digest::SHA512_256 as HashSha512_256;
use ripemd::Digest;
use ripemd::Ripemd160;
use secp256k1::ecdsa::RecoverableSignature;
use secp256k1::ecdsa::RecoveryId;
use secp256k1::Message;
use secp256k1::PublicKey;
use secp256k1::Secp256k1;
use secp256k1::SecretKey;

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Error {
    #[error("Invalid message signature length, expected 65 bytes - got: {0}")]
    InvalidMessageSigLength(usize),
    /// `secp256k1` crate errors.
    #[error(transparent)]
    Secp256k1(#[from] secp256k1::Error),
    /// Conversion from a integer failed.
    #[error(transparent)]
    TryFromInt(#[from] std::num::TryFromIntError),
}

macro_rules! impl_hash_byte_array {
    ($name:ident, $ty:ty, $len:expr) => {
        #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
        pub struct $name(pub [$ty; $len]);
        impl $name {
            pub fn as_bytes(&self) -> &[$ty; $len] {
                &self.0
            }

            pub fn into_bytes(self) -> [$ty; $len] {
                self.0
            }

            pub fn hex(&self) -> String {
                $crate::crypto::bytes_to_hex(&self.0)
            }
        }
        impl ::std::fmt::Debug for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
                let &$name(data) = self;
                for i in data.iter() {
                    write!(f, "{:02x}", i)?;
                }
                Ok(())
            }
        }
        impl ::std::default::Default for $name {
            fn default() -> Self {
                $name([0; $len])
            }
        }
        impl ::std::convert::From<[$ty; $len]> for $name {
            fn from(bytes: [$ty; $len]) -> Self {
                $name(bytes)
            }
        }
        impl ::std::convert::AsRef<[$ty; $len]> for $name {
            fn as_ref(&self) -> &[$ty; $len] {
                &self.0
            }
        }
        impl ::std::convert::AsMut<[$ty; $len]> for $name {
            fn as_mut(&mut self) -> &mut [$ty; $len] {
                &mut self.0
            }
        }
        impl ::std::convert::AsRef<[$ty]> for $name {
            fn as_ref(&self) -> &[$ty] {
                &self.0
            }
        }
        impl ::std::convert::AsMut<[$ty]> for $name {
            fn as_mut(&mut self) -> &mut [$ty] {
                &mut self.0
            }
        }
        impl ::std::convert::From<$name> for Vec<$ty> {
            fn from(hash: $name) -> Vec<$ty> {
                hash.0.to_vec()
            }
        }
    };
}

/// The encoded size of a SHA256 hash.
pub const SHA256_ENCODED_SIZE: usize = 32;
/// The encoded size of a HASH160 hash.
pub const HASH160_ENCODED_SIZE: usize = 20;
/// The encoded size of a message signature.
pub const MESSAGE_ENCODED_SIZE: usize = 65;

impl_hash_byte_array!(Sha256Hash, u8, SHA256_ENCODED_SIZE);
impl Sha256Hash {
    /// Create a new `Sha256Hash` from a slice.
    pub fn from_slice<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let mut buff = [0u8; SHA256_ENCODED_SIZE];
        let mut ctx = Context::new(&HashSha256);
        ctx.update(bytes.as_ref());
        let digest = ctx.finish();
        buff.copy_from_slice(digest.as_ref());
        Self(buff)
    }

    /// Returns the checksum of the hash.
    pub fn checksum(&self) -> [u8; 4] {
        let bytes = self.as_bytes();
        let mut buff = [0u8; 4];
        buff.copy_from_slice(&bytes[0..4]);
        buff
    }
}

impl_hash_byte_array!(DSha256Hash, u8, SHA256_ENCODED_SIZE);
impl DSha256Hash {
    /// Create a new `DSha256Hash` from a slice.
    pub fn from_slice<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let mut buff = [0u8; SHA256_ENCODED_SIZE];
        let sha = Sha256Hash::from_slice(bytes.as_ref());
        let bytes = sha.as_bytes();
        let sha2 = Sha256Hash::from_slice(bytes);
        let bytes2 = sha2.as_bytes();
        buff.copy_from_slice(bytes2);
        Self(buff)
    }

    /// Returns the checksum of the hash.
    pub fn checksum(&self) -> [u8; 4] {
        let bytes = self.as_bytes();
        let mut buff = [0u8; 4];
        buff.copy_from_slice(&bytes[0..4]);
        buff
    }
}

impl_hash_byte_array!(Sha512_256Hash, u8, SHA256_ENCODED_SIZE);
impl Sha512_256Hash {
    /// Create a new `Sha512_256Hash` from a slice.
    pub fn from_slice<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let mut buff = [0u8; SHA256_ENCODED_SIZE];
        let mut ctx = Context::new(&HashSha512_256);
        ctx.update(bytes.as_ref());
        let digest = ctx.finish();
        buff.copy_from_slice(digest.as_ref());
        Self(buff)
    }

    /// Returns the checksum of the hash.
    pub fn checksum(&self) -> [u8; 4] {
        let bytes = self.as_bytes();
        let mut buff = [0u8; 4];
        buff.copy_from_slice(&bytes[0..4]);
        buff
    }
}

impl_hash_byte_array!(Hash160, u8, HASH160_ENCODED_SIZE);
impl Hash160 {
    /// Create a new `Hash160` from a slice.
    pub fn from_slice<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let mut buff = [0u8; HASH160_ENCODED_SIZE];
        let sha = Sha256Hash::from_slice(bytes.as_ref());
        let bytes = sha.as_bytes();
        let ripemd = Ripemd160::digest(bytes);
        buff.copy_from_slice(ripemd.as_slice());
        Self(buff)
    }

    /// Returns the checksum of the hash.
    pub fn checksum(&self) -> [u8; 4] {
        let bytes = self.as_bytes();
        let mut buff = [0u8; 4];
        buff.copy_from_slice(&bytes[0..4]);
        buff
    }
}

impl_hash_byte_array!(MessageSignature, u8, MESSAGE_ENCODED_SIZE);
impl MessageSignature {
    /// Creates a new `MessageSignature`.
    pub fn new<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let mut buff = [0u8; 65];
        buff.copy_from_slice(bytes.as_ref());
        Self(buff)
    }

    /// Creates a new `MessageSignature` from a slice.
    pub fn from_slice<T>(bytes: T) -> Result<Self, Error>
    where
        T: AsRef<[u8]>,
    {
        let len = bytes.as_ref().len();

        if len != 65 {
            return Err(Error::InvalidMessageSigLength(len));
        }

        let mut buff = [0u8; 65];
        buff.copy_from_slice(bytes.as_ref());

        Ok(Self(buff))
    }

    /// Creates a new `MessageSignature` from a recoverable signature.
    pub fn from_recov<T>(recov: T) -> Result<Self, Error>
    where
        T: Into<RecoverableSignature>,
    {
        let (id, bytes) = recov.into().serialize_compact();
        let mut buff = vec![u8::try_from(id.to_i32())?];
        buff.extend_from_slice(&bytes);
        Self::from_slice(&buff)
    }

    /// Converts the `MessageSignature` into a recoverable signature.
    pub fn into_recov(self) -> Result<RecoverableSignature, Error> {
        let bytes = self.as_bytes();
        let id = RecoveryId::from_i32(i32::from(bytes[0]))?;
        Ok(RecoverableSignature::from_compact(&bytes[1..], id)?)
    }
}

impl_hash_byte_array!(SignatureHash, u8, SHA256_ENCODED_SIZE);
impl SignatureHash {
    /// Create a new `SignatureHash` from a slice.
    pub fn from_slice<T>(bytes: T) -> Self
    where
        T: AsRef<[u8]>,
    {
        let hasher = Sha512_256Hash::from_slice(bytes.as_ref());
        Self(hasher.into_bytes())
    }

    pub fn next_signature<T>(
        hash: Self,
        typ: u8,
        fee: u64,
        nonce: u64,
        pk: T,
    ) -> Result<(MessageSignature, Self), Error>
    where
        T: Into<SecretKey>,
    {
        let secp = Secp256k1::new();
        let pre_sign = Self::make_presign_hash(hash, typ, fee, nonce);

        let msg = Message::from_digest_slice(pre_sign.as_bytes())?;
        let recoverable = secp.sign_ecdsa_recoverable(&msg, &pk.into());

        let signature = MessageSignature::from_recov(recoverable)?;
        let hash = Self::make_postsign_hash(pre_sign, signature);

        Ok((signature, hash))
    }

    pub fn next_verify<T>(
        hash: Self,
        typ: u8,
        fee: u64,
        nonce: u64,
        signature: T,
    ) -> Result<(PublicKey, Self), Error>
    where
        T: Into<MessageSignature>,
    {
        let signature = signature.into();
        let secp = secp256k1::Secp256k1::new();
        let pre_sign = Self::make_presign_hash(hash, typ, fee, nonce);

        let recoverable = signature.into_recov()?;
        let msg = secp256k1::Message::from_digest_slice(pre_sign.as_bytes())?;
        let pubk = secp.recover_ecdsa(&msg, &recoverable)?;

        let next = Self::make_postsign_hash(pre_sign, signature);

        Ok((pubk, next))
    }

    pub fn make_presign_hash(hash: Self, typ: u8, fee: u64, nonce: u64) -> Self {
        let mut buff = vec![];

        buff.extend_from_slice(hash.as_bytes());
        buff.push(typ);
        buff.extend_from_slice(&fee.to_be_bytes());
        buff.extend_from_slice(&nonce.to_be_bytes());

        Self::from_slice(&buff)
    }

    pub fn make_postsign_hash<T>(hash: Self, sig: T) -> Self
    where
        T: Into<MessageSignature>,
    {
        let mut buff = vec![];

        buff.extend_from_slice(hash.as_bytes());
        buff.push(0x00);
        buff.extend_from_slice(sig.into().as_bytes());

        Self::from_slice(&buff)
    }
}