Skip to main content

starfish_config/
crypto.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5//! Here we select the cryptographic types that are used by default in the code
6//! base. The whole code base should only:
7//! - refer to those aliases and not use the individual scheme implementations
8//! - not use the schemes in a way that break genericity (e.g. using their Struct impl functions)
9//! - swap one of those aliases to point to another type if necessary
10//!
11//! Beware: if you change those aliases to point to another scheme
12//! implementation, you will have to change all four aliases to point to
13//! concrete types that work with each other. Failure to do so will result in a
14//! ton of compilation errors, and worse: it will not make sense!
15
16use fastcrypto::{
17    bls12381, ed25519,
18    error::FastCryptoError,
19    hash::{Digest, HashFunction},
20    traits::{KeyPair as _, Signer as _, ToFromBytes as _, VerifyingKey as _},
21};
22use iota_sdk_types::crypto::INTENT_PREFIX_LENGTH;
23use rs_merkle::Hasher;
24use serde::{Deserialize, Serialize};
25use tracing::instrument;
26
27/// Network key is used for TLS and as the network identity of the authority.
28#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
29pub struct NetworkPublicKey(iota_sdk_types::Ed25519PublicKey);
30#[derive(Clone)]
31pub struct NetworkKeyPair(iota_sdk_crypto::ed25519::Ed25519PrivateKey);
32
33impl NetworkPublicKey {
34    pub fn new(key: iota_sdk_types::Ed25519PublicKey) -> Self {
35        Self(key)
36    }
37
38    pub fn into_inner(self) -> iota_sdk_types::Ed25519PublicKey {
39        self.0
40    }
41
42    pub fn to_bytes(&self) -> [u8; 32] {
43        self.0.into_bytes()
44    }
45}
46
47impl NetworkKeyPair {
48    pub fn new(private_key: iota_sdk_crypto::ed25519::Ed25519PrivateKey) -> Self {
49        Self(private_key)
50    }
51
52    pub fn generate<R: rand08::RngCore + rand08::CryptoRng>(rng: &mut R) -> Self {
53        let mut seed = [0u8; 32];
54        rng.fill_bytes(&mut seed);
55        Self(iota_sdk_crypto::ed25519::Ed25519PrivateKey::new(seed))
56    }
57
58    pub fn public(&self) -> NetworkPublicKey {
59        NetworkPublicKey(self.0.public_key())
60    }
61
62    pub fn private_key(self) -> iota_sdk_crypto::ed25519::Ed25519PrivateKey {
63        self.0
64    }
65}
66
67/// Protocol key is used for signing blocks and verifying block signatures.
68#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
69pub struct ProtocolPublicKey(ed25519::Ed25519PublicKey);
70pub struct ProtocolKeyPair(ed25519::Ed25519KeyPair);
71pub struct ProtocolKeySignature(ed25519::Ed25519Signature);
72
73impl ProtocolPublicKey {
74    pub fn new(key: ed25519::Ed25519PublicKey) -> Self {
75        Self(key)
76    }
77
78    pub fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
79        Ok(Self(ed25519::Ed25519PublicKey::from_bytes(bytes)?))
80    }
81
82    #[instrument(level = "trace", skip_all)]
83    pub fn verify(
84        &self,
85        message: &[u8],
86        signature: &ProtocolKeySignature,
87    ) -> Result<(), FastCryptoError> {
88        self.0.verify(message, &signature.0)
89    }
90
91    pub fn to_bytes(&self) -> &[u8] {
92        self.0.as_bytes()
93    }
94}
95
96impl ProtocolKeyPair {
97    pub fn new(keypair: ed25519::Ed25519KeyPair) -> Self {
98        Self(keypair)
99    }
100
101    pub fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
102        Ok(Self(ed25519::Ed25519KeyPair::from_bytes(bytes)?))
103    }
104
105    pub fn generate<R: fastcrypto::traits::AllowedRng>(rng: &mut R) -> Self {
106        Self(ed25519::Ed25519KeyPair::generate(rng))
107    }
108
109    pub fn public(&self) -> ProtocolPublicKey {
110        ProtocolPublicKey(self.0.public().clone())
111    }
112
113    #[instrument(level = "trace", skip_all)]
114    pub fn sign(&self, message: &[u8]) -> ProtocolKeySignature {
115        ProtocolKeySignature(self.0.sign(message))
116    }
117}
118
119impl Clone for ProtocolKeyPair {
120    fn clone(&self) -> Self {
121        Self(self.0.copy())
122    }
123}
124
125impl ProtocolKeySignature {
126    pub fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
127        Ok(Self(ed25519::Ed25519Signature::from_bytes(bytes)?))
128    }
129
130    pub fn to_bytes(&self) -> &[u8] {
131        self.0.as_bytes()
132    }
133}
134
135/// Authority key represents the identity of an authority. It is only used for
136/// identity sanity checks and not used for verification.
137#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
138pub struct AuthorityPublicKey(bls12381::min_sig::BLS12381PublicKey);
139pub struct AuthorityKeyPair(bls12381::min_sig::BLS12381KeyPair);
140
141impl AuthorityPublicKey {
142    pub fn new(key: bls12381::min_sig::BLS12381PublicKey) -> Self {
143        Self(key)
144    }
145
146    pub fn inner(&self) -> &bls12381::min_sig::BLS12381PublicKey {
147        &self.0
148    }
149
150    pub fn to_bytes(&self) -> &[u8] {
151        self.0.as_bytes()
152    }
153}
154
155impl AuthorityKeyPair {
156    pub fn new(keypair: bls12381::min_sig::BLS12381KeyPair) -> Self {
157        Self(keypair)
158    }
159
160    pub fn generate<R: fastcrypto::traits::AllowedRng>(rng: &mut R) -> Self {
161        Self(bls12381::min_sig::BLS12381KeyPair::generate(rng))
162    }
163
164    pub fn public(&self) -> AuthorityPublicKey {
165        AuthorityPublicKey(self.0.public().clone())
166    }
167}
168
169#[derive(Default)]
170pub struct Blake3Hasher {
171    hasher: blake3::Hasher,
172}
173
174impl HashFunction<32> for Blake3Hasher {
175    fn update<Data: AsRef<[u8]>>(&mut self, data: Data) {
176        self.hasher.update(data.as_ref());
177    }
178
179    fn finalize(self) -> Digest<32> {
180        let mut out = [0u8; 32];
181        out.copy_from_slice(self.hasher.finalize().as_bytes());
182        Digest { digest: out }
183    }
184}
185
186/// Fast hash function (Blake3) for consensus-related operations.
187/// Since transactions are encoded, their serializations are increased by
188/// approximately three times, making Blake3’s higher throughput beneficial for
189/// overall performance.
190pub type DefaultHashFunction = Blake3Hasher;
191
192#[derive(Clone)]
193pub struct DefaultHashFunctionWrapper;
194
195impl Hasher for DefaultHashFunctionWrapper {
196    type Hash = [u8; DefaultHashFunction::OUTPUT_SIZE];
197    fn hash(data: &[u8]) -> [u8; DefaultHashFunction::OUTPUT_SIZE] {
198        let mut hasher = DefaultHashFunction::new();
199        hasher.update(data);
200        hasher.finalize().into()
201    }
202}
203
204pub const DIGEST_LENGTH: usize = DefaultHashFunction::OUTPUT_SIZE;
205pub const INTENT_MESSAGE_LENGTH: usize = INTENT_PREFIX_LENGTH + DIGEST_LENGTH;