Skip to main content

iota_types/
crypto.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5// This module broadly handles cryptographic types and operations.
6
7use std::{
8    collections::BTreeMap,
9    fmt::{Debug, Display, Formatter},
10    hash::{Hash, Hasher},
11    str::FromStr,
12};
13
14use anyhow::{Error, anyhow};
15use derive_more::{AsRef, From};
16pub use enum_dispatch::enum_dispatch;
17use eyre::eyre;
18pub use fastcrypto::traits::{
19    AggregateAuthenticator, Authenticator, EncodeDecodeBase64, KeyPair as KeypairTraits, Signer,
20    SigningKey, ToFromBytes, VerifyingKey,
21};
22use fastcrypto::{
23    bls12381::min_sig::{
24        BLS12381AggregateSignature, BLS12381AggregateSignatureAsBytes, BLS12381KeyPair,
25        BLS12381PrivateKey, BLS12381PublicKey, BLS12381Signature,
26    },
27    ed25519::{Ed25519PublicKey, Ed25519PublicKeyAsBytes, Ed25519Signature},
28    encoding::{Base64, Encoding, Hex},
29    error::{FastCryptoError, FastCryptoResult},
30    hash::{Blake2b256, HashFunction},
31    secp256k1::{Secp256k1PublicKey, Secp256k1PublicKeyAsBytes},
32    secp256r1::{Secp256r1PublicKey, Secp256r1PublicKeyAsBytes},
33    serde_helpers::BytesRepresentation,
34};
35use iota_sdk_crypto::{
36    ed25519::Ed25519PrivateKey, secp256k1::Secp256k1PrivateKey, secp256r1::Secp256r1PrivateKey,
37    simple::SimpleKeypair,
38};
39use iota_sdk_types::{
40    Address, SignatureScheme,
41    crypto::{Intent, IntentMessage, IntentScope, SimpleSignature},
42};
43use rand::{
44    SeedableRng,
45    rand_core::UnwrapErr,
46    rngs::{StdRng, SysRng},
47};
48use rand08::SeedableRng as _;
49use roaring::RoaringBitmap;
50use serde::{Deserialize, Serialize};
51use serde_with::{Bytes, serde_as};
52use tracing::{instrument, warn};
53
54use crate::{
55    base_types::{AuthorityName, ConciseableName},
56    committee::{Committee, CommitteeTrait, EpochId, StakeUnit},
57    error::{IotaError, IotaResult},
58    iota_serde::{IotaBitmap, Readable},
59};
60
61#[cfg(test)]
62#[path = "unit_tests/crypto_tests.rs"]
63mod crypto_tests;
64
65#[cfg(test)]
66#[path = "unit_tests/intent_tests.rs"]
67mod intent_tests;
68
69////////////////////////////////////////////////////////////////////////
70// Type aliases selecting the signature algorithm for the code base.
71////////////////////////////////////////////////////////////////////////
72// Here we select the types that are used by default in the code base.
73// The whole code base should only:
74// - refer to those aliases and not use the individual scheme implementations
75// - not use the schemes in a way that break genericity (e.g. using their Struct impl functions)
76// - swap one of those aliases to point to another type if necessary
77//
78// Beware: if you change those aliases to point to another scheme
79// implementation, you will have to change all related aliases to point to
80// concrete types that work with each other. Failure to do so will result in a
81// ton of compilation errors, and worse: it will not make sense!
82
83// Authority Objects
84pub type AuthorityKeyPair = BLS12381KeyPair;
85pub type AuthorityPublicKey = BLS12381PublicKey;
86pub type AuthorityPrivateKey = BLS12381PrivateKey;
87pub type AuthoritySignature = BLS12381Signature;
88pub type AggregateAuthorityPublicKey = BLS12381PublicKey;
89pub type AggregateAuthoritySignature = BLS12381AggregateSignature;
90pub type AggregateAuthoritySignatureAsBytes = BLS12381AggregateSignatureAsBytes;
91
92pub type AccountPrivateKey = Ed25519PrivateKey;
93
94pub type NetworkPrivateKey = Ed25519PrivateKey;
95pub type NetworkPublicKey = iota_sdk_types::Ed25519PublicKey;
96
97pub type DefaultHash = Blake2b256;
98
99pub const DEFAULT_EPOCH_ID: EpochId = 0;
100pub const IOTA_PRIV_KEY_PREFIX: &str = "iotaprivkey";
101
102/// Creates a proof of that the authority account address is owned by the
103/// holder of authority key, and also ensures that the authority
104/// public key exists. A proof of possession is an authority
105/// signature committed over the intent message `intent || message || epoch`
106/// (See more at [struct IntentMessage] and [struct Intent]) where the message
107/// is constructed as `authority_pubkey_bytes || authority_account_address`.
108pub fn generate_proof_of_possession(
109    keypair: &AuthorityKeyPair,
110    address: Address,
111) -> AuthoritySignature {
112    let mut msg: Vec<u8> = Vec::new();
113    msg.extend_from_slice(keypair.public().as_bytes());
114    msg.extend_from_slice(address.as_ref());
115    AuthoritySignature::new_secure(
116        &IntentMessage::new(Intent::iota_app(IntentScope::ProofOfPossession), msg),
117        &DEFAULT_EPOCH_ID,
118        keypair,
119    )
120}
121
122/// Verify proof of possession against the expected intent message,
123/// consisting of the authority pubkey and the authority account address.
124pub fn verify_proof_of_possession(
125    pop: &AuthoritySignature,
126    authority_pubkey: &AuthorityPublicKey,
127    iota_address: Address,
128) -> Result<(), IotaError> {
129    authority_pubkey
130        .validate()
131        .map_err(|_| IotaError::InvalidSignature {
132            error: "Fail to validate pubkey".to_string(),
133        })?;
134    let mut msg = authority_pubkey.as_bytes().to_vec();
135    msg.extend_from_slice(iota_address.as_ref());
136    pop.verify_secure(
137        &IntentMessage::new(Intent::iota_app(IntentScope::ProofOfPossession), msg),
138        DEFAULT_EPOCH_ID,
139        authority_pubkey.into(),
140    )
141}
142
143/// Parse an ed25519 network public key, rejecting bytes that do not encode a
144/// valid curve point.
145pub fn network_pubkey_from_bytes(
146    bytes: &[u8],
147) -> Result<NetworkPublicKey, iota_sdk_crypto::SignatureError> {
148    use iota_sdk_types::crypto::PublicKeyExt as _;
149
150    let pubkey = NetworkPublicKey::from_bytes(bytes)
151        .map_err(iota_sdk_crypto::SignatureError::from_source)?;
152    iota_sdk_crypto::ed25519::Ed25519VerifyingKey::new(&pubkey)?;
153    Ok(pubkey)
154}
155
156impl From<&SimpleKeypair> for PublicKey {
157    fn from(kp: &SimpleKeypair) -> Self {
158        match kp.public_key() {
159            iota_sdk_types::PublicKey::Ed25519(pk) => {
160                PublicKey::Ed25519(BytesRepresentation(pk.into_bytes()))
161            }
162            iota_sdk_types::PublicKey::Secp256k1(pk) => {
163                PublicKey::Secp256k1(BytesRepresentation(pk.into_bytes()))
164            }
165            iota_sdk_types::PublicKey::Secp256r1(pk) => {
166                PublicKey::Secp256r1(BytesRepresentation(pk.into_bytes()))
167            }
168            _ => unreachable!("SimpleKeypair keys use the three simple signature schemes"),
169        }
170    }
171}
172
173#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
174pub enum PublicKey {
175    Ed25519(Ed25519PublicKeyAsBytes),
176    Secp256k1(Secp256k1PublicKeyAsBytes),
177    Secp256r1(Secp256r1PublicKeyAsBytes),
178    Passkey(Secp256r1PublicKeyAsBytes),
179}
180
181impl AsRef<[u8]> for PublicKey {
182    fn as_ref(&self) -> &[u8] {
183        match self {
184            PublicKey::Ed25519(pk) => &pk.0,
185            PublicKey::Secp256k1(pk) => &pk.0,
186            PublicKey::Secp256r1(pk) => &pk.0,
187            PublicKey::Passkey(pk) => &pk.0,
188        }
189    }
190}
191
192impl EncodeDecodeBase64 for PublicKey {
193    fn encode_base64(&self) -> String {
194        let mut bytes: Vec<u8> = Vec::new();
195        bytes.extend_from_slice(&[self.flag()]);
196        bytes.extend_from_slice(self.as_ref());
197        Base64::encode(&bytes[..])
198    }
199
200    fn decode_base64(value: &str) -> FastCryptoResult<Self> {
201        let bytes = Base64::decode(value)?;
202        match bytes.first() {
203            Some(x) => {
204                if x == &SignatureScheme::Ed25519.to_u8() {
205                    let pk: Ed25519PublicKey =
206                        Ed25519PublicKey::from_bytes(bytes.get(1..).ok_or(
207                            FastCryptoError::InputLengthWrong(Ed25519PublicKey::LENGTH + 1),
208                        )?)?;
209                    Ok(PublicKey::Ed25519((&pk).into()))
210                } else if x == &SignatureScheme::Secp256k1.to_u8() {
211                    let pk = Secp256k1PublicKey::from_bytes(bytes.get(1..).ok_or(
212                        FastCryptoError::InputLengthWrong(Secp256k1PublicKey::LENGTH + 1),
213                    )?)?;
214                    Ok(PublicKey::Secp256k1((&pk).into()))
215                } else if x == &SignatureScheme::Secp256r1.to_u8() {
216                    let pk = Secp256r1PublicKey::from_bytes(bytes.get(1..).ok_or(
217                        FastCryptoError::InputLengthWrong(Secp256r1PublicKey::LENGTH + 1),
218                    )?)?;
219                    Ok(PublicKey::Secp256r1((&pk).into()))
220                } else if x == &SignatureScheme::PasskeyAuthenticator.to_u8() {
221                    let pk = Secp256r1PublicKey::from_bytes(bytes.get(1..).ok_or(
222                        FastCryptoError::InputLengthWrong(Secp256r1PublicKey::LENGTH + 1),
223                    )?)?;
224                    Ok(PublicKey::Passkey((&pk).into()))
225                } else {
226                    Err(FastCryptoError::InvalidInput)
227                }
228            }
229            _ => Err(FastCryptoError::InvalidInput),
230        }
231    }
232}
233
234impl PublicKey {
235    pub fn flag(&self) -> u8 {
236        self.scheme().to_u8()
237    }
238
239    pub fn try_from_bytes(
240        curve: SignatureScheme,
241        key_bytes: &[u8],
242    ) -> Result<PublicKey, eyre::Report> {
243        match curve {
244            SignatureScheme::Ed25519 => Ok(PublicKey::Ed25519(
245                (&Ed25519PublicKey::from_bytes(key_bytes)?).into(),
246            )),
247            SignatureScheme::Secp256k1 => Ok(PublicKey::Secp256k1(
248                (&Secp256k1PublicKey::from_bytes(key_bytes)?).into(),
249            )),
250            SignatureScheme::Secp256r1 => Ok(PublicKey::Secp256r1(
251                (&Secp256r1PublicKey::from_bytes(key_bytes)?).into(),
252            )),
253            SignatureScheme::PasskeyAuthenticator => Ok(PublicKey::Passkey(
254                (&Secp256r1PublicKey::from_bytes(key_bytes)?).into(),
255            )),
256            _ => Err(eyre!("Unsupported curve")),
257        }
258    }
259
260    pub fn scheme(&self) -> SignatureScheme {
261        match self {
262            PublicKey::Ed25519(_) => SignatureScheme::Ed25519,
263            PublicKey::Secp256k1(_) => SignatureScheme::Secp256k1,
264            PublicKey::Secp256r1(_) => SignatureScheme::Secp256r1,
265            PublicKey::Passkey(_) => SignatureScheme::PasskeyAuthenticator,
266        }
267    }
268}
269
270/// Defines the compressed version of the public key that we pass around
271/// in IOTA.
272#[serde_as]
273#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, AsRef)]
274#[as_ref(forward)]
275pub struct AuthorityPublicKeyBytes(
276    #[serde_as(as = "Readable<Base64, Bytes>")] pub [u8; AuthorityPublicKey::LENGTH],
277);
278
279impl AuthorityPublicKeyBytes {
280    fn fmt_impl(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
281        let s = Hex::encode(self.0);
282        write!(f, "k#{s}")?;
283        Ok(())
284    }
285}
286
287impl<'a> ConciseableName<'a> for AuthorityPublicKeyBytes {
288    type ConciseTypeRef = ConciseAuthorityPublicKeyBytesRef<'a>;
289    type ConciseType = ConciseAuthorityPublicKeyBytes;
290
291    /// Get a ConciseAuthorityPublicKeyBytesRef. Usage:
292    ///
293    ///   debug!(name = ?authority.concise());
294    ///   format!("{:?}", authority.concise());
295    fn concise(&'a self) -> ConciseAuthorityPublicKeyBytesRef<'a> {
296        ConciseAuthorityPublicKeyBytesRef(self)
297    }
298
299    fn concise_owned(&self) -> ConciseAuthorityPublicKeyBytes {
300        ConciseAuthorityPublicKeyBytes(*self)
301    }
302}
303
304/// A wrapper around AuthorityPublicKeyBytes that provides a concise Debug impl.
305pub struct ConciseAuthorityPublicKeyBytesRef<'a>(&'a AuthorityPublicKeyBytes);
306
307impl Debug for ConciseAuthorityPublicKeyBytesRef<'_> {
308    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
309        let s = Hex::encode(self.0.0.get(0..4).ok_or(std::fmt::Error)?);
310        write!(f, "k#{s}..")
311    }
312}
313
314impl Display for ConciseAuthorityPublicKeyBytesRef<'_> {
315    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
316        Debug::fmt(self, f)
317    }
318}
319
320/// A wrapper around AuthorityPublicKeyBytes but owns it.
321#[derive(Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
322pub struct ConciseAuthorityPublicKeyBytes(AuthorityPublicKeyBytes);
323
324impl Debug for ConciseAuthorityPublicKeyBytes {
325    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
326        let s = Hex::encode(self.0.0.get(0..4).ok_or(std::fmt::Error)?);
327        write!(f, "k#{s}..")
328    }
329}
330
331impl Display for ConciseAuthorityPublicKeyBytes {
332    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
333        Debug::fmt(self, f)
334    }
335}
336
337impl TryFrom<AuthorityPublicKeyBytes> for AggregateAuthorityPublicKey {
338    type Error = FastCryptoError;
339
340    fn try_from(
341        bytes: AuthorityPublicKeyBytes,
342    ) -> Result<AggregateAuthorityPublicKey, Self::Error> {
343        AggregateAuthorityPublicKey::from_bytes(bytes.as_ref())
344    }
345}
346
347impl From<&AggregateAuthorityPublicKey> for AuthorityPublicKeyBytes {
348    fn from(pk: &AggregateAuthorityPublicKey) -> AuthorityPublicKeyBytes {
349        AuthorityPublicKeyBytes::from_bytes(pk.as_ref()).unwrap()
350    }
351}
352
353impl Debug for AuthorityPublicKeyBytes {
354    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
355        self.fmt_impl(f)
356    }
357}
358
359impl Display for AuthorityPublicKeyBytes {
360    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
361        self.fmt_impl(f)
362    }
363}
364
365impl ToFromBytes for AuthorityPublicKeyBytes {
366    fn from_bytes(bytes: &[u8]) -> Result<Self, fastcrypto::error::FastCryptoError> {
367        let bytes: [u8; AuthorityPublicKey::LENGTH] = bytes
368            .try_into()
369            .map_err(|_| fastcrypto::error::FastCryptoError::InvalidInput)?;
370        Ok(AuthorityPublicKeyBytes(bytes))
371    }
372}
373
374impl AuthorityPublicKeyBytes {
375    pub const ZERO: Self = Self::new([0u8; AuthorityPublicKey::LENGTH]);
376
377    /// This ensures it's impossible to construct an instance with other than
378    /// registered lengths
379    pub const fn new(bytes: [u8; AuthorityPublicKey::LENGTH]) -> AuthorityPublicKeyBytes
380where {
381        AuthorityPublicKeyBytes(bytes)
382    }
383}
384
385impl FromStr for AuthorityPublicKeyBytes {
386    type Err = Error;
387
388    fn from_str(s: &str) -> Result<Self, Self::Err> {
389        let value = Hex::decode(s).map_err(|e| anyhow!(e))?;
390        Self::from_bytes(&value[..]).map_err(|e| anyhow!(e))
391    }
392}
393
394impl Default for AuthorityPublicKeyBytes {
395    fn default() -> Self {
396        Self::ZERO
397    }
398}
399
400// Add helper calls for Authority Signature
401//
402
403pub trait IotaAuthoritySignature {
404    fn verify_secure<T>(
405        &self,
406        value: &IntentMessage<T>,
407        epoch_id: EpochId,
408        author: AuthorityPublicKeyBytes,
409    ) -> Result<(), IotaError>
410    where
411        T: Serialize;
412
413    fn new_secure<T>(
414        value: &IntentMessage<T>,
415        epoch_id: &EpochId,
416        secret: &dyn Signer<Self>,
417    ) -> Self
418    where
419        T: Serialize;
420}
421
422impl IotaAuthoritySignature for AuthoritySignature {
423    #[instrument(level = "trace", skip_all)]
424    fn new_secure<T>(value: &IntentMessage<T>, epoch: &EpochId, secret: &dyn Signer<Self>) -> Self
425    where
426        T: Serialize,
427    {
428        let mut intent_msg_bytes =
429            bcs::to_bytes(&value).expect("Message serialization should not fail");
430        epoch.write(&mut intent_msg_bytes);
431        secret.sign(&intent_msg_bytes)
432    }
433
434    #[instrument(level = "trace", skip_all)]
435    fn verify_secure<T>(
436        &self,
437        value: &IntentMessage<T>,
438        epoch: EpochId,
439        author: AuthorityPublicKeyBytes,
440    ) -> Result<(), IotaError>
441    where
442        T: Serialize,
443    {
444        let mut message = bcs::to_bytes(&value).expect("Message serialization should not fail");
445        epoch.write(&mut message);
446
447        let public_key = AuthorityPublicKey::try_from(author).map_err(|_| {
448            IotaError::KeyConversion(
449                "Failed to serialize public key bytes to valid public key".to_string(),
450            )
451        })?;
452        public_key
453            .verify(&message[..], self)
454            .map_err(|e| IotaError::InvalidSignature {
455                error: format!(
456                    "Fail to verify auth sig {} epoch: {} author: {}",
457                    e,
458                    epoch,
459                    author.concise()
460                ),
461            })
462    }
463}
464
465/// Random key-pair generation for the `get_key_pair` helpers, implemented for
466/// the fastcrypto authority keypair and the SDK ed25519/secp keys.
467pub trait RandomKeyPair: Sized {
468    fn generate_with_address(seed: [u8; 32]) -> (Address, Self);
469}
470
471impl RandomKeyPair for BLS12381KeyPair {
472    fn generate_with_address(seed: [u8; 32]) -> (Address, Self) {
473        let kp = <BLS12381KeyPair as KeypairTraits>::generate(
474            &mut rand08::rngs::StdRng::from_seed(seed),
475        );
476        // Authority keys have no on-chain account; this address only labels
477        // key files and `keytool` output.
478        let mut hasher = DefaultHash::default();
479        hasher.update([SignatureScheme::Bls12381.to_u8()]);
480        hasher.update(kp.public().as_ref());
481        (Address::new(hasher.finalize().digest), kp)
482    }
483}
484
485macro_rules! random_key_pair_from_sdk {
486    ($private_key:ty, $variant:ident) => {
487        impl RandomKeyPair for $private_key {
488            fn generate_with_address(seed: [u8; 32]) -> (Address, Self) {
489                let key = <$private_key>::random_with(StdRng::from_seed(seed));
490                let public =
491                    PublicKey::$variant(BytesRepresentation(key.public_key().into_bytes()));
492                (Address::from(&public), key)
493            }
494        }
495    };
496}
497
498random_key_pair_from_sdk!(Ed25519PrivateKey, Ed25519);
499random_key_pair_from_sdk!(Secp256k1PrivateKey, Secp256k1);
500random_key_pair_from_sdk!(Secp256r1PrivateKey, Secp256r1);
501
502// TODO: get_key_pair() should return KeyPair only.
503// TODO: rename to random_key_pair
504pub fn get_key_pair<KP: RandomKeyPair>() -> (Address, KP) {
505    get_key_pair_from_rng(&mut UnwrapErr(SysRng))
506}
507
508/// Generate a random committee key pairs with a given committee size
509pub fn random_committee_key_pairs_of_size(size: usize) -> Vec<AuthorityKeyPair> {
510    let mut rng = StdRng::from_seed([0; 32]);
511    (0..size)
512        .map(|_| {
513            // TODO: We are generating the keys 4 times to match exactly as how we generate
514            // keys in ConfigBuilder::build (iota-config/src/network_config_builder). This
515            // is because we are using these key generation functions as
516            // fixtures and we call them independently in different paths and
517            // exact the results to be the same. We should eliminate them.
518            let key_pair = get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut rng);
519            get_key_pair_from_rng::<AuthorityKeyPair, _>(&mut rng);
520            get_key_pair_from_rng::<AccountPrivateKey, _>(&mut rng);
521            get_key_pair_from_rng::<AccountPrivateKey, _>(&mut rng);
522            key_pair.1
523        })
524        .collect()
525}
526
527pub fn deterministic_random_account_private_key() -> (Address, AccountPrivateKey) {
528    let mut rng = StdRng::from_seed([0; 32]);
529    get_key_pair_from_rng(&mut rng)
530}
531
532pub fn get_account_private_key() -> (Address, AccountPrivateKey) {
533    get_key_pair()
534}
535
536pub fn get_authority_key_pair() -> (Address, AuthorityKeyPair) {
537    get_key_pair()
538}
539
540/// Generate a keypair from the specified RNG (useful for testing with seedable
541/// rngs).
542pub fn get_key_pair_from_rng<KP: RandomKeyPair, R>(csprng: &mut R) -> (Address, KP)
543where
544    R: rand::CryptoRng,
545{
546    let mut seed = [0u8; 32];
547    csprng.fill_bytes(&mut seed);
548    KP::generate_with_address(seed)
549}
550
551/// An all-zero ed25519 [`SimpleSignature`] placeholder, used for system
552/// transactions (which are not signed) and in tests where the signature
553/// content is irrelevant.
554pub fn zero_ed25519_signature() -> SimpleSignature {
555    // `flag || signature || public key`, all zero; the leading zero byte selects
556    // the ed25519 scheme.
557    SimpleSignature::from_bytes([0u8; 1 + Ed25519Signature::LENGTH + Ed25519PublicKey::LENGTH])
558        .expect("zero-filled ed25519 signature has the expected length")
559}
560
561// BLS Port
562//
563
564impl IotaPublicKey for BLS12381PublicKey {
565    const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Bls12381;
566}
567
568impl IotaPublicKey for Ed25519PublicKey {
569    const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Ed25519;
570}
571
572impl IotaPublicKey for Secp256k1PublicKey {
573    const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Secp256k1;
574}
575
576impl IotaPublicKey for Secp256r1PublicKey {
577    const SIGNATURE_SCHEME: SignatureScheme = SignatureScheme::Secp256r1;
578}
579
580pub trait IotaPublicKey: VerifyingKey {
581    const SIGNATURE_SCHEME: SignatureScheme;
582}
583
584/// AuthoritySignInfoTrait is a trait used specifically for a few structs in
585/// messages.rs to template on whether the struct is signed by an authority. We
586/// want to limit how those structs can be instantiated on, hence the sealed
587/// trait. TODO: We could also add the aggregated signature as another impl of
588/// the trait.       This will make CertifiedTransaction also an instance of the
589/// same struct.
590pub trait AuthoritySignInfoTrait: private::SealedAuthoritySignInfoTrait {
591    fn verify_secure<T: Serialize>(
592        &self,
593        data: &T,
594        intent: Intent,
595        committee: &Committee,
596    ) -> IotaResult;
597
598    fn add_to_verification_obligation<'a>(
599        &self,
600        committee: &'a Committee,
601        obligation: &mut VerificationObligation<'a>,
602        message_index: usize,
603    ) -> IotaResult<()>;
604}
605
606#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
607pub struct EmptySignInfo {}
608impl AuthoritySignInfoTrait for EmptySignInfo {
609    fn verify_secure<T: Serialize>(
610        &self,
611        _data: &T,
612        _intent: Intent,
613        _committee: &Committee,
614    ) -> IotaResult {
615        Ok(())
616    }
617
618    fn add_to_verification_obligation<'a>(
619        &self,
620        _committee: &'a Committee,
621        _obligation: &mut VerificationObligation<'a>,
622        _message_index: usize,
623    ) -> IotaResult<()> {
624        Ok(())
625    }
626}
627
628#[derive(Clone, Debug, Eq, Serialize, Deserialize)]
629pub struct AuthoritySignInfo {
630    pub epoch: EpochId,
631    pub authority: AuthorityName,
632    pub signature: AuthoritySignature,
633}
634
635impl AuthoritySignInfoTrait for AuthoritySignInfo {
636    #[instrument(level = "trace", skip_all)]
637    fn verify_secure<T: Serialize>(
638        &self,
639        data: &T,
640        intent: Intent,
641        committee: &Committee,
642    ) -> IotaResult<()> {
643        let mut obligation = VerificationObligation::default();
644        let idx = obligation.add_message(data, self.epoch, intent);
645        self.add_to_verification_obligation(committee, &mut obligation, idx)?;
646        obligation.verify_all()?;
647        Ok(())
648    }
649
650    fn add_to_verification_obligation<'a>(
651        &self,
652        committee: &'a Committee,
653        obligation: &mut VerificationObligation<'a>,
654        message_index: usize,
655    ) -> IotaResult<()> {
656        fp_ensure!(
657            self.epoch == committee.epoch(),
658            IotaError::WrongEpoch {
659                expected_epoch: committee.epoch(),
660                actual_epoch: self.epoch,
661            }
662        );
663        let weight = committee.weight(&self.authority);
664        fp_ensure!(
665            weight > 0,
666            IotaError::UnknownSigner {
667                signer: Some(self.authority.concise().to_string()),
668                index: None,
669                committee: Box::new(committee.clone())
670            }
671        );
672
673        obligation
674            .public_keys
675            .get_mut(message_index)
676            .ok_or(IotaError::InvalidAddress)?
677            .push(committee.public_key(&self.authority)?);
678        obligation
679            .signatures
680            .get_mut(message_index)
681            .ok_or(IotaError::InvalidAddress)?
682            .add_signature(self.signature.clone())
683            .map_err(|_| IotaError::InvalidSignature {
684                error: "Fail to aggregator auth sig".to_string(),
685            })?;
686        Ok(())
687    }
688}
689
690impl AuthoritySignInfo {
691    pub fn new<T>(
692        epoch: EpochId,
693        value: &T,
694        intent: Intent,
695        name: AuthorityName,
696        secret: &dyn Signer<AuthoritySignature>,
697    ) -> Self
698    where
699        T: Serialize,
700    {
701        Self {
702            epoch,
703            authority: name,
704            signature: AuthoritySignature::new_secure(
705                &IntentMessage::new(intent, value),
706                &epoch,
707                secret,
708            ),
709        }
710    }
711}
712
713impl Hash for AuthoritySignInfo {
714    fn hash<H: Hasher>(&self, state: &mut H) {
715        self.epoch.hash(state);
716        self.authority.hash(state);
717    }
718}
719
720impl Display for AuthoritySignInfo {
721    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
722        write!(
723            f,
724            "AuthoritySignInfo {{ epoch: {:?}, authority: {} }}",
725            self.epoch, self.authority,
726        )
727    }
728}
729
730impl PartialEq for AuthoritySignInfo {
731    fn eq(&self, other: &Self) -> bool {
732        // We do not compare the signature, because there can be multiple
733        // valid signatures for the same epoch and authority.
734        self.epoch == other.epoch && self.authority == other.authority
735    }
736}
737
738/// Represents at least a quorum (could be more) of authority signatures.
739/// STRONG_THRESHOLD indicates whether to use the quorum threshold for quorum
740/// check. When STRONG_THRESHOLD is true, the quorum is valid when the total
741/// stake is at least the quorum threshold (2f+1) of the committee; when
742/// STRONG_THRESHOLD is false, the quorum is valid when the total stake is at
743/// least the validity threshold (f+1) of the committee.
744#[serde_as]
745#[derive(Clone, Debug, Serialize, Deserialize)]
746pub struct AuthorityQuorumSignInfo<const STRONG_THRESHOLD: bool> {
747    pub epoch: EpochId,
748    pub signature: AggregateAuthoritySignature,
749    #[serde_as(as = "IotaBitmap")]
750    pub signers_map: RoaringBitmap,
751}
752
753pub type AuthorityStrongQuorumSignInfo = AuthorityQuorumSignInfo<true>;
754
755// Variant of [AuthorityStrongQuorumSignInfo] but with a serialized signature,
756// to be used in external APIs.
757#[serde_as]
758#[derive(Clone, Debug, Serialize, Deserialize)]
759pub struct IotaAuthorityStrongQuorumSignInfo {
760    pub epoch: EpochId,
761    pub signature: AggregateAuthoritySignatureAsBytes,
762    #[serde_as(as = "IotaBitmap")]
763    pub signers_map: RoaringBitmap,
764}
765
766impl From<&AuthorityStrongQuorumSignInfo> for IotaAuthorityStrongQuorumSignInfo {
767    fn from(info: &AuthorityStrongQuorumSignInfo) -> Self {
768        Self {
769            epoch: info.epoch,
770            signature: (&info.signature).into(),
771            signers_map: info.signers_map.clone(),
772        }
773    }
774}
775
776impl TryFrom<&IotaAuthorityStrongQuorumSignInfo> for AuthorityStrongQuorumSignInfo {
777    type Error = FastCryptoError;
778
779    fn try_from(info: &IotaAuthorityStrongQuorumSignInfo) -> Result<Self, Self::Error> {
780        Ok(Self {
781            epoch: info.epoch,
782            signature: (&info.signature).try_into()?,
783            signers_map: info.signers_map.clone(),
784        })
785    }
786}
787
788// Note: if you meet an error due to this line it may be because you need an Eq
789// implementation for `CertifiedTransaction`, or one of the structs that include
790// it, i.e. `ConfirmationTransaction`, `TransactionInfoResponse` or
791// `ObjectInfoResponse`.
792//
793// Please note that any such implementation must be agnostic to the exact set of
794// signatures in the certificate, as clients are allowed to equivocate on the
795// exact nature of valid certificates they send to the system. This assertion is
796// a simple tool to make sure certificates are accounted for correctly - should
797// you remove it, you're on your own to maintain the invariant that valid
798// certificates with distinct signatures are equivalent, but yet-unchecked
799// certificates that differ on signers aren't.
800//
801// see also https://github.com/iotaledger/iota/issues/266
802static_assertions::assert_not_impl_any!(AuthorityStrongQuorumSignInfo: Hash, Eq, PartialEq);
803
804impl<const STRONG_THRESHOLD: bool> AuthoritySignInfoTrait
805    for AuthorityQuorumSignInfo<STRONG_THRESHOLD>
806{
807    #[instrument(level = "trace", skip_all)]
808    fn verify_secure<T: Serialize>(
809        &self,
810        data: &T,
811        intent: Intent,
812        committee: &Committee,
813    ) -> IotaResult {
814        let mut obligation = VerificationObligation::default();
815        let idx = obligation.add_message(data, self.epoch, intent);
816        self.add_to_verification_obligation(committee, &mut obligation, idx)?;
817        obligation.verify_all()?;
818        Ok(())
819    }
820
821    fn add_to_verification_obligation<'a>(
822        &self,
823        committee: &'a Committee,
824        obligation: &mut VerificationObligation<'a>,
825        message_index: usize,
826    ) -> IotaResult<()> {
827        // Check epoch
828        fp_ensure!(
829            self.epoch == committee.epoch(),
830            IotaError::WrongEpoch {
831                expected_epoch: committee.epoch(),
832                actual_epoch: self.epoch,
833            }
834        );
835
836        let mut weight = 0;
837
838        // Create obligations for the committee signatures
839        obligation
840            .signatures
841            .get_mut(message_index)
842            .ok_or(IotaError::InvalidAuthenticator)?
843            .add_aggregate(self.signature.clone())
844            .map_err(|_| IotaError::InvalidSignature {
845                error: "Signature Aggregation failed".to_string(),
846            })?;
847
848        let selected_public_keys = obligation
849            .public_keys
850            .get_mut(message_index)
851            .ok_or(IotaError::InvalidAuthenticator)?;
852
853        for authority_index in self.signers_map.iter() {
854            let authority = committee
855                .authority_by_index(authority_index)
856                .ok_or_else(|| IotaError::UnknownSigner {
857                    signer: None,
858                    index: Some(authority_index),
859                    committee: Box::new(committee.clone()),
860                })?;
861            let voting_rights = committee.weight(authority);
862            fp_ensure!(
863                voting_rights > 0,
864                IotaError::UnknownSigner {
865                    signer: Some(authority.concise().to_string()),
866                    index: Some(authority_index),
867                    committee: Box::new(committee.clone()),
868                }
869            );
870            weight += voting_rights;
871
872            selected_public_keys.push(committee.public_key(authority)?);
873        }
874
875        fp_ensure!(
876            weight >= Self::quorum_threshold(committee),
877            IotaError::CertificateRequiresQuorum
878        );
879
880        Ok(())
881    }
882}
883
884impl<const STRONG_THRESHOLD: bool> AuthorityQuorumSignInfo<STRONG_THRESHOLD> {
885    pub fn new_from_auth_sign_infos(
886        auth_sign_infos: Vec<AuthoritySignInfo>,
887        committee: &Committee,
888    ) -> IotaResult<Self> {
889        fp_ensure!(
890            auth_sign_infos.iter().all(|a| a.epoch == committee.epoch),
891            IotaError::InvalidSignature {
892                error: "All signatures must be from the same epoch as the committee".to_string()
893            }
894        );
895        let total_stake: StakeUnit = auth_sign_infos
896            .iter()
897            .map(|a| committee.weight(&a.authority))
898            .sum();
899        fp_ensure!(
900            total_stake >= Self::quorum_threshold(committee),
901            IotaError::InvalidSignature {
902                error: "Signatures don't have enough stake to form a quorum".to_string()
903            }
904        );
905
906        let signatures: BTreeMap<_, _> = auth_sign_infos
907            .into_iter()
908            .map(|a| (a.authority, a.signature))
909            .collect();
910        let mut map = RoaringBitmap::new();
911        for pk in signatures.keys() {
912            map.insert(
913                committee
914                    .authority_index(pk)
915                    .ok_or_else(|| IotaError::UnknownSigner {
916                        signer: Some(pk.concise().to_string()),
917                        index: None,
918                        committee: Box::new(committee.clone()),
919                    })?,
920            );
921        }
922        let sigs: Vec<AuthoritySignature> = signatures.into_values().collect();
923
924        Ok(AuthorityQuorumSignInfo {
925            epoch: committee.epoch,
926            signature: AggregateAuthoritySignature::aggregate(&sigs).map_err(|e| {
927                IotaError::InvalidSignature {
928                    error: e.to_string(),
929                }
930            })?,
931            signers_map: map,
932        })
933    }
934
935    pub fn authorities<'a>(
936        &'a self,
937        committee: &'a Committee,
938    ) -> impl Iterator<Item = IotaResult<&'a AuthorityName>> {
939        self.signers_map.iter().map(|i| {
940            committee
941                .authority_by_index(i)
942                .ok_or(IotaError::InvalidAuthenticator)
943        })
944    }
945
946    pub fn quorum_threshold(committee: &Committee) -> StakeUnit {
947        committee.threshold::<STRONG_THRESHOLD>()
948    }
949
950    pub fn len(&self) -> u64 {
951        self.signers_map.len()
952    }
953
954    pub fn is_empty(&self) -> bool {
955        self.signers_map.is_empty()
956    }
957}
958
959impl<const S: bool> Display for AuthorityQuorumSignInfo<S> {
960    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
961        writeln!(
962            f,
963            "{} {{ epoch: {:?}, signers_map: {:?} }}",
964            if S {
965                "AuthorityStrongQuorumSignInfo"
966            } else {
967                "AuthorityWeakQuorumSignInfo"
968            },
969            self.epoch,
970            self.signers_map,
971        )?;
972        Ok(())
973    }
974}
975
976mod private {
977    pub trait SealedAuthoritySignInfoTrait {}
978    impl SealedAuthoritySignInfoTrait for super::EmptySignInfo {}
979    impl SealedAuthoritySignInfoTrait for super::AuthoritySignInfo {}
980    impl<const S: bool> SealedAuthoritySignInfoTrait for super::AuthorityQuorumSignInfo<S> {}
981}
982
983/// Something that we know how to hash and sign.
984pub trait Signable<W> {
985    fn write(&self, writer: &mut W);
986}
987
988/// Activate the blanket implementation of `Signable` based on serde and BCS.
989/// * We use `serde_name` to extract a seed from the name of structs and enums.
990/// * We use `BCS` to generate canonical bytes suitable for hashing and signing.
991///
992/// # Safety
993/// We protect the access to this marker trait through a "sealed trait" pattern:
994/// impls must be add added here (nowehre else) which lets us note those impls
995/// MUST be on types that comply with the `serde_name` machinery
996/// for the below implementations not to panic. One way to check they work is to
997/// write a unit test for serialization to / deserialization from signable
998/// bytes.
999mod bcs_signable {
1000
1001    pub trait BcsSignable: serde::Serialize + serde::de::DeserializeOwned {}
1002    impl BcsSignable for crate::committee::Committee {}
1003    impl BcsSignable for iota_sdk_types::CheckpointSummary {}
1004    impl BcsSignable for iota_sdk_types::CheckpointContents {}
1005    #[cfg(not(target_arch = "wasm32"))]
1006    impl BcsSignable for crate::messages_consensus::VersionedMisbehaviorReport {}
1007
1008    impl BcsSignable for iota_sdk_types::TransactionEffects {}
1009    impl BcsSignable for iota_sdk_types::TransactionEvents {}
1010    impl BcsSignable for iota_sdk_types::Transaction {}
1011    impl BcsSignable for iota_sdk_types::SenderSignedTransaction {}
1012    impl BcsSignable for crate::object::ObjectInner {}
1013
1014    impl BcsSignable for crate::global_state_hash::GlobalStateHash {}
1015
1016    impl BcsSignable for super::bcs_signable_test::Foo {}
1017    #[cfg(test)]
1018    impl BcsSignable for super::bcs_signable_test::Bar {}
1019}
1020
1021impl<T, W> Signable<W> for T
1022where
1023    T: bcs_signable::BcsSignable,
1024    W: std::io::Write,
1025{
1026    fn write(&self, writer: &mut W) {
1027        let name = serde_name::trace_name::<Self>().expect("Self must be a struct or an enum");
1028        // Note: This assumes that names never contain the separator `::`.
1029        write!(writer, "{name}::").expect("Hasher should not fail");
1030        bcs::serialize_into(writer, &self).expect("Message serialization should not fail");
1031    }
1032}
1033
1034impl<W> Signable<W> for EpochId
1035where
1036    W: std::io::Write,
1037{
1038    fn write(&self, writer: &mut W) {
1039        bcs::serialize_into(writer, &self).expect("Message serialization should not fail");
1040    }
1041}
1042
1043fn hash<S: Signable<H>, H: HashFunction<DIGEST_SIZE>, const DIGEST_SIZE: usize>(
1044    signable: &S,
1045) -> [u8; DIGEST_SIZE] {
1046    let mut digest = H::default();
1047    signable.write(&mut digest);
1048    let hash = digest.finalize();
1049    hash.into()
1050}
1051
1052pub fn default_hash<S: Signable<DefaultHash>>(signable: &S) -> [u8; 32] {
1053    hash::<S, DefaultHash, 32>(signable)
1054}
1055
1056#[derive(Default)]
1057pub struct VerificationObligation<'a> {
1058    pub messages: Vec<Vec<u8>>,
1059    pub signatures: Vec<AggregateAuthoritySignature>,
1060    pub public_keys: Vec<Vec<&'a AggregateAuthorityPublicKey>>,
1061}
1062
1063impl<'a> VerificationObligation<'a> {
1064    pub fn new() -> VerificationObligation<'a> {
1065        VerificationObligation::default()
1066    }
1067
1068    /// Add a new message to the list of messages to be verified.
1069    /// Returns the index of the message.
1070    pub fn add_message<T>(&mut self, message_value: &T, epoch: EpochId, intent: Intent) -> usize
1071    where
1072        T: Serialize,
1073    {
1074        let intent_msg = IntentMessage::new(intent, message_value);
1075        let mut intent_msg_bytes =
1076            bcs::to_bytes(&intent_msg).expect("Message serialization should not fail");
1077        epoch.write(&mut intent_msg_bytes);
1078        self.signatures.push(AggregateAuthoritySignature::default());
1079        self.public_keys.push(Vec::new());
1080        self.messages.push(intent_msg_bytes);
1081        self.messages.len() - 1
1082    }
1083
1084    // Attempts to add signature and public key to the obligation. If this fails,
1085    // ensure to call `verify` manually.
1086    pub fn add_signature_and_public_key(
1087        &mut self,
1088        signature: &AuthoritySignature,
1089        public_key: &'a AggregateAuthorityPublicKey,
1090        idx: usize,
1091    ) -> IotaResult<()> {
1092        self.public_keys
1093            .get_mut(idx)
1094            .ok_or(IotaError::InvalidAuthenticator)?
1095            .push(public_key);
1096        self.signatures
1097            .get_mut(idx)
1098            .ok_or(IotaError::InvalidAuthenticator)?
1099            .add_signature(signature.clone())
1100            .map_err(|_| IotaError::InvalidSignature {
1101                error: "Failed to add signature to obligation".to_string(),
1102            })?;
1103        Ok(())
1104    }
1105
1106    #[instrument(level = "trace", skip_all)]
1107    pub fn verify_all(self) -> IotaResult<()> {
1108        let mut pks = Vec::with_capacity(self.public_keys.len());
1109        for pk in self.public_keys.clone() {
1110            pks.push(pk.into_iter());
1111        }
1112        AggregateAuthoritySignature::batch_verify(
1113            &self.signatures.iter().collect::<Vec<_>>()[..],
1114            pks,
1115            &self.messages.iter().map(|x| &x[..]).collect::<Vec<_>>()[..],
1116        )
1117        .map_err(|e| {
1118            let message = format!(
1119                "pks: {:?}, messages: {:?}, sigs: {:?}",
1120                self.public_keys,
1121                self.messages
1122                    .iter()
1123                    .map(Base64::encode)
1124                    .collect::<Vec<String>>(),
1125                self.signatures
1126                    .iter()
1127                    .map(|s| Base64::encode(s.as_ref()))
1128                    .collect::<Vec<String>>()
1129            );
1130
1131            let chunk_size = 2048;
1132
1133            // This error message may be very long, so we print out the error in chunks of
1134            // to avoid hitting a max log line length on the system.
1135            for (i, chunk) in message
1136                .as_bytes()
1137                .chunks(chunk_size)
1138                .map(std::str::from_utf8)
1139                .enumerate()
1140            {
1141                warn!(
1142                    "Failed to batch verify aggregated auth sig: {} (chunk {}): {}",
1143                    e,
1144                    i,
1145                    chunk.unwrap()
1146                );
1147            }
1148
1149            IotaError::InvalidSignature {
1150                error: format!("Failed to batch verify aggregated auth sig: {e}"),
1151            }
1152        })?;
1153        Ok(())
1154    }
1155}
1156
1157pub mod bcs_signable_test {
1158    use serde::{Deserialize, Serialize};
1159
1160    #[derive(Clone, Serialize, Deserialize)]
1161    pub struct Foo(pub String);
1162
1163    #[cfg(test)]
1164    #[derive(Serialize, Deserialize)]
1165    pub struct Bar(pub String);
1166
1167    #[cfg(test)]
1168    use super::VerificationObligation;
1169
1170    #[cfg(test)]
1171    pub fn get_obligation_input<T>(value: &T) -> (VerificationObligation<'_>, usize)
1172    where
1173        T: super::bcs_signable::BcsSignable,
1174    {
1175        use iota_sdk_types::crypto::{Intent, IntentScope};
1176
1177        let mut obligation = VerificationObligation::default();
1178        // Add the obligation of the authority signature verifications.
1179        let idx = obligation.add_message(
1180            value,
1181            0,
1182            Intent::iota_app(IntentScope::SenderSignedTransaction),
1183        );
1184        (obligation, idx)
1185    }
1186}
1187
1188impl FromStr for PublicKey {
1189    type Err = eyre::Report;
1190    fn from_str(s: &str) -> Result<Self, Self::Err> {
1191        Self::decode_base64(s).map_err(|e| eyre!("Fail to decode base64 {}", e.to_string()))
1192    }
1193}
1194
1195// Types for randomness generation
1196//
1197#[cfg(not(target_arch = "wasm32"))]
1198pub type RandomnessSignature = fastcrypto_threshold::types::Signature;
1199#[cfg(not(target_arch = "wasm32"))]
1200pub type RandomnessPartialSignature =
1201    fastcrypto_threshold::tbls::PartialSignature<RandomnessSignature>;
1202#[cfg(not(target_arch = "wasm32"))]
1203pub type RandomnessPrivateKey =
1204    fastcrypto_threshold::ecies_v1::PrivateKey<fastcrypto::groups::bls12381::G2Element>;