alloy_consensus/
signed.rs

1use crate::{
2    transaction::{RlpEcdsaDecodableTx, RlpEcdsaEncodableTx, SignableTransaction},
3    Transaction,
4};
5use alloy_eips::{
6    eip2718::{Eip2718Error, Eip2718Result},
7    eip2930::AccessList,
8    eip7702::SignedAuthorization,
9    Decodable2718, Encodable2718, Typed2718,
10};
11use alloy_primitives::{Bytes, Sealed, Signature, TxKind, B256, U256};
12use alloy_rlp::BufMut;
13use core::hash::{Hash, Hasher};
14#[cfg(not(feature = "std"))]
15use once_cell::race::OnceBox as OnceLock;
16#[cfg(feature = "std")]
17use std::sync::OnceLock;
18
19/// A transaction with a signature and hash seal.
20#[derive(Debug, Clone)]
21pub struct Signed<T, Sig = Signature> {
22    #[doc(alias = "transaction")]
23    tx: T,
24    signature: Sig,
25    #[doc(alias = "tx_hash", alias = "transaction_hash")]
26    hash: OnceLock<B256>,
27}
28
29impl<T, Sig> Signed<T, Sig> {
30    /// Instantiate from a transaction and signature. Does not verify the signature.
31    pub fn new_unchecked(tx: T, signature: Sig, hash: B256) -> Self {
32        let value = OnceLock::new();
33        #[allow(clippy::useless_conversion)]
34        value.get_or_init(|| hash.into());
35        Self { tx, signature, hash: value }
36    }
37
38    /// Instantiate from a transaction and signature. Does not verify the signature.
39    pub const fn new_unhashed(tx: T, signature: Sig) -> Self {
40        Self { tx, signature, hash: OnceLock::new() }
41    }
42
43    /// Returns a reference to the transaction.
44    #[doc(alias = "transaction")]
45    pub const fn tx(&self) -> &T {
46        &self.tx
47    }
48
49    /// Returns a mutable reference to the transaction.
50    pub const fn tx_mut(&mut self) -> &mut T {
51        &mut self.tx
52    }
53
54    /// Returns a reference to the signature.
55    pub const fn signature(&self) -> &Sig {
56        &self.signature
57    }
58
59    /// Returns the transaction without signature.
60    pub fn strip_signature(self) -> T {
61        self.tx
62    }
63
64    /// Converts the transaction type to the given alternative that is `From<T>`
65    ///
66    /// Caution: This is only intended for converting transaction types that are structurally
67    /// equivalent (produce the same hash).
68    pub fn convert<U>(self) -> Signed<U, Sig>
69    where
70        U: From<T>,
71    {
72        self.map(U::from)
73    }
74
75    /// Converts the transaction to the given alternative that is `TryFrom<T>`
76    ///
77    /// Returns the transaction with the new transaction type if all conversions were successful.
78    ///
79    /// Caution: This is only intended for converting transaction types that are structurally
80    /// equivalent (produce the same hash).
81    pub fn try_convert<U>(self) -> Result<Signed<U, Sig>, U::Error>
82    where
83        U: TryFrom<T>,
84    {
85        self.try_map(U::try_from)
86    }
87
88    /// Applies the given closure to the inner transaction type.
89    ///
90    /// Caution: This is only intended for converting transaction types that are structurally
91    /// equivalent (produce the same hash).
92    pub fn map<Tx>(self, f: impl FnOnce(T) -> Tx) -> Signed<Tx, Sig> {
93        let Self { tx, signature, hash } = self;
94        Signed { tx: f(tx), signature, hash }
95    }
96
97    /// Applies the given fallible closure to the inner transactions.
98    ///
99    /// Caution: This is only intended for converting transaction types that are structurally
100    /// equivalent (produce the same hash).
101    pub fn try_map<Tx, E>(self, f: impl FnOnce(T) -> Result<Tx, E>) -> Result<Signed<Tx, Sig>, E> {
102        let Self { tx, signature, hash } = self;
103        Ok(Signed { tx: f(tx)?, signature, hash })
104    }
105}
106
107impl<T: SignableTransaction<Sig>, Sig> Signed<T, Sig> {
108    /// Calculate the signing hash for the transaction.
109    pub fn signature_hash(&self) -> B256 {
110        self.tx.signature_hash()
111    }
112}
113
114impl<T> Signed<T>
115where
116    T: RlpEcdsaEncodableTx,
117{
118    /// Returns a reference to the transaction hash.
119    #[doc(alias = "tx_hash", alias = "transaction_hash")]
120    pub fn hash(&self) -> &B256 {
121        #[allow(clippy::useless_conversion)]
122        self.hash.get_or_init(|| self.tx.tx_hash(&self.signature).into())
123    }
124
125    /// Splits the transaction into parts.
126    pub fn into_parts(self) -> (T, Signature, B256) {
127        let hash = *self.hash();
128        (self.tx, self.signature, hash)
129    }
130
131    /// Get the length of the transaction when RLP encoded.
132    pub fn rlp_encoded_length(&self) -> usize {
133        self.tx.rlp_encoded_length_with_signature(&self.signature)
134    }
135
136    /// RLP encode the signed transaction.
137    pub fn rlp_encode(&self, out: &mut dyn BufMut) {
138        self.tx.rlp_encode_signed(&self.signature, out);
139    }
140
141    /// Get the length of the transaction when EIP-2718 encoded.
142    pub fn eip2718_encoded_length(&self) -> usize {
143        self.tx.eip2718_encoded_length(&self.signature)
144    }
145
146    /// EIP-2718 encode the signed transaction with a specified type flag.
147    pub fn eip2718_encode_with_type(&self, ty: u8, out: &mut dyn BufMut) {
148        self.tx.eip2718_encode_with_type(&self.signature, ty, out);
149    }
150
151    /// EIP-2718 encode the signed transaction.
152    pub fn eip2718_encode(&self, out: &mut dyn BufMut) {
153        self.tx.eip2718_encode(&self.signature, out);
154    }
155
156    /// Get the length of the transaction when network encoded.
157    pub fn network_encoded_length(&self) -> usize {
158        self.tx.network_encoded_length(&self.signature)
159    }
160
161    /// Network encode the signed transaction with a specified type flag.
162    pub fn network_encode_with_type(&self, ty: u8, out: &mut dyn BufMut) {
163        self.tx.network_encode_with_type(&self.signature, ty, out);
164    }
165
166    /// Network encode the signed transaction.
167    pub fn network_encode(&self, out: &mut dyn BufMut) {
168        self.tx.network_encode(&self.signature, out);
169    }
170}
171
172impl<T> Signed<T>
173where
174    T: RlpEcdsaDecodableTx,
175{
176    /// RLP decode the signed transaction.
177    pub fn rlp_decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
178        T::rlp_decode_signed(buf)
179    }
180
181    /// EIP-2718 decode the signed transaction with a specified type flag.
182    pub fn eip2718_decode_with_type(buf: &mut &[u8], ty: u8) -> Eip2718Result<Self> {
183        T::eip2718_decode_with_type(buf, ty)
184    }
185
186    /// EIP-2718 decode the signed transaction.
187    pub fn eip2718_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
188        T::eip2718_decode(buf)
189    }
190
191    /// Network decode the signed transaction with a specified type flag.
192    pub fn network_decode_with_type(buf: &mut &[u8], ty: u8) -> Eip2718Result<Self> {
193        T::network_decode_with_type(buf, ty)
194    }
195
196    /// Network decode the signed transaction.
197    pub fn network_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
198        T::network_decode(buf)
199    }
200}
201
202impl<T> Hash for Signed<T>
203where
204    T: RlpEcdsaDecodableTx + Hash,
205{
206    fn hash<H: Hasher>(&self, state: &mut H) {
207        self.hash().hash(state);
208        self.tx.hash(state);
209        self.signature.hash(state);
210    }
211}
212
213impl<T: RlpEcdsaEncodableTx + PartialEq> PartialEq for Signed<T> {
214    fn eq(&self, other: &Self) -> bool {
215        self.hash() == other.hash() && self.tx == other.tx && self.signature == other.signature
216    }
217}
218
219impl<T: RlpEcdsaEncodableTx + PartialEq> Eq for Signed<T> {}
220
221#[cfg(feature = "k256")]
222impl<T: SignableTransaction<Signature>> Signed<T, Signature> {
223    /// Recover the signer of the transaction
224    pub fn recover_signer(
225        &self,
226    ) -> Result<alloy_primitives::Address, alloy_primitives::SignatureError> {
227        let sighash = self.tx.signature_hash();
228        self.signature.recover_address_from_prehash(&sighash)
229    }
230
231    /// Attempts to recover signer and constructs a [`crate::transaction::Recovered`] object.
232    pub fn try_into_recovered(
233        self,
234    ) -> Result<crate::transaction::Recovered<T>, alloy_primitives::SignatureError> {
235        let signer = self.recover_signer()?;
236        Ok(crate::transaction::Recovered::new_unchecked(self.tx, signer))
237    }
238
239    /// Attempts to recover signer and constructs a [`crate::transaction::Recovered`] with a
240    /// reference to the transaction `Recovered<&T>`
241    pub fn try_to_recovered_ref(
242        &self,
243    ) -> Result<crate::transaction::Recovered<&T>, alloy_primitives::SignatureError> {
244        let signer = self.recover_signer()?;
245        Ok(crate::transaction::Recovered::new_unchecked(&self.tx, signer))
246    }
247}
248
249#[cfg(all(any(test, feature = "arbitrary"), feature = "k256"))]
250impl<'a, T: SignableTransaction<Signature> + arbitrary::Arbitrary<'a>> arbitrary::Arbitrary<'a>
251    for Signed<T, Signature>
252{
253    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
254        use k256::{
255            ecdsa::{signature::hazmat::PrehashSigner, SigningKey},
256            NonZeroScalar,
257        };
258        use rand::{rngs::StdRng, SeedableRng};
259
260        let rng_seed = u.arbitrary::<[u8; 32]>()?;
261        let mut rand_gen = StdRng::from_seed(rng_seed);
262        let signing_key: SigningKey = NonZeroScalar::random(&mut rand_gen).into();
263
264        let tx = T::arbitrary(u)?;
265
266        let (recoverable_sig, recovery_id) =
267            signing_key.sign_prehash(tx.signature_hash().as_ref()).unwrap();
268        let signature: Signature = (recoverable_sig, recovery_id).into();
269
270        Ok(tx.into_signed(signature))
271    }
272}
273
274impl<T> Typed2718 for Signed<T>
275where
276    T: Typed2718,
277{
278    fn ty(&self) -> u8 {
279        self.tx().ty()
280    }
281}
282
283impl<T: Transaction> Transaction for Signed<T> {
284    #[inline]
285    fn chain_id(&self) -> Option<u64> {
286        self.tx.chain_id()
287    }
288
289    #[inline]
290    fn nonce(&self) -> u64 {
291        self.tx.nonce()
292    }
293
294    #[inline]
295    fn gas_limit(&self) -> u64 {
296        self.tx.gas_limit()
297    }
298
299    #[inline]
300    fn gas_price(&self) -> Option<u128> {
301        self.tx.gas_price()
302    }
303
304    #[inline]
305    fn max_fee_per_gas(&self) -> u128 {
306        self.tx.max_fee_per_gas()
307    }
308
309    #[inline]
310    fn max_priority_fee_per_gas(&self) -> Option<u128> {
311        self.tx.max_priority_fee_per_gas()
312    }
313
314    #[inline]
315    fn max_fee_per_blob_gas(&self) -> Option<u128> {
316        self.tx.max_fee_per_blob_gas()
317    }
318
319    #[inline]
320    fn priority_fee_or_price(&self) -> u128 {
321        self.tx.priority_fee_or_price()
322    }
323
324    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
325        self.tx.effective_gas_price(base_fee)
326    }
327
328    #[inline]
329    fn is_dynamic_fee(&self) -> bool {
330        self.tx.is_dynamic_fee()
331    }
332
333    #[inline]
334    fn kind(&self) -> TxKind {
335        self.tx.kind()
336    }
337
338    #[inline]
339    fn is_create(&self) -> bool {
340        self.tx.is_create()
341    }
342
343    #[inline]
344    fn value(&self) -> U256 {
345        self.tx.value()
346    }
347
348    #[inline]
349    fn input(&self) -> &Bytes {
350        self.tx.input()
351    }
352
353    #[inline]
354    fn access_list(&self) -> Option<&AccessList> {
355        self.tx.access_list()
356    }
357
358    #[inline]
359    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
360        self.tx.blob_versioned_hashes()
361    }
362
363    #[inline]
364    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
365        self.tx.authorization_list()
366    }
367}
368
369impl<T: Transaction> Transaction for Sealed<T> {
370    #[inline]
371    fn chain_id(&self) -> Option<u64> {
372        self.inner().chain_id()
373    }
374
375    #[inline]
376    fn nonce(&self) -> u64 {
377        self.inner().nonce()
378    }
379
380    #[inline]
381    fn gas_limit(&self) -> u64 {
382        self.inner().gas_limit()
383    }
384
385    #[inline]
386    fn gas_price(&self) -> Option<u128> {
387        self.inner().gas_price()
388    }
389
390    #[inline]
391    fn max_fee_per_gas(&self) -> u128 {
392        self.inner().max_fee_per_gas()
393    }
394
395    #[inline]
396    fn max_priority_fee_per_gas(&self) -> Option<u128> {
397        self.inner().max_priority_fee_per_gas()
398    }
399
400    #[inline]
401    fn max_fee_per_blob_gas(&self) -> Option<u128> {
402        self.inner().max_fee_per_blob_gas()
403    }
404
405    #[inline]
406    fn priority_fee_or_price(&self) -> u128 {
407        self.inner().priority_fee_or_price()
408    }
409
410    fn effective_gas_price(&self, base_fee: Option<u64>) -> u128 {
411        self.inner().effective_gas_price(base_fee)
412    }
413
414    #[inline]
415    fn is_dynamic_fee(&self) -> bool {
416        self.inner().is_dynamic_fee()
417    }
418
419    #[inline]
420    fn kind(&self) -> TxKind {
421        self.inner().kind()
422    }
423
424    #[inline]
425    fn is_create(&self) -> bool {
426        self.inner().is_create()
427    }
428
429    #[inline]
430    fn value(&self) -> U256 {
431        self.inner().value()
432    }
433
434    #[inline]
435    fn input(&self) -> &Bytes {
436        self.inner().input()
437    }
438
439    #[inline]
440    fn access_list(&self) -> Option<&AccessList> {
441        self.inner().access_list()
442    }
443
444    #[inline]
445    fn blob_versioned_hashes(&self) -> Option<&[B256]> {
446        self.inner().blob_versioned_hashes()
447    }
448
449    #[inline]
450    fn authorization_list(&self) -> Option<&[SignedAuthorization]> {
451        self.inner().authorization_list()
452    }
453}
454
455#[cfg(any(feature = "secp256k1", feature = "k256"))]
456impl<T> crate::transaction::SignerRecoverable for Signed<T>
457where
458    T: SignableTransaction<Signature>,
459{
460    fn recover_signer(&self) -> Result<alloy_primitives::Address, crate::crypto::RecoveryError> {
461        let signature_hash = self.signature_hash();
462        crate::crypto::secp256k1::recover_signer(self.signature(), signature_hash)
463    }
464
465    fn recover_signer_unchecked(
466        &self,
467    ) -> Result<alloy_primitives::Address, crate::crypto::RecoveryError> {
468        let signature_hash = self.signature_hash();
469        crate::crypto::secp256k1::recover_signer_unchecked(self.signature(), signature_hash)
470    }
471
472    fn recover_unchecked_with_buf(
473        &self,
474        buf: &mut alloc::vec::Vec<u8>,
475    ) -> Result<alloy_primitives::Address, crate::crypto::RecoveryError> {
476        buf.clear();
477        self.tx.encode_for_signing(buf);
478        let signature_hash = alloy_primitives::keccak256(buf);
479        crate::crypto::secp256k1::recover_signer_unchecked(self.signature(), signature_hash)
480    }
481}
482
483impl<T> Encodable2718 for Signed<T>
484where
485    T: RlpEcdsaEncodableTx + Typed2718 + Send + Sync,
486{
487    fn encode_2718_len(&self) -> usize {
488        self.eip2718_encoded_length()
489    }
490
491    fn encode_2718(&self, out: &mut dyn alloy_rlp::BufMut) {
492        self.eip2718_encode(out)
493    }
494
495    fn trie_hash(&self) -> B256 {
496        *self.hash()
497    }
498}
499
500impl<T> Decodable2718 for Signed<T>
501where
502    T: RlpEcdsaDecodableTx + Typed2718 + Send + Sync,
503{
504    fn typed_decode(ty: u8, buf: &mut &[u8]) -> Eip2718Result<Self> {
505        let decoded = T::rlp_decode_signed(buf)?;
506
507        if decoded.ty() != ty {
508            return Err(Eip2718Error::UnexpectedType(ty));
509        }
510
511        Ok(decoded)
512    }
513
514    fn fallback_decode(buf: &mut &[u8]) -> Eip2718Result<Self> {
515        T::rlp_decode_signed(buf).map_err(Into::into)
516    }
517}
518
519#[cfg(feature = "serde")]
520mod serde {
521    use crate::transaction::RlpEcdsaEncodableTx;
522    use alloc::borrow::Cow;
523    use alloy_primitives::B256;
524    use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer};
525
526    #[derive(Serialize, Deserialize)]
527    struct Signed<'a, T: Clone, Sig: Clone> {
528        #[serde(flatten)]
529        tx: Cow<'a, T>,
530        #[serde(flatten)]
531        signature: Cow<'a, Sig>,
532        hash: Cow<'a, B256>,
533    }
534
535    impl<T> Serialize for super::Signed<T>
536    where
537        T: Clone + RlpEcdsaEncodableTx + Serialize,
538    {
539        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
540        where
541            S: Serializer,
542        {
543            Signed {
544                tx: Cow::Borrowed(&self.tx),
545                signature: Cow::Borrowed(&self.signature),
546                hash: Cow::Borrowed(self.hash()),
547            }
548            .serialize(serializer)
549        }
550    }
551
552    impl<'de, T, Sig> Deserialize<'de> for super::Signed<T, Sig>
553    where
554        T: Clone + DeserializeOwned,
555        Sig: Clone + DeserializeOwned,
556    {
557        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
558        where
559            D: Deserializer<'de>,
560        {
561            Signed::<T, Sig>::deserialize(deserializer).map(|value| {
562                Self::new_unchecked(
563                    value.tx.into_owned(),
564                    value.signature.into_owned(),
565                    value.hash.into_owned(),
566                )
567            })
568        }
569    }
570}