linera_base/crypto/
mod.rs

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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
// Copyright (c) Facebook, Inc. and its affiliates.
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Define the cryptographic primitives used by the Linera protocol.

mod ed25519;
mod hash;
#[allow(dead_code)]
mod secp256k1;
use std::{fmt::Display, io, num::ParseIntError, str::FromStr};

use alloy_primitives::FixedBytes;
use custom_debug_derive::Debug;
pub use ed25519::{Ed25519PublicKey, Ed25519SecretKey, Ed25519Signature};
pub use hash::*;
use linera_witty::{WitLoad, WitStore, WitType};
pub use secp256k1::{
    evm::{EvmPublicKey, EvmSecretKey, EvmSignature},
    Secp256k1PublicKey, Secp256k1SecretKey, Secp256k1Signature,
};
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// The public key of a validator.
pub type ValidatorPublicKey = secp256k1::Secp256k1PublicKey;
/// The private key of a validator.
pub type ValidatorSecretKey = secp256k1::Secp256k1SecretKey;
/// The signature of a validator.
pub type ValidatorSignature = secp256k1::Secp256k1Signature;
/// The key pair of a validator.
pub type ValidatorKeypair = secp256k1::Secp256k1KeyPair;

/// Signature scheme used for the public key.
#[derive(Serialize, Deserialize, Debug, Copy, Clone, Eq, PartialEq)]
pub enum SignatureScheme {
    /// Ed25519
    Ed25519,
    /// secp256k1
    Secp256k1,
    /// EVM secp256k1
    EvmSecp256k1,
}

/// The public key of a chain owner.
/// The corresponding private key is allowed to propose blocks
/// on the chain and transfer account's tokens.
#[derive(
    Serialize,
    Deserialize,
    Debug,
    Eq,
    PartialEq,
    Ord,
    PartialOrd,
    Copy,
    Clone,
    Hash,
    WitType,
    WitLoad,
    WitStore,
)]
pub enum AccountPublicKey {
    /// Ed25519 public key.
    Ed25519(ed25519::Ed25519PublicKey),
    /// secp256k1 public key.
    Secp256k1(secp256k1::Secp256k1PublicKey),
    /// EVM secp256k1 public key.
    EvmSecp256k1(secp256k1::evm::EvmPublicKey),
}

/// The private key of a chain owner.
#[derive(Serialize, Deserialize)]
pub enum AccountSecretKey {
    /// Ed25519 secret key.
    Ed25519(ed25519::Ed25519SecretKey),
    /// secp256k1 secret key.
    Secp256k1(secp256k1::Secp256k1SecretKey),
    /// EVM secp256k1 secret key.
    EvmSecp256k1(secp256k1::evm::EvmSecretKey),
}

/// The signature of a chain owner.
#[derive(Eq, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
pub enum AccountSignature {
    /// Ed25519 signature.
    Ed25519(ed25519::Ed25519Signature),
    /// secp256k1 signature.
    Secp256k1(secp256k1::Secp256k1Signature),
    /// EVM secp256k1 signature.
    EvmSecp256k1(secp256k1::evm::EvmSignature),
}

impl AccountSecretKey {
    /// Returns the public key corresponding to this secret key.
    pub fn public(&self) -> AccountPublicKey {
        match self {
            AccountSecretKey::Ed25519(secret) => AccountPublicKey::Ed25519(secret.public()),
            AccountSecretKey::Secp256k1(secret) => AccountPublicKey::Secp256k1(secret.public()),
            AccountSecretKey::EvmSecp256k1(secret) => {
                AccountPublicKey::EvmSecp256k1(secret.public())
            }
        }
    }

    /// Copies the secret key.
    pub fn copy(&self) -> Self {
        match self {
            AccountSecretKey::Ed25519(secret) => AccountSecretKey::Ed25519(secret.copy()),
            AccountSecretKey::Secp256k1(secret) => AccountSecretKey::Secp256k1(secret.copy()),
            AccountSecretKey::EvmSecp256k1(secret) => AccountSecretKey::EvmSecp256k1(secret.copy()),
        }
    }

    /// Creates a signature for the `value` using provided `secret`.
    pub fn sign<'de, T>(&self, value: &T) -> AccountSignature
    where
        T: BcsSignable<'de>,
    {
        match self {
            AccountSecretKey::Ed25519(secret) => {
                let signature = Ed25519Signature::new(value, secret);
                AccountSignature::Ed25519(signature)
            }
            AccountSecretKey::Secp256k1(secret) => {
                let signature = secp256k1::Secp256k1Signature::new(value, secret);
                AccountSignature::Secp256k1(signature)
            }
            AccountSecretKey::EvmSecp256k1(secret) => {
                let signature = secp256k1::evm::EvmSignature::new(value, secret);
                AccountSignature::EvmSecp256k1(signature)
            }
        }
    }

    #[cfg(all(with_testing, with_getrandom))]
    /// Generates a new key pair using the operating system's RNG.
    pub fn generate() -> Self {
        AccountSecretKey::Ed25519(Ed25519SecretKey::generate())
    }
}

impl AccountPublicKey {
    /// Returns the signature scheme of the public key.
    pub fn scheme(&self) -> SignatureScheme {
        match self {
            AccountPublicKey::Ed25519(_) => SignatureScheme::Ed25519,
            AccountPublicKey::Secp256k1(_) => SignatureScheme::Secp256k1,
            AccountPublicKey::EvmSecp256k1(_) => SignatureScheme::EvmSecp256k1,
        }
    }

    /// Returns the byte representation of the public key.
    pub fn as_bytes(&self) -> Vec<u8> {
        bcs::to_bytes(&self).expect("serialization to bytes should not fail")
    }

    /// Parses the byte representation of the public key.
    ///
    /// Returns error if the byte slice has incorrect length or the flag is not recognized.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, CryptoError> {
        bcs::from_bytes(bytes).map_err(CryptoError::PublicKeyParseError)
    }

    /// A fake public key used for testing.
    #[cfg(with_testing)]
    pub fn test_key(name: u8) -> Self {
        AccountPublicKey::Ed25519(Ed25519PublicKey::test_key(name))
    }
}

impl AccountSignature {
    /// Verifies the signature for the `value` using the provided `public_key`.
    pub fn verify<'de, T>(&self, value: &T, author: AccountPublicKey) -> Result<(), CryptoError>
    where
        T: BcsSignable<'de> + std::fmt::Debug,
    {
        match (self, author) {
            (AccountSignature::Ed25519(signature), AccountPublicKey::Ed25519(public_key)) => {
                signature.check(value, public_key)
            }
            (AccountSignature::Secp256k1(signature), AccountPublicKey::Secp256k1(public_key)) => {
                signature.check(value, &public_key)
            }
            (
                AccountSignature::EvmSecp256k1(signature),
                AccountPublicKey::EvmSecp256k1(public_key),
            ) => signature.check(value, &public_key),
            (AccountSignature::Ed25519(_), _) => {
                let type_name = std::any::type_name::<T>();
                Err(CryptoError::InvalidSignature {
                    error: "invalid signature scheme. Expected Ed25519 signature.".to_string(),
                    type_name: type_name.to_string(),
                })
            }
            (AccountSignature::Secp256k1(_), _) => {
                let type_name = std::any::type_name::<T>();
                Err(CryptoError::InvalidSignature {
                    error: "invalid signature scheme. Expected secp256k1 signature.".to_string(),
                    type_name: type_name.to_string(),
                })
            }
            (AccountSignature::EvmSecp256k1(_), _) => {
                let type_name = std::any::type_name::<T>();
                Err(CryptoError::InvalidSignature {
                    error: "invalid signature scheme. Expected EvmSecp256k1 signature.".to_string(),
                    type_name: type_name.to_string(),
                })
            }
        }
    }

    /// Returns byte representation of the signatures.
    pub fn to_bytes(&self) -> Vec<u8> {
        bcs::to_bytes(&self).expect("serialization to bytes should not fail")
    }

    /// Parses the byte representation of the signature.
    pub fn from_slice(bytes: &[u8]) -> Result<Self, CryptoError> {
        bcs::from_bytes(bytes).map_err(CryptoError::SignatureParseError)
    }
}

impl FromStr for AccountPublicKey {
    type Err = CryptoError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let value = hex::decode(s)?;
        AccountPublicKey::from_slice(value.as_slice())
    }
}

impl Display for AccountPublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.as_bytes()))
    }
}

impl TryFrom<&[u8]> for AccountSignature {
    type Error = CryptoError;

    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
        AccountSignature::from_slice(bytes)
    }
}

/// Error type for cryptographic errors.
#[derive(Error, Debug)]
#[allow(missing_docs)]
pub enum CryptoError {
    #[error("Signature for object {type_name} is not valid: {error}")]
    InvalidSignature { error: String, type_name: String },
    #[error("Signature from validator is missing")]
    MissingValidatorSignature,
    #[error(transparent)]
    NonHexDigits(#[from] hex::FromHexError),
    #[error(
        "Byte slice has length {0} but a `CryptoHash` requires exactly {expected} bytes",
        expected = FixedBytes::<32>::len_bytes(),
    )]
    IncorrectHashSize(usize),
    #[error(
        "Byte slice has length {len} but a {scheme} `PublicKey` requires exactly {expected} bytes"
    )]
    IncorrectPublicKeySize {
        scheme: &'static str,
        len: usize,
        expected: usize,
    },
    #[error(
        "byte slice has length {len} but a {scheme} `Signature` requires exactly {expected} bytes"
    )]
    IncorrectSignatureBytes {
        scheme: &'static str,
        len: usize,
        expected: usize,
    },
    #[error("Could not parse integer: {0}")]
    ParseIntError(#[from] ParseIntError),
    #[error("secp256k1 error: {0}")]
    Secp256k1Error(k256::ecdsa::Error),
    #[error("could not parse public key: {0}: point at infinity")]
    Secp256k1PointAtInfinity(String),
    #[error("could not parse public key: {0}")]
    PublicKeyParseError(bcs::Error),
    #[error("could not parse signature: {0}")]
    SignatureParseError(bcs::Error),
}

#[cfg(with_getrandom)]
/// Wrapper around [`rand::CryptoRng`] and [`rand::RngCore`].
pub trait CryptoRng: rand::CryptoRng + rand::RngCore + Send + Sync {}

#[cfg(with_getrandom)]
impl<T: rand::CryptoRng + rand::RngCore + Send + Sync> CryptoRng for T {}

#[cfg(with_getrandom)]
impl From<Option<u64>> for Box<dyn CryptoRng> {
    fn from(seed: Option<u64>) -> Self {
        use rand::SeedableRng;

        match seed {
            Some(seed) => Box::new(rand::rngs::StdRng::seed_from_u64(seed)),
            None => Box::new(rand::rngs::OsRng),
        }
    }
}

/// Something that we know how to hash.
pub trait Hashable<Hasher> {
    /// Send the content of `Self` to the given hasher.
    fn write(&self, hasher: &mut Hasher);
}

/// Something that we know how to hash and sign.
pub trait HasTypeName {
    /// The name of the type.
    fn type_name() -> &'static str;
}

/// Activate the blanket implementation of `Hashable` based on serde and BCS.
/// * We use `serde_name` to extract a seed from the name of structs and enums.
/// * We use `BCS` to generate canonical bytes suitable for hashing.
pub trait BcsHashable<'de>: Serialize + Deserialize<'de> {}

/// Activate the blanket implementation of `Signable` based on serde and BCS.
/// * We use `serde_name` to extract a seed from the name of structs and enums.
/// * We use `BCS` to generate canonical bytes suitable for signing.
pub trait BcsSignable<'de>: Serialize + Deserialize<'de> {}

impl<'de, T: BcsSignable<'de>> BcsHashable<'de> for T {}

impl<'de, T, Hasher> Hashable<Hasher> for T
where
    T: BcsHashable<'de>,
    Hasher: io::Write,
{
    fn write(&self, hasher: &mut Hasher) {
        let name = <Self as HasTypeName>::type_name();
        // Note: This assumes that names never contain the separator `::`.
        write!(hasher, "{}::", name).expect("Hasher should not fail");
        bcs::serialize_into(hasher, &self).expect("Message serialization should not fail");
    }
}

impl<Hasher> Hashable<Hasher> for [u8]
where
    Hasher: io::Write,
{
    fn write(&self, hasher: &mut Hasher) {
        hasher.write_all(self).expect("Hasher should not fail");
    }
}

impl<'de, T> HasTypeName for T
where
    T: BcsHashable<'de>,
{
    fn type_name() -> &'static str {
        serde_name::trace_name::<Self>().expect("Self must be a struct or an enum")
    }
}

/// A BCS-signable struct for testing.
#[cfg(with_testing)]
#[derive(Debug, Serialize, Deserialize)]
pub struct TestString(pub String);

#[cfg(with_testing)]
impl TestString {
    /// Creates a new `TestString` with the given string.
    pub fn new(s: impl Into<String>) -> Self {
        Self(s.into())
    }
}

#[cfg(with_testing)]
impl BcsSignable<'_> for TestString {}

/// Reads the `bytes` as four little-endian unsigned 64-bit integers and returns them.
pub(crate) fn le_bytes_to_u64_array(bytes: &[u8]) -> [u64; 4] {
    let mut integers = [0u64; 4];

    integers[0] = u64::from_le_bytes(bytes[0..8].try_into().expect("incorrect indices"));
    integers[1] = u64::from_le_bytes(bytes[8..16].try_into().expect("incorrect indices"));
    integers[2] = u64::from_le_bytes(bytes[16..24].try_into().expect("incorrect indices"));
    integers[3] = u64::from_le_bytes(bytes[24..32].try_into().expect("incorrect indices"));

    integers
}

/// Reads the `bytes` as four big-endian unsigned 64-bit integers and returns them.
pub(crate) fn be_bytes_to_u64_array(bytes: &[u8]) -> [u64; 4] {
    let mut integers = [0u64; 4];

    integers[0] = u64::from_be_bytes(bytes[0..8].try_into().expect("incorrect indices"));
    integers[1] = u64::from_be_bytes(bytes[8..16].try_into().expect("incorrect indices"));
    integers[2] = u64::from_be_bytes(bytes[16..24].try_into().expect("incorrect indices"));
    integers[3] = u64::from_be_bytes(bytes[24..32].try_into().expect("incorrect indices"));

    integers
}

/// Returns the bytes that represent the `integers` in little-endian.
pub(crate) fn u64_array_to_le_bytes(integers: [u64; 4]) -> [u8; 32] {
    let mut bytes = [0u8; 32];

    bytes[0..8].copy_from_slice(&integers[0].to_le_bytes());
    bytes[8..16].copy_from_slice(&integers[1].to_le_bytes());
    bytes[16..24].copy_from_slice(&integers[2].to_le_bytes());
    bytes[24..32].copy_from_slice(&integers[3].to_le_bytes());

    bytes
}

/// Returns the bytes that represent the `integers` in big-endian.
pub(crate) fn u64_array_to_be_bytes(integers: [u64; 4]) -> [u8; 32] {
    let mut bytes = [0u8; 32];

    bytes[0..8].copy_from_slice(&integers[0].to_be_bytes());
    bytes[8..16].copy_from_slice(&integers[1].to_be_bytes());
    bytes[16..24].copy_from_slice(&integers[2].to_be_bytes());
    bytes[24..32].copy_from_slice(&integers[3].to_be_bytes());

    bytes
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::{ed25519::Ed25519SecretKey, secp256k1::Secp256k1KeyPair};

    #[test]
    fn test_u64_array_to_be_bytes() {
        let input = [
            0x0123456789ABCDEF,
            0xFEDCBA9876543210,
            0x0011223344556677,
            0x8899AABBCCDDEEFF,
        ];
        let expected_output = [
            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54,
            0x32, 0x10, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB,
            0xCC, 0xDD, 0xEE, 0xFF,
        ];

        let output = u64_array_to_be_bytes(input);
        assert_eq!(output, expected_output);
        assert_eq!(input, be_bytes_to_u64_array(&u64_array_to_be_bytes(input)));
    }

    #[test]
    fn test_u64_array_to_le_bytes() {
        let input = [
            0x0123456789ABCDEF,
            0xFEDCBA9876543210,
            0x0011223344556677,
            0x8899AABBCCDDEEFF,
        ];
        let expected_output = [
            0xEF, 0xCD, 0xAB, 0x89, 0x67, 0x45, 0x23, 0x01, 0x10, 0x32, 0x54, 0x76, 0x98, 0xBA,
            0xDC, 0xFE, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x00, 0xFF, 0xEE, 0xDD, 0xCC,
            0xBB, 0xAA, 0x99, 0x88,
        ];

        let output = u64_array_to_le_bytes(input);
        assert_eq!(output, expected_output);
        assert_eq!(input, le_bytes_to_u64_array(&u64_array_to_le_bytes(input)));
    }

    #[test]
    fn roundtrip_account_pk_bytes_repr() {
        fn roundtrip_test(secret: AccountSecretKey) {
            let public = secret.public();
            let bytes = public.as_bytes();
            let parsed = AccountPublicKey::from_slice(&bytes).unwrap();
            assert_eq!(public, parsed);
        }
        roundtrip_test(AccountSecretKey::Ed25519(Ed25519SecretKey::generate()));
        roundtrip_test(AccountSecretKey::Secp256k1(
            Secp256k1KeyPair::generate().secret_key,
        ));
    }

    #[test]
    fn roundtrip_signature_bytes_repr() {
        fn roundtrip_test(secret: AccountSecretKey) {
            let test_string = TestString::new("test");
            let signature = secret.sign(&test_string);
            let bytes = signature.to_bytes();
            let parsed = AccountSignature::from_slice(&bytes).unwrap();
            assert_eq!(signature, parsed);
        }
        roundtrip_test(AccountSecretKey::Ed25519(Ed25519SecretKey::generate()));
        roundtrip_test(AccountSecretKey::Secp256k1(
            Secp256k1KeyPair::generate().secret_key,
        ));
    }

    #[test]
    fn roundtrip_display_from_str_pk() {
        fn test(secret: AccountSecretKey) {
            let public = secret.public();
            let display = public.to_string();
            let parsed = AccountPublicKey::from_str(&display).unwrap();
            assert_eq!(public, parsed);
        }
        test(AccountSecretKey::Ed25519(Ed25519SecretKey::generate()));
        test(AccountSecretKey::Secp256k1(
            Secp256k1KeyPair::generate().secret_key,
        ));
    }
}