alloy-eip8141 0.1.1

Implementation of EIP-8141 type definitions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use alloy_primitives::{Address, B256, Bytes, Signature, U256};
use alloy_rlp::{Decodable, Encodable, Header, RlpDecodable, RlpEncodable};

use crate::{Eip8141Error, FrameAddress, P256_SIGNATURE_LENGTH, SECP256K1_SIGNATURE_LENGTH};

/// EIP-8141 transaction signature scheme.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[repr(u8)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
#[cfg_attr(feature = "borsh", borsh(use_discriminant = true))]
pub enum SignatureScheme {
    /// Arbitrary witness bytes interpreted by EVM validation code.
    #[default]
    Arbitrary = 0x00,
    /// Secp256k1 signature.
    Secp256k1 = 0x01,
    /// P-256 signature.
    P256 = 0x02,
}

impl SignatureScheme {
    /// Returns true if this is [`Self::Arbitrary`].
    pub const fn is_arbitrary(self) -> bool {
        matches!(self, Self::Arbitrary)
    }

    /// Returns true if this is [`Self::Secp256k1`].
    pub const fn is_secp256k1(self) -> bool {
        matches!(self, Self::Secp256k1)
    }

    /// Returns true if this is [`Self::P256`].
    pub const fn is_p256(self) -> bool {
        matches!(self, Self::P256)
    }

    /// Attempts to convert a raw scheme byte into a [`SignatureScheme`].
    pub const fn try_from_u8(value: u8) -> Option<Self> {
        match value {
            0x00 => Some(Self::Arbitrary),
            0x01 => Some(Self::Secp256k1),
            0x02 => Some(Self::P256),
            _ => None,
        }
    }

    /// Returns the protocol signature verification gas cost.
    pub const fn verification_gas(self) -> u64 {
        match self {
            Self::Arbitrary => 100,
            Self::Secp256k1 => 2_800,
            Self::P256 => 6_700,
        }
    }

    /// Returns the fixed signature length of a protocol-validated scheme.
    ///
    /// Arbitrary witnesses have no fixed length.
    pub const fn signature_length(self) -> Option<usize> {
        match self {
            Self::Arbitrary => None,
            Self::Secp256k1 => Some(SECP256K1_SIGNATURE_LENGTH),
            Self::P256 => Some(P256_SIGNATURE_LENGTH),
        }
    }
}

impl_u8_discriminant!(SignatureScheme, InvalidScheme, "invalid EIP-8141 signature scheme");

/// The message authorized by an EIP-8141 signature entry.
///
/// RLP encodes the transaction hash case as an empty byte string and an explicit digest as its 32
/// bytes, preserving the EIP-8141 wire format. Decoding rejects other lengths and the reserved
/// zero digest. JSON uses hex byte strings, including `"0x"` for the transaction hash case; `null`
/// also deserializes as the transaction hash.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
pub enum SignatureMessage {
    /// The signature signs the canonical transaction signature hash.
    #[default]
    TransactionHash,
    /// The signature signs an explicit non-zero 32-byte digest.
    ///
    /// Use [`Self::explicit`] to reject the reserved zero digest.
    Explicit(B256),
}

impl SignatureMessage {
    /// Returns true if this is [`Self::Explicit`].
    pub const fn is_explicit(self) -> bool {
        matches!(self, Self::Explicit(_))
    }

    /// Creates an explicit message, rejecting the reserved zero digest.
    pub fn explicit(digest: B256) -> Result<Self, Eip8141Error> {
        if digest.is_zero() { Err(Eip8141Error::ZeroMessage) } else { Ok(Self::Explicit(digest)) }
    }

    /// Returns true if the signature signs the canonical transaction signature hash.
    pub const fn is_transaction_hash(self) -> bool {
        matches!(self, Self::TransactionHash)
    }

    /// Returns the explicit digest, or `None` for the transaction hash case.
    pub const fn digest(self) -> Option<B256> {
        match self {
            Self::TransactionHash => None,
            Self::Explicit(digest) => Some(digest),
        }
    }

    /// Returns the byte string carried by a signature entry: empty for the transaction hash.
    pub const fn as_bytes(&self) -> &[u8] {
        match self {
            Self::TransactionHash => &[],
            Self::Explicit(digest) => digest.as_slice(),
        }
    }
}

impl TryFrom<&[u8]> for SignatureMessage {
    type Error = Eip8141Error;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        if value.is_empty() {
            return Ok(Self::TransactionHash);
        }
        B256::try_from(value)
            .map_err(|_| Eip8141Error::InvalidMessageLength(value.len()))
            .and_then(Self::explicit)
    }
}

impl Encodable for SignatureMessage {
    fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
        match self {
            Self::TransactionHash => out.put_u8(alloy_rlp::EMPTY_STRING_CODE),
            Self::Explicit(digest) => digest.encode(out),
        }
    }

    fn length(&self) -> usize {
        match self {
            Self::TransactionHash => 1,
            Self::Explicit(digest) => digest.length(),
        }
    }
}

impl Decodable for SignatureMessage {
    fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
        Self::try_from(Header::decode_bytes(buf, false)?).map_err(|err| match err {
            Eip8141Error::ZeroMessage => {
                alloy_rlp::Error::Custom("EIP-8141 signature message must be nonzero")
            }
            _ => alloy_rlp::Error::Custom("invalid EIP-8141 signature message length"),
        })
    }
}

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for SignatureMessage {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(match u.arbitrary::<Option<B256>>()? {
            Some(digest) if !digest.is_zero() => Self::Explicit(digest),
            _ => Self::TransactionHash,
        })
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for SignatureMessage {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let digest = match self {
            Self::TransactionHash => None,
            Self::Explicit(digest) if digest.is_zero() => {
                return Err(serde::ser::Error::custom(Eip8141Error::ZeroMessage));
            }
            Self::Explicit(digest) => Some(*digest),
        };
        crate::serde_utils::serialize_optional_bytes(digest, serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for SignatureMessage {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        crate::serde_utils::deserialize_optional_bytes::<32, D>(deserializer)?
            .map_or(Ok(Self::TransactionHash), |digest| {
                Self::explicit(digest).map_err(serde::de::Error::custom)
            })
    }
}

/// A signature entry attached to an EIP-8141 frame transaction.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, RlpEncodable, RlpDecodable)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
#[cfg_attr(feature = "borsh", derive(borsh::BorshSerialize, borsh::BorshDeserialize))]
pub struct FrameSignature {
    /// Signature scheme identifier.
    pub scheme: SignatureScheme,
    /// Scheme-dependent signer metadata. For `ARBITRARY`, this must be empty.
    pub signer: FrameAddress,
    /// The signed message: the canonical transaction signature hash or an explicit digest.
    pub msg: SignatureMessage,
    /// Raw signature bytes.
    pub signature: Bytes,
}

impl FrameSignature {
    /// Creates a new frame signature from raw field values.
    ///
    /// Call [`Self::validate_structure`] before using an untrusted entry, then perform the
    /// scheme-specific cryptographic verification. This constructor does not validate the fields.
    pub const fn new(
        scheme: SignatureScheme,
        signer: FrameAddress,
        msg: SignatureMessage,
        signature: Bytes,
    ) -> Self {
        Self { scheme, signer, msg, signature }
    }

    /// Returns true if this signature signs the canonical transaction signature hash.
    pub const fn signs_transaction_hash(&self) -> bool {
        self.msg.is_transaction_hash()
    }

    /// Returns the explicit signed digest, or `None` for the transaction hash case.
    pub const fn explicit_message(&self) -> Option<B256> {
        self.msg.digest()
    }

    /// Returns a borrowed RLP view for the transaction's signing preimage.
    ///
    /// The view preserves the scheme, signer, and message. It encodes an empty signature when
    /// [`Self::signs_transaction_hash`] is true to avoid self-reference; explicit-message entries
    /// retain their signature bytes. This does not validate or modify the entry.
    pub fn as_signing(&self) -> SigningFrameSignature<'_> {
        SigningFrameSignature {
            scheme: self.scheme,
            signer: self.signer,
            msg: self.msg,
            signature: if self.signs_transaction_hash() { &[] } else { &self.signature },
        }
    }

    /// Returns the explicit signer address of a protocol-validated scheme.
    ///
    /// Returns `None` for an empty signer, which resolves to the transaction sender, and for
    /// arbitrary signatures, which have no signer. Use [`Self::resolved_signer`] when the
    /// transaction sender is available.
    pub const fn signer_address(&self) -> Option<Address> {
        match self.scheme {
            SignatureScheme::Arbitrary => None,
            _ => self.signer.address(),
        }
    }

    /// Resolves the signer, rejecting a nonempty signer on an arbitrary signature.
    pub const fn resolved_signer(&self, sender: Address) -> Result<Option<Address>, Eip8141Error> {
        match self.scheme {
            SignatureScheme::Arbitrary => {
                if self.signer.is_empty() {
                    Ok(None)
                } else {
                    Err(Eip8141Error::UnexpectedSigner)
                }
            }
            _ => Ok(Some(self.signer.resolve(sender))),
        }
    }

    /// Checks the signer, signature length, parity, and canonical scalar bounds.
    ///
    /// This does not perform cryptographic verification: callers must still recover the secp256k1
    /// signer or verify the P-256 signature against the resolved signer and message. Decoding a
    /// signature entry does not imply that these checks have passed.
    pub fn validate_structure(&self) -> Result<(), Eip8141Error> {
        let (expected, order) = match self.scheme {
            SignatureScheme::Arbitrary => {
                return if self.signer.is_empty() {
                    Ok(())
                } else {
                    Err(Eip8141Error::UnexpectedSigner)
                };
            }
            SignatureScheme::Secp256k1 => (SECP256K1_SIGNATURE_LENGTH, crate::SECP256K1N),
            SignatureScheme::P256 => (P256_SIGNATURE_LENGTH, crate::SECP256R1N),
        };
        if self.signature.len() != expected {
            return Err(Eip8141Error::InvalidSignatureLength {
                expected,
                actual: self.signature.len(),
            });
        }
        let offset = if self.scheme == SignatureScheme::Secp256k1 {
            if self.signature[0] > 1 {
                return Err(Eip8141Error::InvalidParity(self.signature[0]));
            }
            1
        } else {
            0
        };
        let r = U256::from_be_slice(&self.signature[offset..offset + 32]);
        let s = U256::from_be_slice(&self.signature[offset + 32..offset + 64]);
        if r.is_zero() || r >= order || s.is_zero() || s > order >> 1 {
            return Err(Eip8141Error::InvalidSignatureScalar);
        }
        Ok(())
    }

    /// Runs [`Self::validate_structure`] and checks that a P-256 public key hashes to the resolved
    /// signer.
    ///
    /// This covers every check of the specification's `validate_signature` that does not need a
    /// cryptographic backend.
    pub fn validate_structure_with_sender(&self, sender: Address) -> Result<(), Eip8141Error> {
        self.validate_structure()?;
        if let Some(derived) = self.p256_signer_address() {
            let expected = self.signer.resolve(sender);
            if derived != expected {
                return Err(Eip8141Error::P256SignerMismatch { expected, derived });
            }
        }
        Ok(())
    }

    /// Parses the `v || r || s` payload of a secp256k1 entry.
    ///
    /// Returns `None` unless the entry uses the secp256k1 scheme with a 65-byte signature whose
    /// parity byte is zero or one.
    pub fn secp256k1_signature(&self) -> Option<Signature> {
        if self.scheme != SignatureScheme::Secp256k1
            || self.signature.len() != SECP256K1_SIGNATURE_LENGTH
        {
            return None;
        }
        let parity = match self.signature[0] {
            0 => false,
            1 => true,
            _ => return None,
        };
        Some(Signature::from_bytes_and_parity(&self.signature[1..], parity))
    }

    /// Derives the signer address committed to by the public key of a P-256 entry.
    ///
    /// Returns `None` unless the entry uses the P-256 scheme with a 128-byte signature.
    pub fn p256_signer_address(&self) -> Option<Address> {
        (self.scheme == SignatureScheme::P256 && self.signature.len() == P256_SIGNATURE_LENGTH)
            .then(|| Address::from_raw_public_key(&self.signature[64..]))
    }

    /// Creates a structurally checked secp256k1 entry using EIP-8141's `v || r || s` layout.
    ///
    /// Unlike legacy signatures, the parity byte is zero or one and precedes the scalars.
    pub fn from_secp256k1(
        signer: FrameAddress,
        msg: SignatureMessage,
        signature: Signature,
    ) -> Result<Self, Eip8141Error> {
        let mut bytes = [0u8; SECP256K1_SIGNATURE_LENGTH];
        bytes[0] = u8::from(signature.v());
        bytes[1..33].copy_from_slice(&signature.r().to_be_bytes::<32>());
        bytes[33..].copy_from_slice(&signature.s().to_be_bytes::<32>());
        let entry = Self::new(SignatureScheme::Secp256k1, signer, msg, bytes.into());
        entry.validate_structure()?;
        Ok(entry)
    }

    /// Returns the protocol signature verification gas cost.
    pub const fn verification_gas(&self) -> u64 {
        self.scheme.verification_gas()
    }
}

/// Borrowed RLP view of a signature entry in a transaction's signing preimage.
///
/// Created by [`FrameSignature::as_signing`]. Its [`Encodable`] implementation includes the entry's
/// list header and applies signature elision independently of the signature scheme.
#[derive(Clone, Copy, Debug, RlpEncodable)]
pub struct SigningFrameSignature<'a> {
    scheme: SignatureScheme,
    signer: FrameAddress,
    msg: SignatureMessage,
    signature: &'a [u8],
}

/// Borrowed RLP view of a signature list in a transaction's signing preimage.
///
/// Each entry is encoded through [`FrameSignature::as_signing`], and the outer RLP list header
/// reflects the transformed entries' lengths. Encoding does not allocate or modify the entries.
///
/// ```
/// use alloy_eip8141::{FrameSignature, SigningFrameSignatures};
/// use alloy_rlp::Encodable;
///
/// let entries = [FrameSignature::default()];
/// let signing = SigningFrameSignatures::new(&entries);
/// let encoded = alloy_rlp::encode(signing);
/// assert_eq!(encoded.len(), signing.length());
/// assert_eq!(encoded, [0xc5, 0xc4, 0x80, 0x80, 0x80, 0x80]);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct SigningFrameSignatures<'a>(&'a [FrameSignature]);

impl<'a> SigningFrameSignatures<'a> {
    /// Creates a signing-preimage view of the signature list.
    pub const fn new(signatures: &'a [FrameSignature]) -> Self {
        Self(signatures)
    }
}

impl Encodable for SigningFrameSignatures<'_> {
    fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
        alloy_rlp::encode_iter(self.0.iter().map(FrameSignature::as_signing), out);
    }

    fn length(&self) -> usize {
        let payload_length = self.0.iter().map(|signature| signature.as_signing().length()).sum();
        Header { list: true, payload_length }.length_with_payload()
    }
}