rings-core 0.20.0

Chord DHT implementation with ICE
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
//! ECDSA, EdDSA, and ElGamal
use std::convert::TryFrom;
use std::str::FromStr;

use ethereum_types::H160;
use hex;
use k256::ecdsa::RecoveryId;
use k256::ecdsa::Signature as K256Signature;
use k256::ecdsa::SigningKey as K256SigningKey;
use k256::ecdsa::VerifyingKey as K256VerifyingKey;
use k256::AffinePoint as K256AffinePoint;
use k256::PublicKey as K256PublicKey;
use k256::Scalar as K256Scalar;
use k256::SecretKey as K256SecretKey;
use rand::SeedableRng;
use rand_hc::Hc128Rng;
use serde::Deserialize;
use serde::Serialize;
use sha1::Digest;
use sha1::Sha1;
use subtle::CtOption;

use crate::error::Error;
use crate::error::Result;
pub mod elgamal;
pub mod group;
pub mod keys;
/// Signature schemes used by DID identity and provider login.
pub mod signers;
mod types;
use elliptic_curve::generic_array::typenum::U32;
use elliptic_curve::generic_array::GenericArray;
use elliptic_curve::point::AffineCoordinates;
use elliptic_curve::point::DecompressPoint;
use elliptic_curve::sec1::ToEncodedPoint;
use elliptic_curve::FieldBytes;
use elliptic_curve::PrimeField as _;
pub use group::*;
pub use keys::*;
use p256::NistP256;
use subtle::Choice;
pub use types::PublicKey;

/// ref <https://docs.rs/web3/0.18.0/src/web3/signing.rs.html#69>
///
/// length r: 32, length s: 32, length v(recovery_id): 1
pub type SigBytes = [u8; 65];
/// Alias PublicKey.
pub type CurveEle<const SIZE: usize> = PublicKey<SIZE>;
/// PublicKeyAddress is H160.
pub type PublicKeyAddress = H160;

/// Secp256k1 secret key bytes.
///
/// The bytes are validated at construction time and stay in the canonical
/// external format used by existing configs and DIDs.
#[derive(PartialEq, Eq, Clone, Copy)]
pub struct SecretKey([u8; 32]);

impl std::fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("SecretKey").field(&"<redacted>").finish()
    }
}

/// Wrap String into HashStr.
#[derive(Deserialize, Serialize, Debug, Clone, Eq, PartialEq)]
pub struct HashStr(String);

/// Compute the Keccak-256 hash of input bytes.
pub fn keccak256(bytes: &[u8]) -> [u8; 32] {
    use tiny_keccak::Hasher;
    use tiny_keccak::Keccak;
    let mut output = [0u8; 32];
    let mut hasher = Keccak::v256();
    hasher.update(bytes);
    hasher.finalize(&mut output);
    output
}

impl HashStr {
    /// Create a hash string wrapper from an existing string value.
    pub fn new<T: Into<String>>(s: T) -> Self {
        HashStr(s.into())
    }

    /// Compute the SHA-1 digest of raw bytes and encode it as lowercase hex.
    pub fn from_bytes(bytes: &[u8]) -> Self {
        let mut hasher = Sha1::new();
        hasher.update(bytes);
        HashStr(hex::encode(hasher.finalize()))
    }

    /// Return the wrapped hash string.
    pub fn inner(&self) -> String {
        self.0.clone()
    }
}

impl TryFrom<PublicKey<33>> for K256PublicKey {
    type Error = Error;
    fn try_from(key: PublicKey<33>) -> Result<Self> {
        Self::from_sec1_bytes(&key.0).map_err(|_| Error::ECDSAPublicKeyBadFormat)
    }
}

impl TryFrom<PublicKey<33>> for ed25519_dalek::VerifyingKey {
    type Error = Error;
    fn try_from(key: PublicKey<33>) -> Result<Self> {
        // pubkey[0] == 0
        let [_, bytes @ ..] = key.0;
        Self::from_bytes(&bytes).map_err(|_| Error::EdDSAPublicKeyBadFormat)
    }
}

impl AffineCoordinates for PublicKey<33> {
    type FieldRepr = GenericArray<u8, U32>;

    fn x(&self) -> Self::FieldRepr {
        let [_, x @ ..] = self.0;
        GenericArray::<u8, U32>::from(x)
    }

    fn y_is_odd(&self) -> subtle::Choice {
        let [prefix, ..] = self.0;
        match prefix {
            2u8 => Choice::from(1),
            3u8 => Choice::from(0),
            _ => Choice::from(0),
        }
    }
}

impl PublicKey<33> {
    /// Map a PublicKey into secp256r1 affine point,
    /// This function is an constant-time cryptographic implementations
    pub fn ct_into_secp256r1_affine(self) -> CtOption<primeorder::AffinePoint<NistP256>> {
        primeorder::AffinePoint::<NistP256>::decompress(&self.x(), self.y_is_odd())
    }

    /// Map a PublicKey into secp256r1 public key,
    /// This function is an constant-time cryptographic implementations
    pub fn ct_try_into_secp256r1_pubkey(self) -> CtOption<Result<ecdsa::VerifyingKey<NistP256>>> {
        let opt_affine: CtOption<primeorder::AffinePoint<NistP256>> =
            self.ct_into_secp256r1_affine();
        opt_affine.and_then(|affine| {
            let ret =
                ecdsa::VerifyingKey::<NistP256>::from_affine(affine).map_err(Error::ECDSAError);
            match ret {
                Ok(_r) => CtOption::new(ret, Choice::from(1)),
                Err(_) => CtOption::new(ret, Choice::from(0)),
            }
        })
    }
}

impl From<SecretKey> for FieldBytes<NistP256> {
    fn from(val: SecretKey) -> Self {
        GenericArray::<u8, U32>::from(val.ser())
    }
}

impl From<ed25519_dalek::VerifyingKey> for PublicKey<33> {
    fn from(key: ed25519_dalek::VerifyingKey) -> Self {
        // [u8;32] here
        // ref: https://docs.rs/ed25519-dalek/latest/ed25519_dalek/struct.VerifyingKey.html
        let mut data = [0u8; 33];
        let key_bytes = key.to_bytes();
        if let Some(suffix) = data.get_mut(1..) {
            suffix.copy_from_slice(&key_bytes);
        }
        Self(data)
    }
}

impl TryFrom<PublicKey<33>> for K256AffinePoint {
    type Error = Error;
    fn try_from(key: PublicKey<33>) -> Result<Self> {
        Ok(TryInto::<K256PublicKey>::try_into(key)?
            .to_projective()
            .to_affine())
    }
}

impl TryFrom<K256AffinePoint> for PublicKey<33> {
    type Error = Error;
    fn try_from(a: K256AffinePoint) -> Result<Self> {
        let encoded = a.to_encoded_point(true);
        let data: [u8; 33] = encoded
            .as_bytes()
            .try_into()
            .map_err(|_| Error::InvalidPublicKey)?;
        Ok(Self(data))
    }
}

impl From<K256PublicKey> for PublicKey<33> {
    fn from(key: K256PublicKey) -> Self {
        let encoded = key.to_encoded_point(true);
        let mut data = [0u8; 33];
        if encoded.as_bytes().len() == data.len() {
            data.copy_from_slice(encoded.as_bytes());
        }
        Self(data)
    }
}

impl From<K256VerifyingKey> for PublicKey<33> {
    fn from(key: K256VerifyingKey) -> Self {
        let encoded = key.to_encoded_point(true);
        let mut data = [0u8; 33];
        if encoded.as_bytes().len() == data.len() {
            data.copy_from_slice(encoded.as_bytes());
        }
        Self(data)
    }
}

impl From<SecretKey> for PublicKey<33> {
    fn from(secret_key: SecretKey) -> Self {
        secret_key.pubkey()
    }
}

impl<T> From<T> for HashStr
where T: Into<String>
{
    fn from(s: T) -> Self {
        let inputs = s.into();
        HashStr::from_bytes(inputs.as_bytes())
    }
}

impl TryFrom<&str> for SecretKey {
    type Error = Error;
    fn try_from(s: &str) -> Result<Self> {
        let key = hex::decode(s)?;
        let key_arr: [u8; 32] = key.as_slice().try_into()?;
        Self::from_bytes(key_arr)
    }
}

impl std::str::FromStr for SecretKey {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::try_from(s)
    }
}

#[allow(clippy::to_string_trait_impl)]
impl ToString for SecretKey {
    fn to_string(&self) -> String {
        hex::encode(self.0)
    }
}

struct SecretKeyVisitor;

impl<'de> serde::de::Visitor<'de> for SecretKeyVisitor {
    type Value = SecretKey;

    fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
        formatter.write_str("SecretKey deserializer")
    }
    fn visit_str<E>(self, value: &str) -> std::result::Result<Self::Value, E>
    where E: serde::de::Error {
        SecretKey::from_str(value).map_err(|e| serde::de::Error::custom(e))
    }
}

impl<'de> Deserialize<'de> for SecretKey {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where D: serde::Deserializer<'de> {
        deserializer.deserialize_str(SecretKeyVisitor)
    }
}

impl Serialize for SecretKey {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where S: serde::Serializer {
        serializer.serialize_str(self.to_string().as_str())
    }
}

fn public_key_address(pubkey: &PublicKey<33>) -> PublicKeyAddress {
    let hash = match TryInto::<K256PublicKey>::try_into(*pubkey) {
        // if pubkey is ecdsa key
        Ok(pk) => {
            let data = pk.to_encoded_point(false);
            let data = data.as_bytes();
            debug_assert_eq!(data.first(), Some(&0x04));
            keccak256(data.get(1..).unwrap_or_default())
        }
        // if pubkey is eddsa key
        Err(_) => keccak256(pubkey.0.get(1..).unwrap_or_default()),
    };
    PublicKeyAddress::from_slice(&hash[12..])
}

fn secret_key_address(secret_key: &SecretKey) -> PublicKeyAddress {
    secret_key.pubkey().address()
}

impl SecretKey {
    pub(crate) fn from_bytes(bytes: [u8; 32]) -> Result<Self> {
        K256SecretKey::from_slice(&bytes).map_err(|_| Error::PrivateKeyBadFormat)?;
        Ok(Self(bytes))
    }

    pub(crate) fn secp256k1_scalar(&self) -> K256Scalar {
        Option::<K256Scalar>::from(K256Scalar::from_repr(self.0.into())).unwrap_or(K256Scalar::ONE)
    }

    /// Generate a random secp256k1 secret key.
    pub fn random() -> Self {
        let mut rng = Hc128Rng::from_entropy();
        let bytes = K256SecretKey::random(&mut rng).to_bytes();
        Self(bytes.into())
    }

    /// Derive the Ethereum-style address for this secret key.
    pub fn address(&self) -> PublicKeyAddress {
        secret_key_address(self)
    }

    /// Sign a UTF-8 message after hashing it with Keccak-256.
    pub fn sign(&self, message: &str) -> SigBytes {
        self.sign_raw(message.as_bytes())
    }

    /// Sign raw message bytes after hashing them with Keccak-256.
    pub fn sign_raw(&self, message: &[u8]) -> SigBytes {
        let message_hash = keccak256(message);
        self.sign_hash(&message_hash)
    }

    /// Sign an already computed 32-byte message hash.
    pub fn sign_hash(&self, message_hash: &[u8; 32]) -> SigBytes {
        let signing_key = match K256SigningKey::from_slice(&self.0) {
            Ok(signing_key) => signing_key,
            Err(_) => return [0u8; 65],
        };
        let (signature, recover_id) = match signing_key.sign_prehash_recoverable(message_hash) {
            Ok(signature) => signature,
            Err(_) => return [0u8; 65],
        };
        let mut sig_bytes: SigBytes = [0u8; 65];
        sig_bytes[0..64].copy_from_slice(signature.to_bytes().as_slice());
        sig_bytes[64] = recover_id.to_byte();
        sig_bytes
    }

    /// Derive the compressed public key for this secret key.
    pub fn pubkey(&self) -> PublicKey<33> {
        match K256SecretKey::from_slice(&self.0) {
            Ok(secret_key) => secret_key.public_key().into(),
            Err(_) => PublicKey([0u8; 33]),
        }
    }

    /// Serialize this secret key into its 32-byte representation.
    pub fn ser(&self) -> [u8; 32] {
        self.0
    }
}

impl PublicKey<33> {
    /// Derive the Ethereum-style address for this public key.
    pub fn address(&self) -> PublicKeyAddress {
        public_key_address(self)
    }
}

/// Recover PublicKey from RawMessage using signature.
pub fn recover<S>(message: &[u8], signature: S) -> Result<PublicKey<33>>
where S: AsRef<[u8]> {
    let sig_bytes: SigBytes = signature.as_ref().try_into()?;
    let message_hash: [u8; 32] = keccak256(message);
    recover_hash(&message_hash, &sig_bytes)
}

/// Recover PublicKey from HashMessage using signature.
pub fn recover_hash(message_hash: &[u8; 32], sig: &[u8; 65]) -> Result<PublicKey<33>> {
    let r_s_signature: [u8; 64] = sig[..64].try_into()?;
    let recovery_id: u8 = sig[64];
    let signature = K256Signature::try_from(r_s_signature.as_slice()).map_err(Error::ECDSAError)?;
    let recovery_id =
        RecoveryId::from_byte(recovery_id).ok_or(Error::InvalidRecoverId(recovery_id))?;
    Ok(
        K256VerifyingKey::recover_from_prehash(message_hash, &signature, recovery_id)
            .map_err(Error::ECDSAError)?
            .into(),
    )
}

#[cfg(test)]
pub(crate) mod tests {
    use hex::FromHex;

    use super::*;

    #[test]
    fn test_parse_to_string_with_sha10x00() {
        let s = "65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0";
        let t: HashStr = s.into();
        assert_eq!(t.0.len(), 40);
    }

    #[test]
    fn test_parse_to_string_with_sha10x01() {
        let s = "hello";
        let t: HashStr = s.into();
        assert_eq!(t.0.len(), 40);
    }

    #[test]
    fn test_metamask_sign_for_debug() {
        let key = &SecretKey::try_from(
            "65860affb4b570dba06db294aa7c676f68e04a5bf2721243ad3cbc05a79c68c0",
        )
        .unwrap();
        let sig_hash =
            Vec::from_hex("4a5c5d454721bbbb25540c3317521e71c373ae36458f960d2ad46ef088110e95")
                .unwrap();
        let msg = "test";
        // https://docs.rs/web3/latest/src/web3/signing.rs.html#221
        let prefix_msg_ret = "\x19Ethereum Signed Message:\n4test"
            .to_string()
            .into_bytes();
        let mut prefix_msg = format!("\x19Ethereum Signed Message:\n{}", msg.len()).into_bytes();
        prefix_msg.extend_from_slice(msg.as_bytes());
        assert_eq!(
            prefix_msg,
            prefix_msg_ret,
            "{}",
            String::from_utf8(prefix_msg.clone()).unwrap()
        );
        //        let hash = hash_message(msg.as_bytes()).0;
        assert_eq!(keccak256(prefix_msg_ret.as_slice()), sig_hash.as_slice());
        // window.ethereum.request({method: "personal_sign", params: ["test", "0x11E807fcc88dD319270493fB2e822e388Fe36ab0"]})
        let metamask_sig = Vec::from_hex("724fc31d9272b34d8406e2e3a12a182e72510b008de6cc44684577e31e20d9626fb760d6a0badd79a6cf4cd56b2fc0fbd60c438b809aa7d29bfb598c13e7b50e1b").unwrap();
        assert_eq!(metamask_sig.len(), 65);
        let h: [u8; 32] = sig_hash.as_slice().try_into().unwrap();
        let recover_id = key.sign_hash(&h)[64];
        assert_eq!(recover_id, 0);
        let mut sig = key.sign_raw(&prefix_msg);
        sig[64] = 27;
        assert_eq!(sig, metamask_sig.as_slice());
    }

    #[test]
    fn test_recover() {
        let key = SecretKey::random();
        let pubkey1 = key.pubkey();
        let pubkey2 = recover("hello".as_bytes(), key.sign("hello")).unwrap();
        assert_eq!(pubkey1, pubkey2);
    }

    pub(crate) fn gen_ordered_keys(n: usize) -> Vec<SecretKey> {
        let mut keys = Vec::from_iter(std::iter::repeat_with(SecretKey::random).take(n));
        keys.sort_by(|a, b| {
            if a.address() < b.address() {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Greater
            }
        });
        keys
    }
}