alloy_primitives/signature/
sig.rs

1#![allow(unknown_lints, unnameable_types)]
2
3use crate::{
4    hex,
5    signature::{Parity, SignatureError},
6    uint, U256,
7};
8use alloc::vec::Vec;
9use core::str::FromStr;
10
11/// The order of the secp256k1 curve
12const SECP256K1N_ORDER: U256 =
13    uint!(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141_U256);
14
15/// An Ethereum ECDSA signature.
16#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
17pub struct Signature {
18    v: Parity,
19    r: U256,
20    s: U256,
21}
22
23impl<'a> TryFrom<&'a [u8]> for Signature {
24    type Error = SignatureError;
25
26    /// Parses a raw signature which is expected to be 65 bytes long where
27    /// the first 32 bytes is the `r` value, the second 32 bytes the `s` value
28    /// and the final byte is the `v` value in 'Electrum' notation.
29    fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
30        if bytes.len() != 65 {
31            return Err(SignatureError::FromBytes("expected exactly 65 bytes"));
32        }
33        Self::from_bytes_and_parity(&bytes[..64], bytes[64] as u64)
34    }
35}
36
37impl FromStr for Signature {
38    type Err = SignatureError;
39
40    fn from_str(s: &str) -> Result<Self, Self::Err> {
41        let bytes = hex::decode(s)?;
42        Self::try_from(&bytes[..])
43    }
44}
45
46impl From<&Signature> for [u8; 65] {
47    #[inline]
48    fn from(value: &Signature) -> [u8; 65] {
49        value.as_bytes()
50    }
51}
52
53impl From<Signature> for [u8; 65] {
54    #[inline]
55    fn from(value: Signature) -> [u8; 65] {
56        value.as_bytes()
57    }
58}
59
60impl From<&Signature> for Vec<u8> {
61    #[inline]
62    fn from(value: &Signature) -> Self {
63        value.as_bytes().to_vec()
64    }
65}
66
67impl From<Signature> for Vec<u8> {
68    #[inline]
69    fn from(value: Signature) -> Self {
70        value.as_bytes().to_vec()
71    }
72}
73
74#[cfg(feature = "k256")]
75impl From<(k256::ecdsa::Signature, k256::ecdsa::RecoveryId)> for Signature {
76    fn from(value: (k256::ecdsa::Signature, k256::ecdsa::RecoveryId)) -> Self {
77        Self::from_signature_and_parity(value.0, value.1).unwrap()
78    }
79}
80
81#[cfg(feature = "k256")]
82impl TryFrom<Signature> for k256::ecdsa::Signature {
83    type Error = k256::ecdsa::Error;
84
85    fn try_from(value: Signature) -> Result<Self, Self::Error> {
86        value.to_k256()
87    }
88}
89
90#[cfg(feature = "rlp")]
91impl Signature {
92    /// Decode an RLP-encoded VRS signature.
93    pub fn decode_rlp_vrs(buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
94        use alloy_rlp::Decodable;
95
96        let parity: Parity = Decodable::decode(buf)?;
97        let r = Decodable::decode(buf)?;
98        let s = Decodable::decode(buf)?;
99
100        Self::from_rs_and_parity(r, s, parity)
101            .map_err(|_| alloy_rlp::Error::Custom("attempted to decode invalid field element"))
102    }
103}
104
105impl Signature {
106    #[doc(hidden)]
107    pub fn test_signature() -> Self {
108        Self::from_scalars_and_parity(
109            b256!("840cfc572845f5786e702984c2a582528cad4b49b2a10b9db1be7fca90058565"),
110            b256!("25e7109ceb98168d95b09b18bbf6b685130e0562f233877d492b94eee0c5b6d1"),
111            false,
112        )
113        .unwrap()
114    }
115
116    /// Instantiate a new signature from `r`, `s`, and `v` values.
117    #[allow(clippy::missing_const_for_fn)]
118    pub fn new(r: U256, s: U256, v: Parity) -> Self {
119        Self { r, s, v }
120    }
121
122    /// Returns the inner ECDSA signature.
123    #[cfg(feature = "k256")]
124    #[deprecated(note = "use `Signature::to_k256` instead")]
125    #[inline]
126    pub fn into_inner(self) -> k256::ecdsa::Signature {
127        self.try_into().expect("signature conversion failed")
128    }
129
130    /// Returns the inner ECDSA signature.
131    #[cfg(feature = "k256")]
132    #[inline]
133    pub fn to_k256(self) -> Result<k256::ecdsa::Signature, k256::ecdsa::Error> {
134        k256::ecdsa::Signature::from_scalars(self.r.to_be_bytes(), self.s.to_be_bytes())
135    }
136
137    /// Instantiate from a signature and recovery id
138    #[cfg(feature = "k256")]
139    pub fn from_signature_and_parity<T: TryInto<Parity, Error = E>, E: Into<SignatureError>>(
140        sig: k256::ecdsa::Signature,
141        parity: T,
142    ) -> Result<Self, SignatureError> {
143        let r = U256::from_be_slice(sig.r().to_bytes().as_ref());
144        let s = U256::from_be_slice(sig.s().to_bytes().as_ref());
145        Ok(Self { v: parity.try_into().map_err(Into::into)?, r, s })
146    }
147
148    /// Creates a [`Signature`] from the serialized `r` and `s` scalar values, which comprise the
149    /// ECDSA signature, alongside a `v` value, used to determine the recovery ID.
150    #[inline]
151    pub fn from_scalars_and_parity<T: TryInto<Parity, Error = E>, E: Into<SignatureError>>(
152        r: crate::B256,
153        s: crate::B256,
154        parity: T,
155    ) -> Result<Self, SignatureError> {
156        Self::from_rs_and_parity(
157            U256::from_be_slice(r.as_ref()),
158            U256::from_be_slice(s.as_ref()),
159            parity,
160        )
161    }
162
163    /// Normalizes the signature into "low S" form as described in
164    /// [BIP 0062: Dealing with Malleability][1].
165    ///
166    /// [1]: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki
167    #[inline]
168    pub fn normalize_s(&self) -> Option<Self> {
169        let s = self.s();
170
171        if s > SECP256K1N_ORDER >> 1 {
172            Some(Self { v: self.v.inverted(), r: self.r, s: SECP256K1N_ORDER - s })
173        } else {
174            None
175        }
176    }
177
178    /// Returns the recovery ID.
179    #[cfg(feature = "k256")]
180    #[inline]
181    pub const fn recid(&self) -> k256::ecdsa::RecoveryId {
182        self.v.recid()
183    }
184
185    #[cfg(feature = "k256")]
186    #[doc(hidden)]
187    #[deprecated(note = "use `Signature::recid` instead")]
188    pub const fn recovery_id(&self) -> k256::ecdsa::RecoveryId {
189        self.recid()
190    }
191
192    /// Recovers an [`Address`] from this signature and the given message by first prefixing and
193    /// hashing the message according to [EIP-191](crate::eip191_hash_message).
194    ///
195    /// [`Address`]: crate::Address
196    #[cfg(feature = "k256")]
197    #[inline]
198    pub fn recover_address_from_msg<T: AsRef<[u8]>>(
199        &self,
200        msg: T,
201    ) -> Result<crate::Address, SignatureError> {
202        self.recover_from_msg(msg).map(|vk| crate::Address::from_public_key(&vk))
203    }
204
205    /// Recovers an [`Address`] from this signature and the given prehashed message.
206    ///
207    /// [`Address`]: crate::Address
208    #[cfg(feature = "k256")]
209    #[inline]
210    pub fn recover_address_from_prehash(
211        &self,
212        prehash: &crate::B256,
213    ) -> Result<crate::Address, SignatureError> {
214        self.recover_from_prehash(prehash).map(|vk| crate::Address::from_public_key(&vk))
215    }
216
217    /// Recovers a [`VerifyingKey`] from this signature and the given message by first prefixing and
218    /// hashing the message according to [EIP-191](crate::eip191_hash_message).
219    ///
220    /// [`VerifyingKey`]: k256::ecdsa::VerifyingKey
221    #[cfg(feature = "k256")]
222    #[inline]
223    pub fn recover_from_msg<T: AsRef<[u8]>>(
224        &self,
225        msg: T,
226    ) -> Result<k256::ecdsa::VerifyingKey, SignatureError> {
227        self.recover_from_prehash(&crate::eip191_hash_message(msg))
228    }
229
230    /// Recovers a [`VerifyingKey`] from this signature and the given prehashed message.
231    ///
232    /// [`VerifyingKey`]: k256::ecdsa::VerifyingKey
233    #[cfg(feature = "k256")]
234    #[inline]
235    pub fn recover_from_prehash(
236        &self,
237        prehash: &crate::B256,
238    ) -> Result<k256::ecdsa::VerifyingKey, SignatureError> {
239        let this = self.normalize_s().unwrap_or(*self);
240        k256::ecdsa::VerifyingKey::recover_from_prehash(
241            prehash.as_slice(),
242            &this.to_k256()?,
243            this.recid(),
244        )
245        .map_err(Into::into)
246    }
247
248    /// Parses a signature from a byte slice, with a v value
249    ///
250    /// # Panics
251    ///
252    /// If the slice is not at least 64 bytes long.
253    #[inline]
254    pub fn from_bytes_and_parity<T: TryInto<Parity, Error = E>, E: Into<SignatureError>>(
255        bytes: &[u8],
256        parity: T,
257    ) -> Result<Self, SignatureError> {
258        let r = U256::from_be_slice(&bytes[..32]);
259        let s = U256::from_be_slice(&bytes[32..64]);
260        Self::from_rs_and_parity(r, s, parity)
261    }
262
263    /// Instantiate from v, r, s.
264    pub fn from_rs_and_parity<T: TryInto<Parity, Error = E>, E: Into<SignatureError>>(
265        r: U256,
266        s: U256,
267        parity: T,
268    ) -> Result<Self, SignatureError> {
269        Ok(Self { v: parity.try_into().map_err(Into::into)?, r, s })
270    }
271
272    /// Modifies the recovery ID by applying [EIP-155] to a `v` value.
273    ///
274    /// [EIP-155]: https://eips.ethereum.org/EIPS/eip-155
275    #[inline]
276    pub fn with_chain_id(self, chain_id: u64) -> Self {
277        self.with_parity(self.v.with_chain_id(chain_id))
278    }
279
280    /// Modifies the recovery ID by dropping any [EIP-155] v value, converting
281    /// to a simple parity bool.
282    pub fn with_parity_bool(self) -> Self {
283        self.with_parity(self.v.to_parity_bool())
284    }
285
286    /// Returns the `r` component of this signature.
287    #[inline]
288    pub const fn r(&self) -> U256 {
289        self.r
290    }
291
292    /// Returns the `s` component of this signature.
293    #[inline]
294    pub const fn s(&self) -> U256 {
295        self.s
296    }
297
298    /// Returns the recovery ID as a `u8`.
299    #[inline]
300    pub const fn v(&self) -> Parity {
301        self.v
302    }
303
304    /// Returns the byte-array representation of this signature.
305    ///
306    /// The first 32 bytes are the `r` value, the second 32 bytes the `s` value
307    /// and the final byte is the `v` value in 'Electrum' notation.
308    #[inline]
309    pub fn as_bytes(&self) -> [u8; 65] {
310        let mut sig = [0u8; 65];
311        sig[..32].copy_from_slice(&self.r.to_be_bytes::<32>());
312        sig[32..64].copy_from_slice(&self.s.to_be_bytes::<32>());
313        sig[64] = self.v.y_parity_byte_non_eip155().unwrap_or(self.v.y_parity_byte());
314        sig
315    }
316
317    /// Sets the recovery ID by normalizing a `v` value.
318    #[inline]
319    pub fn with_parity<T: Into<Parity>>(self, parity: T) -> Self {
320        Self { v: parity.into(), r: self.r, s: self.s }
321    }
322
323    /// Length of RLP RS field encoding
324    #[cfg(feature = "rlp")]
325    pub fn rlp_rs_len(&self) -> usize {
326        alloy_rlp::Encodable::length(&self.r) + alloy_rlp::Encodable::length(&self.s)
327    }
328
329    #[cfg(feature = "rlp")]
330    /// Length of RLP V field encoding
331    pub fn rlp_vrs_len(&self) -> usize {
332        self.rlp_rs_len() + alloy_rlp::Encodable::length(&self.v)
333    }
334
335    /// Write R and S to an RLP buffer in progress.
336    #[cfg(feature = "rlp")]
337    pub fn write_rlp_rs(&self, out: &mut dyn alloy_rlp::BufMut) {
338        alloy_rlp::Encodable::encode(&self.r, out);
339        alloy_rlp::Encodable::encode(&self.s, out);
340    }
341
342    /// Write the V to an RLP buffer without using EIP-155.
343    #[cfg(feature = "rlp")]
344    pub fn write_rlp_v(&self, out: &mut dyn alloy_rlp::BufMut) {
345        alloy_rlp::Encodable::encode(&self.v, out);
346    }
347
348    /// Write the VRS to the output. The V will always be 27 or 28.
349    #[cfg(feature = "rlp")]
350    pub fn write_rlp_vrs(&self, out: &mut dyn alloy_rlp::BufMut) {
351        self.write_rlp_v(out);
352        self.write_rlp_rs(out);
353    }
354}
355
356#[cfg(feature = "rlp")]
357impl alloy_rlp::Encodable for Signature {
358    fn encode(&self, out: &mut dyn alloy_rlp::BufMut) {
359        alloy_rlp::Header { list: true, payload_length: self.rlp_vrs_len() }.encode(out);
360        self.write_rlp_vrs(out);
361    }
362
363    fn length(&self) -> usize {
364        let payload_length = self.rlp_vrs_len();
365        payload_length + alloy_rlp::length_of_length(payload_length)
366    }
367}
368
369#[cfg(feature = "rlp")]
370impl alloy_rlp::Decodable for Signature {
371    fn decode(buf: &mut &[u8]) -> Result<Self, alloy_rlp::Error> {
372        let header = alloy_rlp::Header::decode(buf)?;
373        let pre_len = buf.len();
374        let decoded = Self::decode_rlp_vrs(buf)?;
375        let consumed = pre_len - buf.len();
376        if consumed != header.payload_length {
377            return Err(alloy_rlp::Error::Custom("consumed incorrect number of bytes"));
378        }
379
380        Ok(decoded)
381    }
382}
383
384#[cfg(feature = "serde")]
385impl serde::Serialize for Signature {
386    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
387    where
388        S: serde::Serializer,
389    {
390        // if the serializer is human readable, serialize as a map, otherwise as a tuple
391        if serializer.is_human_readable() {
392            use serde::ser::SerializeMap;
393
394            let mut map = serializer.serialize_map(Some(3))?;
395
396            map.serialize_entry("r", &self.r)?;
397            map.serialize_entry("s", &self.s)?;
398
399            match self.v {
400                Parity::Eip155(v) => map.serialize_entry("v", &crate::U64::from(v))?,
401                Parity::NonEip155(b) => {
402                    map.serialize_entry("v", &crate::U64::from(b as u8 + 27))?
403                }
404                Parity::Parity(true) => map.serialize_entry("yParity", "0x1")?,
405                Parity::Parity(false) => map.serialize_entry("yParity", "0x0")?,
406            }
407            map.end()
408        } else {
409            use serde::ser::SerializeTuple;
410
411            let mut tuple = serializer.serialize_tuple(3)?;
412            tuple.serialize_element(&self.r)?;
413            tuple.serialize_element(&self.s)?;
414            tuple.serialize_element(&crate::U64::from(self.v.to_u64()))?;
415            tuple.end()
416        }
417    }
418}
419
420#[cfg(feature = "serde")]
421impl<'de> serde::Deserialize<'de> for Signature {
422    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
423    where
424        D: serde::Deserializer<'de>,
425    {
426        use serde::de::MapAccess;
427
428        enum Field {
429            R,
430            S,
431            V,
432            YParity,
433            Unknown,
434        }
435
436        impl<'de> serde::Deserialize<'de> for Field {
437            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
438            where
439                D: serde::Deserializer<'de>,
440            {
441                struct FieldVisitor;
442
443                impl<'de> serde::de::Visitor<'de> for FieldVisitor {
444                    type Value = Field;
445
446                    fn expecting(
447                        &self,
448                        formatter: &mut core::fmt::Formatter<'_>,
449                    ) -> core::fmt::Result {
450                        formatter.write_str("v, r, s, or yParity")
451                    }
452
453                    fn visit_str<E>(self, value: &str) -> Result<Field, E>
454                    where
455                        E: serde::de::Error,
456                    {
457                        match value {
458                            "r" => Ok(Field::R),
459                            "s" => Ok(Field::S),
460                            "v" => Ok(Field::V),
461                            "yParity" => Ok(Field::YParity),
462                            _ => Ok(Field::Unknown),
463                        }
464                    }
465                }
466                deserializer.deserialize_identifier(FieldVisitor)
467            }
468        }
469
470        struct MapVisitor;
471        impl<'de> serde::de::Visitor<'de> for MapVisitor {
472            type Value = Signature;
473
474            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
475                formatter.write_str("a JSON signature object containing r, s, and v or yParity")
476            }
477
478            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
479            where
480                A: MapAccess<'de>,
481            {
482                let mut v: Option<Parity> = None;
483                let mut r = None;
484                let mut s = None;
485
486                while let Some(key) = map.next_key()? {
487                    match key {
488                        Field::V => {
489                            let value: crate::U64 = map.next_value()?;
490                            let parity = value.try_into().map_err(|_| {
491                                serde::de::Error::invalid_value(
492                                    serde::de::Unexpected::Unsigned(value.as_limbs()[0]),
493                                    &"a valid v value matching the range 0 | 1 | 27 | 28 | 35..",
494                                )
495                            })?;
496                            v = Some(parity);
497                        }
498                        Field::YParity => {
499                            let value: crate::Uint<1, 1> = map.next_value()?;
500                            if v.is_none() {
501                                v = Some(value.into());
502                            }
503                        }
504                        Field::R => {
505                            let value: U256 = map.next_value()?;
506                            r = Some(value);
507                        }
508                        Field::S => {
509                            let value: U256 = map.next_value()?;
510                            s = Some(value);
511                        }
512                        _ => {}
513                    }
514                }
515
516                let v = v.ok_or_else(|| serde::de::Error::missing_field("v"))?;
517                let r = r.ok_or_else(|| serde::de::Error::missing_field("r"))?;
518                let s = s.ok_or_else(|| serde::de::Error::missing_field("s"))?;
519
520                Signature::from_rs_and_parity(r, s, v).map_err(serde::de::Error::custom)
521            }
522        }
523
524        struct TupleVisitor;
525        impl<'de> serde::de::Visitor<'de> for TupleVisitor {
526            type Value = Signature;
527
528            fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
529                formatter.write_str("a tuple containing r, s, and v")
530            }
531
532            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
533            where
534                A: serde::de::SeqAccess<'de>,
535            {
536                let r = seq
537                    .next_element()?
538                    .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
539                let s = seq
540                    .next_element()?
541                    .ok_or_else(|| serde::de::Error::invalid_length(1, &self))?;
542                let v: crate::U64 = seq
543                    .next_element()?
544                    .ok_or_else(|| serde::de::Error::invalid_length(2, &self))?;
545
546                Signature::from_rs_and_parity(r, s, v).map_err(serde::de::Error::custom)
547            }
548        }
549
550        if deserializer.is_human_readable() {
551            deserializer.deserialize_map(MapVisitor)
552        } else {
553            deserializer.deserialize_tuple(3, TupleVisitor)
554        }
555    }
556}
557
558#[cfg(feature = "arbitrary")]
559impl<'a> arbitrary::Arbitrary<'a> for Signature {
560    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
561        Self::from_rs_and_parity(u.arbitrary()?, u.arbitrary()?, u.arbitrary::<Parity>()?)
562            .map_err(|_| arbitrary::Error::IncorrectFormat)
563    }
564}
565
566#[cfg(feature = "arbitrary")]
567impl proptest::arbitrary::Arbitrary for Signature {
568    type Parameters = ();
569    type Strategy = proptest::strategy::FilterMap<
570        <(U256, U256, Parity) as proptest::arbitrary::Arbitrary>::Strategy,
571        fn((U256, U256, Parity)) -> Option<Self>,
572    >;
573
574    fn arbitrary_with((): Self::Parameters) -> Self::Strategy {
575        use proptest::strategy::Strategy;
576        proptest::arbitrary::any::<(U256, U256, Parity)>()
577            .prop_filter_map("invalid signature", |(r, s, parity)| {
578                Self::from_rs_and_parity(r, s, parity).ok()
579            })
580    }
581}
582
583#[cfg(test)]
584#[allow(unused_imports)]
585mod tests {
586    use super::*;
587    use crate::Bytes;
588    use core::str::FromStr;
589    use hex::FromHex;
590
591    #[cfg(feature = "rlp")]
592    use alloy_rlp::{Decodable, Encodable};
593
594    #[test]
595    #[cfg(feature = "k256")]
596    fn can_recover_tx_sender_not_normalized() {
597        let sig = Signature::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c8041b").unwrap();
598        let hash = b256!("5eb4f5a33c621f32a8622d5f943b6b102994dfe4e5aebbefe69bb1b2aa0fc93e");
599        let expected = address!("0f65fe9276bc9a24ae7083ae28e2660ef72df99e");
600        assert_eq!(sig.recover_address_from_prehash(&hash).unwrap(), expected);
601    }
602
603    #[test]
604    #[cfg(feature = "k256")]
605    fn recover_web3_signature() {
606        // test vector taken from:
607        // https://web3js.readthedocs.io/en/v1.2.2/web3-eth-accounts.html#sign
608        let sig = Signature::from_str(
609            "b91467e570a6466aa9e9876cbcd013baba02900b8979d43fe208a4a4f339f5fd6007e74cd82e037b800186422fc2da167c747ef045e5d18a5f5d4300f8e1a0291c"
610        ).expect("could not parse signature");
611        let expected = address!("2c7536E3605D9C16a7a3D7b1898e529396a65c23");
612        assert_eq!(sig.recover_address_from_msg("Some data").unwrap(), expected);
613    }
614
615    #[test]
616    fn signature_from_str() {
617        let s1 = Signature::from_str(
618            "0xaa231fbe0ed2b5418e6ba7c19bee2522852955ec50996c02a2fe3e71d30ddaf1645baf4823fea7cb4fcc7150842493847cfb6a6d63ab93e8ee928ee3f61f503500"
619        ).expect("could not parse 0x-prefixed signature");
620
621        let s2 = Signature::from_str(
622            "aa231fbe0ed2b5418e6ba7c19bee2522852955ec50996c02a2fe3e71d30ddaf1645baf4823fea7cb4fcc7150842493847cfb6a6d63ab93e8ee928ee3f61f503500"
623        ).expect("could not parse non-prefixed signature");
624
625        assert_eq!(s1, s2);
626    }
627
628    #[cfg(feature = "serde")]
629    #[test]
630    fn deserialize_without_parity() {
631        let raw_signature_without_y_parity = r#"{
632            "r":"0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0",
633            "s":"0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05",
634            "v":"0x1"
635        }"#;
636
637        let signature: Signature = serde_json::from_str(raw_signature_without_y_parity).unwrap();
638
639        let expected = Signature::from_rs_and_parity(
640            U256::from_str("0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0")
641                .unwrap(),
642            U256::from_str("0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05")
643                .unwrap(),
644            1,
645        )
646        .unwrap();
647
648        assert_eq!(signature, expected);
649    }
650
651    #[cfg(feature = "serde")]
652    #[test]
653    fn deserialize_with_parity() {
654        let raw_signature_with_y_parity = serde_json::json!({
655            "r": "0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0",
656            "s": "0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05",
657            "v": "0x1",
658            "yParity": "0x1"
659        });
660
661        let signature: Signature = serde_json::from_value(raw_signature_with_y_parity).unwrap();
662
663        let expected = Signature::from_rs_and_parity(
664            U256::from_str("0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0")
665                .unwrap(),
666            U256::from_str("0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05")
667                .unwrap(),
668            1,
669        )
670        .unwrap();
671
672        assert_eq!(signature, expected);
673    }
674
675    #[cfg(feature = "serde")]
676    #[test]
677    fn serialize_both_parity() {
678        // this test should be removed if the struct moves to an enum based on tx type
679        let signature = Signature::from_rs_and_parity(
680            U256::from_str("0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0")
681                .unwrap(),
682            U256::from_str("0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05")
683                .unwrap(),
684            1,
685        )
686        .unwrap();
687
688        let serialized = serde_json::to_string(&signature).unwrap();
689        assert_eq!(
690            serialized,
691            r#"{"r":"0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0","s":"0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05","yParity":"0x1"}"#
692        );
693    }
694
695    #[cfg(feature = "serde")]
696    #[test]
697    fn serialize_v_only() {
698        // this test should be removed if the struct moves to an enum based on tx type
699        let signature = Signature::from_rs_and_parity(
700            U256::from_str("0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0")
701                .unwrap(),
702            U256::from_str("0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05")
703                .unwrap(),
704            1,
705        )
706        .unwrap();
707
708        let expected = r#"{"r":"0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0","s":"0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05","yParity":"0x1"}"#;
709
710        let serialized = serde_json::to_string(&signature).unwrap();
711        assert_eq!(serialized, expected);
712    }
713
714    #[cfg(feature = "serde")]
715    #[test]
716    fn serialize_v_hex() {
717        let s = r#"{"r":"0x3d43270611ffb1a10fcab841e636e355a787151969b920cf10fef48d3a61aac3","s":"0x11336489e3050e3ec017079dfe16582ce3d167559bcaa8383b665b3fda4eb963","v":"0x1b"}"#;
718
719        let sig = serde_json::from_str::<Signature>(s).unwrap();
720        let serialized = serde_json::to_string(&sig).unwrap();
721        assert_eq!(serialized, s);
722    }
723
724    #[cfg(feature = "serde")]
725    #[test]
726    fn test_bincode_roundtrip() {
727        let signature = Signature::from_rs_and_parity(
728            U256::from_str("0xc569c92f176a3be1a6352dd5005bfc751dcb32f57623dd2a23693e64bf4447b0")
729                .unwrap(),
730            U256::from_str("0x1a891b566d369e79b7a66eecab1e008831e22daa15f91a0a0cf4f9f28f47ee05")
731                .unwrap(),
732            1,
733        )
734        .unwrap();
735
736        let bin = bincode::serialize(&signature).unwrap();
737        assert_eq!(bincode::deserialize::<Signature>(&bin).unwrap(), signature);
738    }
739
740    #[cfg(feature = "rlp")]
741    #[test]
742    fn signature_rlp_decode() {
743        // Given a hex-encoded byte sequence
744        let bytes = crate::hex!("f84301a048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a010002cef538bc0c8e21c46080634a93e082408b0ad93f4a7207e63ec5463793d");
745
746        // Decode the byte sequence into a Signature instance
747        let result = Signature::decode(&mut &bytes[..]).unwrap();
748
749        // Assert that the decoded Signature matches the expected Signature
750        assert_eq!(
751            result,
752            Signature::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a3664935310002cef538bc0c8e21c46080634a93e082408b0ad93f4a7207e63ec5463793d01").unwrap()
753        );
754    }
755
756    #[cfg(feature = "rlp")]
757    #[test]
758    fn signature_rlp_encode() {
759        // Given a Signature instance
760        let sig = Signature::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c8041b").unwrap();
761
762        // Initialize an empty buffer
763        let mut buf = vec![];
764
765        // Encode the Signature into the buffer
766        sig.encode(&mut buf);
767
768        // Define the expected hex-encoded string
769        let expected = "f8431ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804";
770
771        // Assert that the encoded buffer matches the expected hex-encoded string
772        assert_eq!(hex::encode(&buf), expected);
773    }
774
775    #[cfg(feature = "rlp")]
776    #[test]
777    fn signature_rlp_length() {
778        // Given a Signature instance
779        let sig = Signature::from_str("48b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c8041b").unwrap();
780
781        // Assert that the length of the Signature matches the expected length
782        assert_eq!(sig.length(), 69);
783    }
784
785    #[cfg(feature = "rlp")]
786    #[test]
787    fn test_rlp_vrs_len() {
788        let signature = Signature::test_signature();
789        assert_eq!(67, signature.rlp_vrs_len());
790    }
791
792    #[cfg(feature = "rlp")]
793    #[test]
794    fn test_encode_and_decode() {
795        let signature = Signature::test_signature();
796
797        let mut encoded = Vec::new();
798        signature.encode(&mut encoded);
799        assert_eq!(encoded.len(), signature.length());
800        let decoded = Signature::decode(&mut &*encoded).unwrap();
801        assert_eq!(signature, decoded);
802    }
803
804    #[test]
805    fn test_as_bytes() {
806        let signature = Signature::new(
807            U256::from_str(
808                "18515461264373351373200002665853028612451056578545711640558177340181847433846",
809            )
810            .unwrap(),
811            U256::from_str(
812                "46948507304638947509940763649030358759909902576025900602547168820602576006531",
813            )
814            .unwrap(),
815            Parity::Parity(false),
816        );
817
818        let expected = Bytes::from_hex("0x28ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa63627667cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d831b").unwrap();
819        assert_eq!(signature.as_bytes(), **expected);
820    }
821}