alloy_consensus/
crypto.rs

1//! Cryptographic algorithms
2
3use alloc::boxed::Box;
4use alloy_primitives::U256;
5
6#[cfg(any(feature = "secp256k1", feature = "k256"))]
7use alloy_primitives::Signature;
8
9#[cfg(feature = "crypto-backend")]
10pub use backend::{install_default_provider, CryptoProvider, CryptoProviderAlreadySetError};
11
12/// Error for signature S.
13#[derive(Debug, thiserror::Error)]
14#[error("signature S value is greater than `secp256k1n / 2`")]
15pub struct InvalidSignatureS;
16
17/// Opaque error type for sender recovery.
18#[derive(Debug, Default, thiserror::Error)]
19#[error("Failed to recover the signer")]
20pub struct RecoveryError {
21    #[source]
22    source: Option<Box<dyn core::error::Error + Send + Sync + 'static>>,
23}
24
25impl RecoveryError {
26    /// Create a new error with no associated source
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// Create a new error with an associated source.
32    ///
33    /// **NOTE:** The "source" should **NOT** be used to propagate cryptographic
34    /// errors e.g. signature parsing or verification errors.
35    pub fn from_source<E: core::error::Error + Send + Sync + 'static>(err: E) -> Self {
36        Self { source: Some(Box::new(err)) }
37    }
38}
39
40impl From<alloy_primitives::SignatureError> for RecoveryError {
41    fn from(err: alloy_primitives::SignatureError) -> Self {
42        Self::from_source(err)
43    }
44}
45
46/// The order of the secp256k1 curve, divided by two. Signatures that should be checked according
47/// to EIP-2 should have an S value less than or equal to this.
48///
49/// `57896044618658097711785492504343953926418782139537452191302581570759080747168`
50pub const SECP256K1N_HALF: U256 = U256::from_be_bytes([
51    0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
52    0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D, 0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0,
53]);
54
55/// Crypto backend module for pluggable cryptographic implementations.
56#[cfg(feature = "crypto-backend")]
57pub mod backend {
58    use super::*;
59    use alloc::sync::Arc;
60    use alloy_primitives::Address;
61
62    #[cfg(feature = "std")]
63    use std::sync::OnceLock;
64
65    #[cfg(not(feature = "std"))]
66    use once_cell::race::OnceBox;
67
68    /// Trait for cryptographic providers that can perform signature recovery.
69    ///
70    /// This trait allows pluggable cryptographic backends for Ethereum signature recovery.
71    /// By default, alloy uses compile-time selected implementations (secp256k1 or k256),
72    /// but applications can install a custom provider to override this behavior.
73    ///
74    /// # Why is this needed?
75    ///
76    /// The primary reason is performance - when targeting special execution environments
77    /// that require custom cryptographic logic. For example, zkVMs (zero-knowledge virtual
78    /// machines) may have special accelerators that would allow them to perform signature
79    /// recovery faster.
80    ///
81    /// # Usage
82    ///
83    /// 1. Enable the `crypto-backend` feature in your `Cargo.toml`
84    /// 2. Implement the `CryptoProvider` trait for your custom backend
85    /// 3. Install it globally using [`install_default_provider`]
86    /// 4. All subsequent signature recovery operations will use your provider
87    ///
88    /// Note: This trait currently only provides signature recovery functionality,
89    /// not signature creation. For signature creation, use the compile-time selected
90    /// implementations in the [`secp256k1`] module.
91    ///
92    /// ```rust,ignore
93    /// use alloy_consensus::crypto::backend::{CryptoProvider, install_default_provider};
94    /// use alloy_primitives::Address;
95    /// use alloc::sync::Arc;
96    ///
97    /// struct MyCustomProvider;
98    ///
99    /// impl CryptoProvider for MyCustomProvider {
100    ///     fn recover_signer_unchecked(
101    ///         &self,
102    ///         sig: &[u8; 65],
103    ///         msg: &[u8; 32],
104    ///     ) -> Result<Address, RecoveryError> {
105    ///         // Your custom implementation here
106    ///         todo!()
107    ///     }
108    /// }
109    ///
110    /// // Install your provider globally
111    /// install_default_provider(Arc::new(MyCustomProvider)).unwrap();
112    /// ```
113    pub trait CryptoProvider: Send + Sync + 'static {
114        /// Recover signer from signature and message hash, without ensuring low S values.
115        fn recover_signer_unchecked(
116            &self,
117            sig: &[u8; 65],
118            msg: &[u8; 32],
119        ) -> Result<Address, RecoveryError>;
120    }
121
122    /// Global default crypto provider.
123    #[cfg(feature = "std")]
124    static DEFAULT_PROVIDER: OnceLock<Arc<dyn CryptoProvider>> = OnceLock::new();
125
126    #[cfg(not(feature = "std"))]
127    static DEFAULT_PROVIDER: OnceBox<Arc<dyn CryptoProvider>> = OnceBox::new();
128
129    /// Error returned when attempting to install a provider when one is already installed.
130    /// Contains the provider that was attempted to be installed.
131    pub struct CryptoProviderAlreadySetError {
132        /// The provider that was attempted to be installed.
133        pub provider: Arc<dyn CryptoProvider>,
134    }
135
136    impl core::fmt::Debug for CryptoProviderAlreadySetError {
137        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
138            f.debug_struct("CryptoProviderAlreadySetError")
139                .field("provider", &"<crypto provider>")
140                .finish()
141        }
142    }
143
144    impl core::fmt::Display for CryptoProviderAlreadySetError {
145        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
146            write!(f, "crypto provider already installed")
147        }
148    }
149
150    impl core::error::Error for CryptoProviderAlreadySetError {}
151
152    /// Install the default crypto provider.
153    ///
154    /// This sets the global default provider used by the high-level crypto functions.
155    /// Returns an error containing the provider that was attempted to be installed if one is
156    /// already set.
157    pub fn install_default_provider(
158        provider: Arc<dyn CryptoProvider>,
159    ) -> Result<(), CryptoProviderAlreadySetError> {
160        #[cfg(feature = "std")]
161        {
162            DEFAULT_PROVIDER.set(provider).map_err(|provider| {
163                // Return the provider we tried to install in the error
164                CryptoProviderAlreadySetError { provider }
165            })
166        }
167        #[cfg(not(feature = "std"))]
168        {
169            DEFAULT_PROVIDER.set(Box::new(provider)).map_err(|provider| {
170                // Return the provider we tried to install in the error
171                CryptoProviderAlreadySetError { provider: *provider }
172            })
173        }
174    }
175
176    /// Get the currently installed default provider, panicking if none is installed.
177    pub fn get_default_provider() -> &'static dyn CryptoProvider {
178        try_get_provider().unwrap_or_else(|| {
179            panic!("No crypto backend installed. Call install_default_provider() first.")
180        })
181    }
182
183    /// Try to get the currently installed default provider, returning None if none is installed.
184    pub(super) fn try_get_provider() -> Option<&'static dyn CryptoProvider> {
185        DEFAULT_PROVIDER.get().map(|arc| arc.as_ref())
186    }
187}
188
189/// Secp256k1 cryptographic functions.
190#[cfg(any(feature = "secp256k1", feature = "k256"))]
191pub mod secp256k1 {
192    pub use imp::{public_key_to_address, sign_message};
193
194    use super::*;
195    use alloy_primitives::{Address, B256};
196
197    #[cfg(not(feature = "secp256k1"))]
198    use super::impl_k256 as imp;
199    #[cfg(feature = "secp256k1")]
200    use super::impl_secp256k1 as imp;
201
202    /// Recover signer from message hash, _without ensuring that the signature has a low `s`
203    /// value_.
204    ///
205    /// Using this for signature validation will succeed, even if the signature is malleable or not
206    /// compliant with EIP-2. This is provided for compatibility with old signatures which have
207    /// large `s` values.
208    pub fn recover_signer_unchecked(
209        signature: &Signature,
210        hash: B256,
211    ) -> Result<Address, RecoveryError> {
212        let mut sig: [u8; 65] = [0; 65];
213
214        sig[0..32].copy_from_slice(&signature.r().to_be_bytes::<32>());
215        sig[32..64].copy_from_slice(&signature.s().to_be_bytes::<32>());
216        sig[64] = signature.v() as u8;
217
218        // Try dynamic backend first when crypto-backend feature is enabled
219        #[cfg(feature = "crypto-backend")]
220        if let Some(provider) = super::backend::try_get_provider() {
221            return provider.recover_signer_unchecked(&sig, &hash.0);
222        }
223
224        // Fallback to compile-time selected implementation
225        // NOTE: we are removing error from underlying crypto library as it will restrain primitive
226        // errors and we care only if recovery is passing or not.
227        imp::recover_signer_unchecked(&sig, &hash.0).map_err(|_| RecoveryError::new())
228    }
229
230    /// Recover signer address from message hash. This ensures that the signature S value is
231    /// lower than `secp256k1n / 2`, as specified in
232    /// [EIP-2](https://eips.ethereum.org/EIPS/eip-2).
233    ///
234    /// If the S value is too large, then this will return a `RecoveryError`
235    pub fn recover_signer(signature: &Signature, hash: B256) -> Result<Address, RecoveryError> {
236        if signature.s() > SECP256K1N_HALF {
237            return Err(RecoveryError::from_source(InvalidSignatureS));
238        }
239        recover_signer_unchecked(signature, hash)
240    }
241}
242
243#[cfg(feature = "secp256k1")]
244mod impl_secp256k1 {
245    pub(crate) use ::secp256k1::Error;
246    use ::secp256k1::{
247        ecdsa::{RecoverableSignature, RecoveryId},
248        Message, PublicKey, SecretKey, SECP256K1,
249    };
250    use alloy_primitives::{keccak256, Address, Signature, B256, U256};
251
252    /// Recovers the address of the sender using secp256k1 pubkey recovery.
253    ///
254    /// Converts the public key into an ethereum address by hashing the public key with keccak256.
255    ///
256    /// This does not ensure that the `s` value in the signature is low, and _just_ wraps the
257    /// underlying secp256k1 library.
258    pub(crate) fn recover_signer_unchecked(
259        sig: &[u8; 65],
260        msg: &[u8; 32],
261    ) -> Result<Address, Error> {
262        let sig =
263            RecoverableSignature::from_compact(&sig[0..64], RecoveryId::try_from(sig[64] as i32)?)?;
264
265        let public = SECP256K1.recover_ecdsa(&Message::from_digest(*msg), &sig)?;
266        Ok(public_key_to_address(public))
267    }
268
269    /// Signs message with the given secret key.
270    /// Returns the corresponding signature.
271    pub fn sign_message(secret: B256, message: B256) -> Result<Signature, Error> {
272        let sec = SecretKey::from_slice(secret.as_ref())?;
273        let s = SECP256K1.sign_ecdsa_recoverable(&Message::from_digest(message.0), &sec);
274        let (rec_id, data) = s.serialize_compact();
275
276        let signature = Signature::new(
277            U256::try_from_be_slice(&data[..32]).expect("The slice has at most 32 bytes"),
278            U256::try_from_be_slice(&data[32..64]).expect("The slice has at most 32 bytes"),
279            i32::from(rec_id) != 0,
280        );
281        Ok(signature)
282    }
283
284    /// Converts a public key into an ethereum address by hashing the encoded public key with
285    /// keccak256.
286    pub fn public_key_to_address(public: PublicKey) -> Address {
287        // strip out the first byte because that should be the SECP256K1_TAG_PUBKEY_UNCOMPRESSED
288        // tag returned by libsecp's uncompressed pubkey serialization
289        let hash = keccak256(&public.serialize_uncompressed()[1..]);
290        Address::from_slice(&hash[12..])
291    }
292}
293
294#[cfg(feature = "k256")]
295#[cfg_attr(feature = "secp256k1", allow(unused, unreachable_pub))]
296mod impl_k256 {
297    pub(crate) use k256::ecdsa::Error;
298
299    use super::*;
300    use alloy_primitives::{keccak256, Address, B256};
301    use k256::ecdsa::{RecoveryId, SigningKey, VerifyingKey};
302
303    /// Recovers the address of the sender using secp256k1 pubkey recovery.
304    ///
305    /// Converts the public key into an ethereum address by hashing the public key with keccak256.
306    ///
307    /// This does not ensure that the `s` value in the signature is low, and _just_ wraps the
308    /// underlying secp256k1 library.
309    pub(crate) fn recover_signer_unchecked(
310        sig: &[u8; 65],
311        msg: &[u8; 32],
312    ) -> Result<Address, Error> {
313        let mut signature = k256::ecdsa::Signature::from_slice(&sig[0..64])?;
314        let mut recid = sig[64];
315
316        // normalize signature and flip recovery id if needed.
317        if let Some(sig_normalized) = signature.normalize_s() {
318            signature = sig_normalized;
319            recid ^= 1;
320        }
321        let recid = RecoveryId::from_byte(recid).expect("recovery ID is valid");
322
323        // recover key
324        let recovered_key = VerifyingKey::recover_from_prehash(&msg[..], &signature, recid)?;
325        Ok(public_key_to_address(recovered_key))
326    }
327
328    /// Signs message with the given secret key.
329    /// Returns the corresponding signature.
330    pub fn sign_message(secret: B256, message: B256) -> Result<Signature, Error> {
331        let sec = SigningKey::from_slice(secret.as_ref())?;
332        sec.sign_prehash_recoverable(&message.0).map(Into::into)
333    }
334
335    /// Converts a public key into an ethereum address by hashing the encoded public key with
336    /// keccak256.
337    pub fn public_key_to_address(public: VerifyingKey) -> Address {
338        let hash = keccak256(&public.to_encoded_point(/* compress = */ false).as_bytes()[1..]);
339        Address::from_slice(&hash[12..])
340    }
341}
342
343#[cfg(test)]
344mod tests {
345
346    #[cfg(feature = "secp256k1")]
347    #[test]
348    fn sanity_ecrecover_call_secp256k1() {
349        use super::impl_secp256k1::*;
350        use alloy_primitives::B256;
351
352        let (secret, public) = secp256k1::generate_keypair(&mut rand::thread_rng());
353        let signer = public_key_to_address(public);
354
355        let message = b"hello world";
356        let hash = alloy_primitives::keccak256(message);
357        let signature =
358            sign_message(B256::from_slice(&secret.secret_bytes()[..]), hash).expect("sign message");
359
360        let mut sig: [u8; 65] = [0; 65];
361        sig[0..32].copy_from_slice(&signature.r().to_be_bytes::<32>());
362        sig[32..64].copy_from_slice(&signature.s().to_be_bytes::<32>());
363        sig[64] = signature.v() as u8;
364
365        assert_eq!(recover_signer_unchecked(&sig, &hash), Ok(signer));
366    }
367
368    #[cfg(feature = "k256")]
369    #[test]
370    fn sanity_ecrecover_call_k256() {
371        use super::impl_k256::*;
372        use alloy_primitives::B256;
373
374        let secret = k256::ecdsa::SigningKey::random(&mut rand::thread_rng());
375        let public = *secret.verifying_key();
376        let signer = public_key_to_address(public);
377
378        let message = b"hello world";
379        let hash = alloy_primitives::keccak256(message);
380        let signature =
381            sign_message(B256::from_slice(&secret.to_bytes()[..]), hash).expect("sign message");
382
383        let mut sig: [u8; 65] = [0; 65];
384        sig[0..32].copy_from_slice(&signature.r().to_be_bytes::<32>());
385        sig[32..64].copy_from_slice(&signature.s().to_be_bytes::<32>());
386        sig[64] = signature.v() as u8;
387
388        assert_eq!(recover_signer_unchecked(&sig, &hash).ok(), Some(signer));
389    }
390
391    #[test]
392    #[cfg(all(feature = "secp256k1", feature = "k256"))]
393    fn sanity_secp256k1_k256_compat() {
394        use super::{impl_k256, impl_secp256k1};
395        use alloy_primitives::B256;
396
397        let (secp256k1_secret, secp256k1_public) =
398            secp256k1::generate_keypair(&mut rand::thread_rng());
399        let k256_secret = k256::ecdsa::SigningKey::from_slice(&secp256k1_secret.secret_bytes())
400            .expect("k256 secret");
401        let k256_public = *k256_secret.verifying_key();
402
403        let secp256k1_signer = impl_secp256k1::public_key_to_address(secp256k1_public);
404        let k256_signer = impl_k256::public_key_to_address(k256_public);
405        assert_eq!(secp256k1_signer, k256_signer);
406
407        let message = b"hello world";
408        let hash = alloy_primitives::keccak256(message);
409
410        let secp256k1_signature = impl_secp256k1::sign_message(
411            B256::from_slice(&secp256k1_secret.secret_bytes()[..]),
412            hash,
413        )
414        .expect("secp256k1 sign");
415        let k256_signature =
416            impl_k256::sign_message(B256::from_slice(&k256_secret.to_bytes()[..]), hash)
417                .expect("k256 sign");
418        assert_eq!(secp256k1_signature, k256_signature);
419
420        let mut sig: [u8; 65] = [0; 65];
421
422        sig[0..32].copy_from_slice(&secp256k1_signature.r().to_be_bytes::<32>());
423        sig[32..64].copy_from_slice(&secp256k1_signature.s().to_be_bytes::<32>());
424        sig[64] = secp256k1_signature.v() as u8;
425        let secp256k1_recovered =
426            impl_secp256k1::recover_signer_unchecked(&sig, &hash).expect("secp256k1 recover");
427        assert_eq!(secp256k1_recovered, secp256k1_signer);
428
429        sig[0..32].copy_from_slice(&k256_signature.r().to_be_bytes::<32>());
430        sig[32..64].copy_from_slice(&k256_signature.s().to_be_bytes::<32>());
431        sig[64] = k256_signature.v() as u8;
432        let k256_recovered =
433            impl_k256::recover_signer_unchecked(&sig, &hash).expect("k256 recover");
434        assert_eq!(k256_recovered, k256_signer);
435
436        assert_eq!(secp256k1_recovered, k256_recovered);
437    }
438
439    #[cfg(feature = "crypto-backend")]
440    mod backend_tests {
441        use crate::crypto::{backend::CryptoProvider, RecoveryError};
442        use alloc::sync::Arc;
443        use alloy_primitives::{Address, Signature, B256};
444
445        /// Mock crypto provider for testing
446        struct MockCryptoProvider {
447            should_fail: bool,
448            return_address: Address,
449        }
450
451        impl CryptoProvider for MockCryptoProvider {
452            fn recover_signer_unchecked(
453                &self,
454                _sig: &[u8; 65],
455                _msg: &[u8; 32],
456            ) -> Result<Address, RecoveryError> {
457                if self.should_fail {
458                    Err(RecoveryError::new())
459                } else {
460                    Ok(self.return_address)
461                }
462            }
463        }
464
465        #[test]
466        fn test_crypto_backend_basic_functionality() {
467            // Test that when a provider is installed, it's actually used
468            let custom_address = Address::from([0x99; 20]); // Unique test address
469            let provider =
470                Arc::new(MockCryptoProvider { should_fail: false, return_address: custom_address });
471
472            // Try to install the provider (may fail if already set from other tests)
473            let install_result = crate::crypto::backend::install_default_provider(provider);
474
475            // Create test signature and hash
476            let signature = Signature::new(
477                alloy_primitives::U256::from(123u64),
478                alloy_primitives::U256::from(456u64),
479                false,
480            );
481            let hash = B256::from([0xAB; 32]);
482
483            // Call the high-level function
484            let result = crate::crypto::secp256k1::recover_signer_unchecked(&signature, hash);
485
486            // If our provider was successfully installed, we should get our custom address
487            if install_result.is_ok() {
488                assert!(result.is_ok());
489                assert_eq!(result.unwrap(), custom_address);
490            }
491            // If provider was already set, we still should get a valid result
492            else {
493                assert!(result.is_ok()); // Should work with any provider
494            }
495        }
496
497        #[test]
498        fn test_provider_already_set_error() {
499            // First installation might work or fail if already set from another test
500            // Since tests are ran in parallel.
501            let provider1 = Arc::new(MockCryptoProvider {
502                should_fail: false,
503                return_address: Address::from([0x11; 20]),
504            });
505            let _result1 = crate::crypto::backend::install_default_provider(provider1);
506
507            // Second installation should always fail since OnceLock can only be set once
508            let provider2 = Arc::new(MockCryptoProvider {
509                should_fail: true,
510                return_address: Address::from([0x22; 20]),
511            });
512            let result2 = crate::crypto::backend::install_default_provider(provider2);
513
514            // The second attempt should fail with CryptoProviderAlreadySetError
515            assert!(result2.is_err());
516
517            // The error should contain the provider we tried to install (provider2)
518            if let Err(err) = result2 {
519                // We can't easily compare Arc pointers due to type erasure,
520                // but we can verify the error contains a valid provider
521                // (just by accessing it without panicking)
522                let _provider_ref = err.provider.as_ref();
523            }
524        }
525    }
526}