alloy-rs / core

High-performance, well-tested & documented core libraries for Ethereum, in Rust
https://alloy.rs
Apache License 2.0
758 stars 131 forks source link

[Bug] Signatures from sign_hash return Parity, but if converting to Vec and restoring, it returns NonEip155 #705

Open gusinacio opened 1 month ago

gusinacio commented 1 month ago

Component

primitives

What version of Alloy are you on?

0.2.1

Operating System

None

Describe the bug

The following code doesn't work, it looks like it's returned Parity() every signature, but if we convert to bytes and restore elsewhere, it returns NonEip155.

The following test fails:

    #[test]
    fn test_parity() {
        let signer = PrivateKeySigner::random();
        // The message to sign.
        let message = b"hello";

        // Sign the message asynchronously with the signer.
        let signature = signer.sign_message_sync(message).unwrap();

        let value = signature.as_bytes().to_vec();
        let recovered_signature: Signature = value.as_slice().try_into().unwrap();
        assert_eq!(signature, recovered_signature);
    }

The error is the following:

assertion `left == right` failed
  left: Signature { inner: ecdsa::Signature<Secp256k1>(33828FC1FE49FB3177AA80459AE130BD8147158000FA701D7E33BC33B8EDDF25586239AF447392DD8AC6DACBE5E3F91B72AB5593BE3ED6DC702489CA4E2BE1B6), v: Parity(false), r: 23298637575944829774526378124809190621347391490807772432023406486951885135653, s: 39977079812416937747731152449858872909720600328418637835900651766296202699190 }
 right: Signature { inner: ecdsa::Signature<Secp256k1>(33828FC1FE49FB3177AA80459AE130BD8147158000FA701D7E33BC33B8EDDF25586239AF447392DD8AC6DACBE5E3F91B72AB5593BE3ED6DC702489CA4E2BE1B6), v: NonEip155(false), r: 23298637575944829774526378124809190621347391490807772432023406486951885135653, s: 39977079812416937747731152449858872909720600328418637835900651766296202699190 }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
test tap::context::rav::test::test_parity ... FAILED

failures:

failures:
    test::test_parity
mattsse commented 1 month ago

hmm these are indeed not symmetrical

https://github.com/alloy-rs/core/blob/adcf7adfa1f35c56e6331bab85b8c56d32a465f1/crates/primitives/src/signature/parity.rs#L19-L24

https://github.com/alloy-rs/core/blob/adcf7adfa1f35c56e6331bab85b8c56d32a465f1/crates/primitives/src/signature/parity.rs#L45-L56

I assume this is the bug here:

https://github.com/alloy-rs/core/blob/adcf7adfa1f35c56e6331bab85b8c56d32a465f1/crates/primitives/src/signature/parity.rs#L87-L94

invoked by

https://github.com/alloy-rs/core/blob/adcf7adfa1f35c56e6331bab85b8c56d32a465f1/crates/primitives/src/signature/sig.rs#L334-L334