Skip to main content

sui_types/
signature.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::committee::EpochId;
5use crate::crypto::{
6    CompressedSignature, PasskeyAuthenticatorAsBytes, PublicKey, SignatureScheme, SuiSignature,
7    ZkLoginAuthenticatorAsBytes,
8};
9use crate::digests::ZKLoginInputsDigest;
10use crate::error::{SuiError, SuiErrorKind};
11use crate::multisig_legacy::MultiSigLegacy;
12use crate::passkey_authenticator::PasskeyAuthenticator;
13use crate::signature_verification::VerifiedDigestCache;
14use crate::zk_login_authenticator::ZkLoginAuthenticator;
15use crate::{base_types::SuiAddress, crypto::Signature, error::SuiResult, multisig::MultiSig};
16pub use enum_dispatch::enum_dispatch;
17use fastcrypto::ed25519::{Ed25519PublicKey, Ed25519Signature};
18use fastcrypto::secp256k1::{Secp256k1PublicKey, Secp256k1Signature};
19use fastcrypto::secp256r1::{Secp256r1PublicKey, Secp256r1Signature};
20use fastcrypto::{
21    error::FastCryptoError,
22    traits::{EncodeDecodeBase64, ToFromBytes},
23};
24use fastcrypto_pq::mldsa65::{MLDSA65PublicKey, MLDSA65Signature};
25use fastcrypto_zkp::bn254::zk_login::{JWK, JwkId, OIDCProvider};
26use fastcrypto_zkp::bn254::zk_login_api::ZkLoginEnv;
27use imbl::hashmap::HashMap as ImHashMap;
28use schemars::JsonSchema;
29use serde::Serialize;
30use shared_crypto::intent::IntentMessage;
31use std::hash::Hash;
32use std::sync::Arc;
33#[derive(Default, Debug, Clone)]
34pub struct VerifyParams {
35    // map from JwkId (iss, kid) => JWK
36    pub oidc_provider_jwks: ImHashMap<JwkId, JWK>,
37    pub supported_providers: Vec<OIDCProvider>,
38    pub zk_login_env: ZkLoginEnv,
39    // zkLogin circuit verify mode: 0 = v1 circuit only, 1 = v2 circuit with
40    // fallback to v1, 2 = v2 circuit only.
41    pub zklogin_circuit_mode: u64,
42    pub verify_legacy_zklogin_address: bool,
43    pub accept_zklogin_in_multisig: bool,
44    pub accept_passkey_in_multisig: bool,
45    pub accept_mldsa65_in_multisig: bool,
46    pub zklogin_max_epoch_upper_bound_delta: Option<u64>,
47    pub additional_multisig_checks: bool,
48    pub validate_zklogin_public_identifier: bool,
49    pub secp256r1_strict_public_keys: bool,
50}
51
52impl VerifyParams {
53    pub fn new(
54        oidc_provider_jwks: ImHashMap<JwkId, JWK>,
55        supported_providers: Vec<OIDCProvider>,
56        zk_login_env: ZkLoginEnv,
57        zklogin_circuit_mode: u64,
58        verify_legacy_zklogin_address: bool,
59        accept_zklogin_in_multisig: bool,
60        accept_passkey_in_multisig: bool,
61        zklogin_max_epoch_upper_bound_delta: Option<u64>,
62        additional_multisig_checks: bool,
63        validate_zklogin_public_identifier: bool,
64    ) -> Self {
65        Self {
66            oidc_provider_jwks,
67            supported_providers,
68            zk_login_env,
69            zklogin_circuit_mode,
70            verify_legacy_zklogin_address,
71            accept_zklogin_in_multisig,
72            accept_passkey_in_multisig,
73            accept_mldsa65_in_multisig: false,
74            zklogin_max_epoch_upper_bound_delta,
75            additional_multisig_checks,
76            validate_zklogin_public_identifier,
77            secp256r1_strict_public_keys: false,
78        }
79    }
80
81    /// Whether ML-DSA-65 signatures are accepted, standalone or as a multisig
82    /// member. Off by default: only the validator path turns it on, from the
83    /// `mldsa65_auth` protocol flag, so client-side verifiers match validators
84    /// until the scheme is enabled.
85    pub fn with_mldsa65_in_multisig(mut self, accept: bool) -> Self {
86        self.accept_mldsa65_in_multisig = accept;
87        self
88    }
89
90    /// Whether secp256r1 public keys in the SEC1 compact encoding are rejected. Set from the
91    /// `secp256r1_strict_public_keys` protocol flag.
92    pub fn with_secp256r1_strict_public_keys(mut self, strict: bool) -> Self {
93        self.secp256r1_strict_public_keys = strict;
94        self
95    }
96
97    /// Parse a secp256r1 public key, rejecting the SEC1 compact encoding if
98    /// `secp256r1_strict_public_keys` is set.
99    pub(crate) fn parse_secp256r1_public_key(
100        &self,
101        bytes: &[u8],
102    ) -> Result<Secp256r1PublicKey, FastCryptoError> {
103        if self.secp256r1_strict_public_keys {
104            Secp256r1PublicKey::from_bytes_strict(bytes)
105        } else {
106            Secp256r1PublicKey::from_bytes(bytes)
107        }
108    }
109
110    /// If `secp256r1_strict_public_keys` is set, reject `pk` if it was parsed from the SEC1 compact
111    /// encoding.
112    pub(crate) fn reject_compact_secp256r1_key(&self, pk: &Secp256r1PublicKey) -> SuiResult {
113        self.reject_compact_secp256r1_key_bytes(pk.as_ref())
114    }
115
116    /// If `secp256r1_strict_public_keys` is set, reject `signature` if it is a secp256r1 signature
117    /// whose public key is in the SEC1 compact encoding.
118    pub(crate) fn reject_compact_signature_key(&self, signature: &Signature) -> SuiResult {
119        if signature.scheme() == SignatureScheme::Secp256r1 {
120            self.reject_compact_secp256r1_key_bytes(signature.public_key_bytes())?;
121        }
122        Ok(())
123    }
124
125    /// This function does the same check as [Self::reject_compact_secp256r1_key] on bytes that the
126    /// caller knows to be a secp256r1 public key. It does not parse the bytes.
127    fn reject_compact_secp256r1_key_bytes(&self, bytes: &[u8]) -> SuiResult {
128        if self.secp256r1_strict_public_keys && is_compact_encoding(bytes) {
129            return Err(SuiErrorKind::InvalidSignature {
130                error: "secp256r1 public key in the SEC1 compact encoding".to_string(),
131            }
132            .into());
133        }
134        Ok(())
135    }
136}
137
138fn is_compact_encoding(bytes: &[u8]) -> bool {
139    const SEC1_COMPACT_TAG: u8 = 0x05;
140    bytes.first() == Some(&SEC1_COMPACT_TAG)
141}
142
143/// A lightweight trait that all members of [enum GenericSignature] implement.
144#[enum_dispatch]
145pub trait AuthenticatorTrait {
146    fn verify_user_authenticator_epoch(
147        &self,
148        epoch: EpochId,
149        max_epoch_upper_bound_delta: Option<u64>,
150    ) -> SuiResult;
151
152    fn verify_claims<T>(
153        &self,
154        value: &IntentMessage<T>,
155        author: SuiAddress,
156        aux_verify_data: &VerifyParams,
157        zklogin_inputs_cache: Arc<VerifiedDigestCache<ZKLoginInputsDigest>>,
158    ) -> SuiResult
159    where
160        T: Serialize;
161}
162
163/// Due to the incompatibility of [enum Signature] (which dispatches a trait that
164/// assumes signature and pubkey bytes for verification), here we add a wrapper
165/// enum where member can just implement a lightweight [trait AuthenticatorTrait].
166/// This way MultiSig (and future Authenticators) can implement its own `verify`.
167#[enum_dispatch(AuthenticatorTrait)]
168#[derive(Debug, Clone, PartialEq, Eq, JsonSchema, Hash)]
169pub enum GenericSignature {
170    MultiSig,
171    MultiSigLegacy,
172    Signature,
173    ZkLoginAuthenticator,
174    PasskeyAuthenticator,
175}
176
177impl GenericSignature {
178    pub fn is_zklogin(&self) -> bool {
179        matches!(self, GenericSignature::ZkLoginAuthenticator(_))
180    }
181    pub fn is_passkey(&self) -> bool {
182        matches!(self, GenericSignature::PasskeyAuthenticator(_))
183    }
184
185    pub fn is_mldsa65(&self) -> bool {
186        matches!(self, GenericSignature::Signature(s) if s.scheme() == SignatureScheme::MLDSA65)
187    }
188
189    pub fn is_upgraded_multisig(&self) -> bool {
190        matches!(self, GenericSignature::MultiSig(_))
191    }
192
193    pub fn verify_authenticator<T>(
194        &self,
195        value: &IntentMessage<T>,
196        author: SuiAddress,
197        epoch: EpochId,
198        verify_params: &VerifyParams,
199        zklogin_inputs_cache: Arc<VerifiedDigestCache<ZKLoginInputsDigest>>,
200    ) -> SuiResult
201    where
202        T: Serialize,
203    {
204        self.verify_user_authenticator_epoch(
205            epoch,
206            verify_params.zklogin_max_epoch_upper_bound_delta,
207        )?;
208        self.verify_claims(value, author, verify_params, zklogin_inputs_cache)
209    }
210
211    /// Parse [enum CompressedSignature] from trait SuiSignature `flag || sig || pk`.
212    /// This is useful for the MultiSig to combine partial signature into a MultiSig public key.
213    pub fn to_compressed(&self) -> Result<CompressedSignature, SuiError> {
214        match self {
215            GenericSignature::Signature(s) => {
216                let bytes = s.signature_bytes();
217                match s.scheme() {
218                    SignatureScheme::ED25519 => Ok(CompressedSignature::Ed25519(
219                        (&Ed25519Signature::from_bytes(bytes).map_err(|_| {
220                            SuiErrorKind::InvalidSignature {
221                                error: "Cannot parse ed25519 sig".to_string(),
222                            }
223                        })?)
224                            .into(),
225                    )),
226                    SignatureScheme::Secp256k1 => Ok(CompressedSignature::Secp256k1(
227                        (&Secp256k1Signature::from_bytes(bytes).map_err(|_| {
228                            SuiErrorKind::InvalidSignature {
229                                error: "Cannot parse secp256k1 sig".to_string(),
230                            }
231                        })?)
232                            .into(),
233                    )),
234                    SignatureScheme::MLDSA65 => Ok(CompressedSignature::MLDSA65(Box::new(
235                        (&MLDSA65Signature::from_bytes(bytes).map_err(|_| {
236                            SuiErrorKind::InvalidSignature {
237                                error: "Cannot parse mldsa65 sig".to_string(),
238                            }
239                        })?)
240                            .into(),
241                    ))),
242                    SignatureScheme::Secp256r1 | SignatureScheme::PasskeyAuthenticator => {
243                        Ok(CompressedSignature::Secp256r1(
244                            (&Secp256r1Signature::from_bytes(bytes).map_err(|_| {
245                                SuiErrorKind::InvalidSignature {
246                                    error: "Cannot parse secp256r1 sig".to_string(),
247                                }
248                            })?)
249                                .into(),
250                        ))
251                    }
252
253                    _ => Err(SuiErrorKind::UnsupportedFeatureError {
254                        error: "Unsupported signature scheme".to_string(),
255                    }
256                    .into()),
257                }
258            }
259            GenericSignature::ZkLoginAuthenticator(s) => Ok(CompressedSignature::ZkLogin(
260                ZkLoginAuthenticatorAsBytes(s.as_ref().to_vec()),
261            )),
262            GenericSignature::PasskeyAuthenticator(s) => Ok(CompressedSignature::Passkey(
263                PasskeyAuthenticatorAsBytes(s.as_ref().to_vec()),
264            )),
265            _ => Err(SuiErrorKind::UnsupportedFeatureError {
266                error: "Unsupported signature scheme".to_string(),
267            }
268            .into()),
269        }
270    }
271
272    /// Parse [struct PublicKey] from trait SuiSignature `flag || sig || pk`.
273    /// This is useful for the MultiSig to construct the bitmap in [struct MultiPublicKey].
274    pub fn to_public_key(&self) -> Result<PublicKey, SuiError> {
275        match self {
276            GenericSignature::Signature(s) => {
277                let bytes = s.public_key_bytes();
278                match s.scheme() {
279                    SignatureScheme::ED25519 => Ok(PublicKey::Ed25519(
280                        (&Ed25519PublicKey::from_bytes(bytes).map_err(|_| {
281                            SuiErrorKind::KeyConversionError("Cannot parse ed25519 pk".to_string())
282                        })?)
283                            .into(),
284                    )),
285                    SignatureScheme::Secp256k1 => Ok(PublicKey::Secp256k1(
286                        (&Secp256k1PublicKey::from_bytes(bytes).map_err(|_| {
287                            SuiErrorKind::KeyConversionError(
288                                "Cannot parse secp256k1 pk".to_string(),
289                            )
290                        })?)
291                            .into(),
292                    )),
293                    SignatureScheme::MLDSA65 => Ok(PublicKey::MLDSA65(Box::new(
294                        (&MLDSA65PublicKey::from_bytes(bytes).map_err(|_| {
295                            SuiErrorKind::KeyConversionError("Cannot parse mldsa65 pk".to_string())
296                        })?)
297                            .into(),
298                    ))),
299                    SignatureScheme::Secp256r1 => Ok(PublicKey::Secp256r1(
300                        (&Secp256r1PublicKey::from_bytes(bytes).map_err(|_| {
301                            SuiErrorKind::KeyConversionError(
302                                "Cannot parse secp256r1 pk".to_string(),
303                            )
304                        })?)
305                            .into(),
306                    )),
307                    _ => Err(SuiErrorKind::UnsupportedFeatureError {
308                        error: "Unsupported signature scheme in MultiSig".to_string(),
309                    }
310                    .into()),
311                }
312            }
313            GenericSignature::ZkLoginAuthenticator(s) => s.get_pk(),
314            GenericSignature::PasskeyAuthenticator(s) => s.get_pk(),
315            _ => Err(SuiErrorKind::UnsupportedFeatureError {
316                error: "Unsupported signature scheme".to_string(),
317            }
318            .into()),
319        }
320    }
321}
322
323/// GenericSignature encodes a single signature [enum Signature] as is `flag || signature || pubkey`.
324/// It encodes [struct MultiSigLegacy] as the MultiSig flag (0x03) concat with the bcs serializedbytes
325/// of [struct MultiSigLegacy] i.e. `flag || bcs_bytes(MultiSigLegacy)`.
326/// [struct Multisig] is encodede as the MultiSig flag (0x03) concat with the bcs serializedbytes
327/// of [struct Multisig] i.e. `flag || bcs_bytes(Multisig)`.
328impl ToFromBytes for GenericSignature {
329    fn from_bytes(bytes: &[u8]) -> Result<Self, FastCryptoError> {
330        match SignatureScheme::from_flag_byte(
331            bytes.first().ok_or(FastCryptoError::InputTooShort(0))?,
332        ) {
333            Ok(x) => match x {
334                SignatureScheme::ED25519
335                | SignatureScheme::Secp256k1
336                | SignatureScheme::Secp256r1
337                | SignatureScheme::MLDSA65 => Ok(GenericSignature::Signature(
338                    Signature::from_bytes(bytes).map_err(|_| FastCryptoError::InvalidSignature)?,
339                )),
340                SignatureScheme::MultiSig => match MultiSig::from_bytes(bytes) {
341                    Ok(multisig) => Ok(GenericSignature::MultiSig(multisig)),
342                    Err(_) => {
343                        let multisig = MultiSigLegacy::from_bytes(bytes)?;
344                        Ok(GenericSignature::MultiSigLegacy(multisig))
345                    }
346                },
347                SignatureScheme::ZkLoginAuthenticator => {
348                    let zk_login = ZkLoginAuthenticator::from_bytes(bytes)?;
349                    Ok(GenericSignature::ZkLoginAuthenticator(zk_login))
350                }
351                SignatureScheme::PasskeyAuthenticator => {
352                    let passkey = PasskeyAuthenticator::from_bytes(bytes)?;
353                    Ok(GenericSignature::PasskeyAuthenticator(passkey))
354                }
355                _ => Err(FastCryptoError::InvalidInput),
356            },
357            Err(_) => Err(FastCryptoError::InvalidInput),
358        }
359    }
360}
361
362/// Trait useful to get the bytes reference for [enum GenericSignature].
363impl AsRef<[u8]> for GenericSignature {
364    fn as_ref(&self) -> &[u8] {
365        match self {
366            GenericSignature::MultiSig(s) => s.as_ref(),
367            GenericSignature::MultiSigLegacy(s) => s.as_ref(),
368            GenericSignature::Signature(s) => s.as_ref(),
369            GenericSignature::ZkLoginAuthenticator(s) => s.as_ref(),
370            GenericSignature::PasskeyAuthenticator(s) => s.as_ref(),
371        }
372    }
373}
374
375impl ::serde::Serialize for GenericSignature {
376    fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
377        if serializer.is_human_readable() {
378            #[derive(serde::Serialize)]
379            struct GenericSignature(String);
380            GenericSignature(self.encode_base64()).serialize(serializer)
381        } else {
382            #[derive(serde::Serialize)]
383            struct GenericSignature<'a>(&'a [u8]);
384            GenericSignature(self.as_ref()).serialize(serializer)
385        }
386    }
387}
388
389impl<'de> ::serde::Deserialize<'de> for GenericSignature {
390    fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
391        use serde::de::Error;
392
393        if deserializer.is_human_readable() {
394            #[derive(serde::Deserialize)]
395            struct GenericSignature(String);
396            let s = GenericSignature::deserialize(deserializer)?;
397            Self::decode_base64(&s.0).map_err(::serde::de::Error::custom)
398        } else {
399            #[derive(serde::Deserialize)]
400            struct GenericSignature(Vec<u8>);
401
402            let data = GenericSignature::deserialize(deserializer)?;
403            Self::from_bytes(&data.0).map_err(|e| Error::custom(e.to_string()))
404        }
405    }
406}
407
408/// This ports the wrapper trait to the verify_secure defined on [enum Signature].
409impl AuthenticatorTrait for Signature {
410    fn verify_user_authenticator_epoch(&self, _: EpochId, _: Option<EpochId>) -> SuiResult {
411        Ok(())
412    }
413
414    fn verify_claims<T>(
415        &self,
416        value: &IntentMessage<T>,
417        author: SuiAddress,
418        verify_params: &VerifyParams,
419        _zklogin_inputs_cache: Arc<VerifiedDigestCache<ZKLoginInputsDigest>>,
420    ) -> SuiResult
421    where
422        T: Serialize,
423    {
424        // Same gate as the multisig member check, so the ML-DSA verifier never runs on a
425        // network that has not enabled the scheme. Fullnodes verify before `validity_check`.
426        if self.scheme() == SignatureScheme::MLDSA65 && !verify_params.accept_mldsa65_in_multisig {
427            return Err(SuiErrorKind::InvalidSignature {
428                error: "ML-DSA-65 signatures not supported".to_string(),
429            }
430            .into());
431        }
432        verify_params.reject_compact_signature_key(self)?;
433        self.verify_secure(value, author, self.scheme())
434    }
435}