Skip to main content

sui_types/
multisig.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::{
5    crypto::{CompressedSignature, DefaultHash, SignatureScheme},
6    digests::ZKLoginInputsDigest,
7    error::SuiErrorKind,
8    passkey_authenticator::PasskeyAuthenticator,
9    signature::{AuthenticatorTrait, GenericSignature, VerifyParams},
10    signature_verification::VerifiedDigestCache,
11    zk_login_authenticator::ZkLoginAuthenticator,
12};
13pub use enum_dispatch::enum_dispatch;
14use fastcrypto::{
15    ed25519::Ed25519PublicKey,
16    encoding::{Base64, Encoding},
17    error::FastCryptoError,
18    hash::HashFunction,
19    secp256k1::Secp256k1PublicKey,
20    traits::{EncodeDecodeBase64, ToFromBytes, VerifyingKey},
21};
22use fastcrypto_pq::mldsa65::{MLDSA65PublicKey, MLDSA65Signature};
23use mysten_common::ZipDebugEqIteratorExt;
24use once_cell::sync::OnceCell;
25use schemars::JsonSchema;
26use serde::{Deserialize, Serialize};
27use serde_with::serde_as;
28use shared_crypto::intent::IntentMessage;
29use std::{
30    hash::{Hash, Hasher},
31    str::FromStr,
32    sync::Arc,
33};
34
35use crate::{
36    base_types::{EpochId, SuiAddress},
37    crypto::PublicKey,
38    error::SuiError,
39};
40
41#[cfg(test)]
42#[path = "unit_tests/multisig_tests.rs"]
43mod multisig_tests;
44
45pub type WeightUnit = u8;
46pub type ThresholdUnit = u16;
47pub type BitmapUnit = u16;
48pub const MAX_SIGNER_IN_MULTISIG: usize = 10;
49pub const MAX_BITMAP_VALUE: BitmapUnit = 0b1111111111;
50/// The struct that contains signatures and public keys necessary for authenticating a MultiSig.
51#[serde_as]
52#[derive(Debug, Serialize, Deserialize, Clone, JsonSchema)]
53pub struct MultiSig {
54    /// The plain signature encoded with signature scheme.
55    sigs: Vec<CompressedSignature>,
56    /// A bitmap that indicates the position of which public key the signature should be authenticated with.
57    bitmap: BitmapUnit,
58    /// The public key encoded with each public key with its signature scheme used along with the corresponding weight.
59    multisig_pk: MultiSigPublicKey,
60    /// A bytes representation of [struct MultiSig]. This helps with implementing [trait AsRef<[u8]>].
61    #[serde(skip)]
62    bytes: OnceCell<Vec<u8>>,
63}
64
65/// Necessary trait for [struct SenderSignedData].
66impl PartialEq for MultiSig {
67    fn eq(&self, other: &Self) -> bool {
68        self.sigs == other.sigs
69            && self.bitmap == other.bitmap
70            && self.multisig_pk == other.multisig_pk
71    }
72}
73
74/// Necessary trait for [struct SenderSignedData].
75impl Eq for MultiSig {}
76
77/// Necessary trait for [struct SenderSignedData].
78impl Hash for MultiSig {
79    fn hash<H: Hasher>(&self, state: &mut H) {
80        self.as_ref().hash(state);
81    }
82}
83
84impl AuthenticatorTrait for MultiSig {
85    fn verify_user_authenticator_epoch(
86        &self,
87        epoch_id: EpochId,
88        max_epoch_upper_bound_delta: Option<u64>,
89    ) -> Result<(), SuiError> {
90        // If there is any zkLogin signatures, filter and check epoch for each.
91        // TODO: call this on all sigs to avoid future lapses
92        self.get_zklogin_sigs()?.iter().try_for_each(|s| {
93            s.verify_user_authenticator_epoch(epoch_id, max_epoch_upper_bound_delta)
94        })
95    }
96
97    fn verify_claims<T>(
98        &self,
99        value: &IntentMessage<T>,
100        multisig_address: SuiAddress,
101        verify_params: &VerifyParams,
102        zklogin_inputs_cache: Arc<VerifiedDigestCache<ZKLoginInputsDigest>>,
103    ) -> Result<(), SuiError>
104    where
105        T: Serialize,
106    {
107        self.multisig_pk
108            .validate()
109            .map_err(|_| SuiErrorKind::InvalidSignature {
110                error: "Invalid multisig pubkey".to_string(),
111            })?;
112
113        // Additional validation on zkLogin public identifier struct if flag is enabled.
114        if verify_params.validate_zklogin_public_identifier {
115            for (pk, _weight) in &self.multisig_pk.pk_map {
116                if let PublicKey::ZkLogin(zklogin_pk) = pk {
117                    zklogin_pk
118                        .validate()
119                        .map_err(|e| SuiErrorKind::InvalidSignature {
120                            error: format!("Invalid zkLogin pk in multisig: {}", e),
121                        })?;
122                }
123            }
124        }
125
126        if SuiAddress::from(&self.multisig_pk) != multisig_address {
127            return Err(SuiErrorKind::InvalidSignature {
128                error: "Invalid address derived from pks".to_string(),
129            }
130            .into());
131        }
132
133        if self.has_zklogin_sigs() && !verify_params.accept_zklogin_in_multisig {
134            return Err(SuiErrorKind::InvalidSignature {
135                error: "zkLogin sig not supported inside multisig".to_string(),
136            }
137            .into());
138        }
139
140        if self.has_passkey_sigs() && !verify_params.accept_passkey_in_multisig {
141            return Err(SuiErrorKind::InvalidSignature {
142                error: "Passkey sig not supported inside multisig".to_string(),
143            }
144            .into());
145        }
146
147        // Gates membership, not just signing: an ML-DSA key in the committee
148        // is a BCS variant that older binaries cannot decode.
149        if self.multisig_pk.has_mldsa65_member() && !verify_params.accept_mldsa65_in_multisig {
150            return Err(SuiErrorKind::InvalidSignature {
151                error: "ML-DSA-65 member not supported inside multisig".to_string(),
152            }
153            .into());
154        }
155
156        let mut weight_sum: u16 = 0;
157        let mut hasher = DefaultHash::default();
158        bcs::serialize_into(&mut hasher, &value).expect("Message serialization should not fail");
159        let digest = hasher.finalize().digest;
160        // Verify each signature against its corresponding signature scheme and public key.
161        // TODO: further optimization can be done because multiple Ed25519 signatures can be batch verified.
162        for (sig, i) in self.sigs.iter().zip_debug_eq(as_indices(self.bitmap)?) {
163            let (subsig_pubkey, weight) =
164                self.multisig_pk
165                    .pk_map
166                    .get(i as usize)
167                    .ok_or(SuiErrorKind::InvalidSignature {
168                        error: "Invalid public keys index".to_string(),
169                    })?;
170            let res = match sig {
171                CompressedSignature::Ed25519(s) => {
172                    if verify_params.additional_multisig_checks
173                        && !matches!(subsig_pubkey.scheme(), SignatureScheme::ED25519)
174                    {
175                        return Err(SuiErrorKind::InvalidSignature {
176                            error: format!(
177                                "Invalid sig for pk={} address={:?} error=signature/pubkey type mismatch",
178                                subsig_pubkey.encode_base64(),
179                                SuiAddress::from(subsig_pubkey)
180                            ),
181                        }.into());
182                    }
183                    let pk =
184                        Ed25519PublicKey::from_bytes(subsig_pubkey.as_ref()).map_err(|_| {
185                            SuiErrorKind::InvalidSignature {
186                                error: "Invalid ed25519 pk bytes".to_string(),
187                            }
188                        })?;
189                    pk.verify(
190                        &digest,
191                        &s.try_into().map_err(|_| SuiErrorKind::InvalidSignature {
192                            error: "Invalid ed25519 signature bytes".to_string(),
193                        })?,
194                    )
195                }
196                CompressedSignature::Secp256k1(s) => {
197                    if verify_params.additional_multisig_checks
198                        && !matches!(subsig_pubkey.scheme(), SignatureScheme::Secp256k1)
199                    {
200                        return Err(SuiErrorKind::InvalidSignature {
201                            error: format!(
202                                "Invalid sig for pk={} address={:?} error=signature/pubkey type mismatch",
203                                subsig_pubkey.encode_base64(),
204                                SuiAddress::from(subsig_pubkey)
205                            ),
206                        }.into());
207                    }
208                    let pk =
209                        Secp256k1PublicKey::from_bytes(subsig_pubkey.as_ref()).map_err(|_| {
210                            SuiErrorKind::InvalidSignature {
211                                error: "Invalid k1 pk bytes".to_string(),
212                            }
213                        })?;
214                    pk.verify(
215                        &digest,
216                        &s.try_into().map_err(|_| SuiErrorKind::InvalidSignature {
217                            error: "Invalid k1 signature bytes".to_string(),
218                        })?,
219                    )
220                }
221                CompressedSignature::Secp256r1(s) => {
222                    if verify_params.additional_multisig_checks
223                        && !matches!(subsig_pubkey.scheme(), SignatureScheme::Secp256r1)
224                    {
225                        return Err(SuiErrorKind::InvalidSignature {
226                            error: format!(
227                                "Invalid sig for pk={} address={:?} error=signature/pubkey type mismatch",
228                                subsig_pubkey.encode_base64(),
229                                SuiAddress::from(subsig_pubkey)
230                            ),
231                        }.into());
232                    }
233                    let pk = verify_params
234                        .parse_secp256r1_public_key(subsig_pubkey.as_ref())
235                        .map_err(|_| SuiErrorKind::InvalidSignature {
236                            error: "Invalid r1 pk bytes".to_string(),
237                        })?;
238                    pk.verify(
239                        &digest,
240                        &s.try_into().map_err(|_| SuiErrorKind::InvalidSignature {
241                            error: "Invalid r1 signature bytes".to_string(),
242                        })?,
243                    )
244                }
245                CompressedSignature::MLDSA65(s) => {
246                    if verify_params.additional_multisig_checks
247                        && !matches!(subsig_pubkey.scheme(), SignatureScheme::MLDSA65)
248                    {
249                        return Err(SuiErrorKind::InvalidSignature {
250                            error: format!(
251                                "Invalid sig for pk={} address={:?} error=signature/pubkey type mismatch",
252                                subsig_pubkey.encode_base64(),
253                                SuiAddress::from(subsig_pubkey)
254                            ),
255                        }.into());
256                    }
257                    let pk =
258                        MLDSA65PublicKey::from_bytes(subsig_pubkey.as_ref()).map_err(|_| {
259                            SuiErrorKind::InvalidSignature {
260                                error: "Invalid mldsa65 pk bytes".to_string(),
261                            }
262                        })?;
263                    pk.verify(
264                        &digest,
265                        &MLDSA65Signature::from_bytes(&s.0).map_err(|_| {
266                            SuiErrorKind::InvalidSignature {
267                                error: "Invalid mldsa65 signature bytes".to_string(),
268                            }
269                        })?,
270                    )
271                }
272                CompressedSignature::ZkLogin(z) => {
273                    if verify_params.additional_multisig_checks
274                        && !matches!(
275                            subsig_pubkey.scheme(),
276                            SignatureScheme::ZkLoginAuthenticator
277                        )
278                    {
279                        return Err(SuiErrorKind::InvalidSignature {
280                            error: format!(
281                                "Invalid sig for pk={} address={:?} error=signature/pubkey type mismatch",
282                                subsig_pubkey.encode_base64(),
283                                SuiAddress::from(subsig_pubkey)
284                            ),
285                        }.into());
286                    }
287                    let authenticator = ZkLoginAuthenticator::from_bytes(&z.0).map_err(|_| {
288                        SuiErrorKind::InvalidSignature {
289                            error: "Invalid zklogin authenticator bytes".to_string(),
290                        }
291                    })?;
292                    authenticator
293                        .verify_claims(
294                            value,
295                            SuiAddress::from(subsig_pubkey),
296                            verify_params,
297                            zklogin_inputs_cache.clone(),
298                        )
299                        .map_err(|e| FastCryptoError::GeneralError(e.to_string()))
300                }
301                CompressedSignature::Passkey(bytes) => {
302                    let authenticator =
303                        PasskeyAuthenticator::from_bytes(&bytes.0).map_err(|_| {
304                            SuiErrorKind::InvalidSignature {
305                                error: "Invalid passkey authenticator bytes".to_string(),
306                            }
307                        })?;
308                    authenticator
309                        .verify_claims(
310                            value,
311                            SuiAddress::from(subsig_pubkey),
312                            verify_params,
313                            zklogin_inputs_cache.clone(),
314                        )
315                        .map_err(|e| FastCryptoError::GeneralError(e.to_string()))
316                }
317            };
318            if res.is_ok() {
319                weight_sum += *weight as u16;
320            } else {
321                return res.map_err(|e| {
322                    SuiErrorKind::InvalidSignature {
323                        error: format!(
324                            "Invalid sig for pk={} address={:?} error={:?}",
325                            subsig_pubkey.encode_base64(),
326                            SuiAddress::from(subsig_pubkey),
327                            e.to_string()
328                        ),
329                    }
330                    .into()
331                });
332            }
333        }
334        if weight_sum >= self.multisig_pk.threshold {
335            Ok(())
336        } else {
337            Err(SuiErrorKind::InvalidSignature {
338                error: format!(
339                    "Insufficient weight={:?} threshold={:?}",
340                    weight_sum, self.multisig_pk.threshold
341                ),
342            }
343            .into())
344        }
345    }
346}
347
348/// Interpret a bitmap of 01s as a list of indices that is set to 1s.
349/// e.g. 22 = 0b10110, then the result is [1, 2, 4].
350pub fn as_indices(bitmap: u16) -> Result<Vec<u8>, SuiError> {
351    if bitmap > MAX_BITMAP_VALUE {
352        return Err(SuiErrorKind::InvalidSignature {
353            error: "Invalid bitmap".to_string(),
354        }
355        .into());
356    }
357    let mut res = Vec::new();
358    for i in 0..10 {
359        if bitmap & (1 << i) != 0 {
360            res.push(i as u8);
361        }
362    }
363    Ok(res)
364}
365
366impl MultiSig {
367    /// Create MultiSig from its fields without validation
368    pub fn insecure_new(
369        sigs: Vec<CompressedSignature>,
370        bitmap: BitmapUnit,
371        multisig_pk: MultiSigPublicKey,
372    ) -> Self {
373        Self {
374            sigs,
375            bitmap,
376            multisig_pk,
377            bytes: OnceCell::new(),
378        }
379    }
380    /// This combines a list of [enum Signature] `flag || signature || pk` to a MultiSig.
381    /// `full_sigs` may come in any order. They are stored in the order of their public
382    /// keys in [enum MultiSigPublicKey], which is the order verification walks the bitmap in.
383    pub fn combine(
384        full_sigs: Vec<GenericSignature>,
385        multisig_pk: MultiSigPublicKey,
386    ) -> Result<Self, SuiError> {
387        multisig_pk
388            .validate()
389            .map_err(|_| SuiErrorKind::InvalidSignature {
390                error: "Invalid multisig public key".to_string(),
391            })?;
392
393        if full_sigs.len() > multisig_pk.pk_map.len() || full_sigs.is_empty() {
394            return Err(SuiErrorKind::InvalidSignature {
395                error: "Invalid number of signatures".to_string(),
396            }
397            .into());
398        }
399        let mut bitmap = 0;
400        let mut indexed_sigs = Vec::with_capacity(full_sigs.len());
401        for s in full_sigs {
402            let pk = s.to_public_key()?;
403            let index = multisig_pk
404                .get_index(&pk)
405                .ok_or(SuiErrorKind::IncorrectSigner {
406                    error: format!("pk does not exist: {:?}", pk),
407                })?;
408            if bitmap & (1 << index) != 0 {
409                return Err(SuiErrorKind::InvalidSignature {
410                    error: "Duplicate public key".to_string(),
411                }
412                .into());
413            }
414            bitmap |= 1 << index;
415            indexed_sigs.push((index, s.to_compressed()?));
416        }
417        indexed_sigs.sort_by_key(|(index, _)| *index);
418
419        Ok(MultiSig {
420            sigs: indexed_sigs.into_iter().map(|(_, sig)| sig).collect(),
421            bitmap,
422            multisig_pk,
423            bytes: OnceCell::new(),
424        })
425    }
426
427    pub fn init_and_validate(&mut self) -> Result<Self, FastCryptoError> {
428        if self.sigs.len() > self.multisig_pk.pk_map.len()
429            || self.sigs.is_empty()
430            || self.bitmap > MAX_BITMAP_VALUE
431        {
432            return Err(FastCryptoError::InvalidInput);
433        }
434        self.multisig_pk.validate()?;
435        Ok(self.to_owned())
436    }
437
438    pub fn get_pk(&self) -> &MultiSigPublicKey {
439        &self.multisig_pk
440    }
441
442    pub fn get_sigs(&self) -> &[CompressedSignature] {
443        &self.sigs
444    }
445
446    pub fn get_bitmap(&self) -> u16 {
447        self.bitmap
448    }
449
450    pub fn get_zklogin_sigs(&self) -> Result<Vec<ZkLoginAuthenticator>, SuiError> {
451        let authenticator_as_bytes: Vec<_> = self
452            .sigs
453            .iter()
454            .filter_map(|s| match s {
455                CompressedSignature::ZkLogin(z) => Some(z),
456                _ => None,
457            })
458            .collect();
459        authenticator_as_bytes
460            .iter()
461            .map(|z| {
462                ZkLoginAuthenticator::from_bytes(&z.0).map_err(|_| {
463                    SuiErrorKind::InvalidSignature {
464                        error: "Invalid zklogin authenticator bytes".to_string(),
465                    }
466                    .into()
467                })
468            })
469            .collect()
470    }
471
472    pub fn get_indices(&self) -> Result<Vec<u8>, SuiError> {
473        as_indices(self.bitmap)
474    }
475
476    pub fn has_passkey_sigs(&self) -> bool {
477        self.sigs
478            .iter()
479            .any(|s| matches!(s, CompressedSignature::Passkey(_)))
480    }
481
482    pub fn has_zklogin_sigs(&self) -> bool {
483        self.sigs
484            .iter()
485            .any(|s| matches!(s, CompressedSignature::ZkLogin(_)))
486    }
487
488    /// Whether any committee key or signature is ML-DSA-65.
489    pub fn uses_mldsa65(&self) -> bool {
490        self.multisig_pk.has_mldsa65_member()
491            || self
492                .sigs
493                .iter()
494                .any(|s| matches!(s, CompressedSignature::MLDSA65(_)))
495    }
496}
497
498impl ToFromBytes for MultiSig {
499    fn from_bytes(bytes: &[u8]) -> Result<MultiSig, FastCryptoError> {
500        // The first byte matches the flag of MultiSig.
501        if bytes.first().ok_or(FastCryptoError::InvalidInput)? != &SignatureScheme::MultiSig.flag()
502        {
503            return Err(FastCryptoError::InvalidInput);
504        }
505        let mut multisig: MultiSig =
506            bcs::from_bytes(&bytes[1..]).map_err(|_| FastCryptoError::InvalidSignature)?;
507        multisig.init_and_validate()
508    }
509}
510
511impl FromStr for MultiSig {
512    type Err = SuiError;
513
514    fn from_str(s: &str) -> Result<Self, Self::Err> {
515        let bytes = Base64::decode(s).map_err(|_| SuiErrorKind::InvalidSignature {
516            error: "Invalid base64 string".to_string(),
517        })?;
518        let sig = MultiSig::from_bytes(&bytes).map_err(|_| SuiErrorKind::InvalidSignature {
519            error: "Invalid multisig bytes".to_string(),
520        })?;
521        Ok(sig)
522    }
523}
524
525/// This initialize the underlying bytes representation of MultiSig. It encodes
526/// [struct MultiSig] as the MultiSig flag (0x03) concat with the bcs bytes
527/// of [struct MultiSig] i.e. `flag || bcs_bytes(MultiSig)`.
528impl AsRef<[u8]> for MultiSig {
529    fn as_ref(&self) -> &[u8] {
530        self.bytes
531            .get_or_try_init::<_, eyre::Report>(|| {
532                let as_bytes = bcs::to_bytes(self).expect("BCS serialization should not fail");
533                let mut bytes = Vec::with_capacity(1 + as_bytes.len());
534                bytes.push(SignatureScheme::MultiSig.flag());
535                bytes.extend_from_slice(as_bytes.as_slice());
536                Ok(bytes)
537            })
538            .expect("OnceCell invariant violated")
539    }
540}
541
542/// The struct that contains the public key used for authenticating a MultiSig.
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
544pub struct MultiSigPublicKey {
545    /// A list of public key and its corresponding weight.
546    pk_map: Vec<(PublicKey, WeightUnit)>,
547    /// If the total weight of the public keys corresponding to verified signatures is larger than threshold, the MultiSig is verified.
548    threshold: ThresholdUnit,
549}
550
551impl MultiSigPublicKey {
552    /// Construct MultiSigPublicKey without validation.
553    pub fn insecure_new(pk_map: Vec<(PublicKey, WeightUnit)>, threshold: ThresholdUnit) -> Self {
554        Self { pk_map, threshold }
555    }
556
557    pub fn new(
558        pks: Vec<PublicKey>,
559        weights: Vec<WeightUnit>,
560        threshold: ThresholdUnit,
561    ) -> Result<Self, SuiError> {
562        if pks.is_empty()
563            || weights.is_empty()
564            || threshold == 0
565            || pks.len() != weights.len()
566            || pks.len() > MAX_SIGNER_IN_MULTISIG
567            || weights.contains(&0)
568            || weights
569                .iter()
570                .map(|w| *w as ThresholdUnit)
571                .sum::<ThresholdUnit>()
572                < threshold
573            || pks
574                .iter()
575                .enumerate()
576                .any(|(i, pk)| pks.iter().skip(i + 1).any(|other_pk| *pk == *other_pk))
577        {
578            return Err(SuiErrorKind::InvalidSignature {
579                error: "Invalid multisig public key construction".to_string(),
580            }
581            .into());
582        }
583
584        Ok(MultiSigPublicKey {
585            pk_map: pks.into_iter().zip_debug_eq(weights).collect(),
586            threshold,
587        })
588    }
589
590    pub fn get_index(&self, pk: &PublicKey) -> Option<u8> {
591        self.pk_map.iter().position(|x| &x.0 == pk).map(|x| x as u8)
592    }
593
594    pub fn threshold(&self) -> &ThresholdUnit {
595        &self.threshold
596    }
597
598    pub fn pubkeys(&self) -> &Vec<(PublicKey, WeightUnit)> {
599        &self.pk_map
600    }
601
602    pub fn has_mldsa65_member(&self) -> bool {
603        self.pk_map
604            .iter()
605            .any(|(pk, _)| matches!(pk, PublicKey::MLDSA65(_)))
606    }
607
608    pub fn validate(&self) -> Result<MultiSigPublicKey, FastCryptoError> {
609        let pk_map = self.pubkeys();
610        if self.threshold == 0
611            || pk_map.is_empty()
612            || pk_map.len() > MAX_SIGNER_IN_MULTISIG
613            || pk_map.iter().any(|(_pk, weight)| *weight == 0)
614            || pk_map
615                .iter()
616                .map(|(_pk, weight)| *weight as ThresholdUnit)
617                .sum::<ThresholdUnit>()
618                < self.threshold
619            || pk_map.iter().enumerate().any(|(i, (pk, _weight))| {
620                pk_map
621                    .iter()
622                    .skip(i + 1)
623                    .any(|(other_pk, _weight)| *pk == *other_pk)
624            })
625        {
626            return Err(FastCryptoError::InvalidInput);
627        }
628        Ok(self.to_owned())
629    }
630}