Skip to content

Instantly share code, notes, and snippets.

@alisinabh
Created April 8, 2024 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alisinabh/249bf2c33bf288d69f7b18382d0494ac to your computer and use it in GitHub Desktop.
Save alisinabh/249bf2c33bf288d69f7b18382d0494ac to your computer and use it in GitHub Desktop.
EIP1559 Decode and recover public key using Elixir Ethers

Recover EIP1559 pub-key

Mix.install([:ethers, :ex_secp256k1])

Transaction payload

tx =
  "0x02f8a70103020482a41094826180541412d574cf1336d22c0c0a287822678a80b844a9059cbb000000000000000000000000b1228c21546e3848498169f4241ab63279d502d5000000000000000000000000000000000000000000000000000000e8d4a51000c080a0b37b7057eaf42412f834b4e3f1cd00ed4a346381ac2bdd7ddc2fad48619453b3a00868d3423b2e365793bc691be1f7611e3d09c8e883535a1d7f25c2d2f8ee514c"
"0x02f8a70103020482a41094826180541412d574cf1336d22c0c0a287822678a80b844a9059cbb000000000000000000000000b1228c21546e3848498169f4241ab63279d502d5000000000000000000000000000000000000000000000000000000e8d4a51000c080a0b37b7057eaf42412f834b4e3f1cd00ed4a346381ac2bdd7ddc2fad48619453b3a00868d3423b2e365793bc691be1f7611e3d09c8e883535a1d7f25c2d2f8ee514c"

RLP Decode

<<2::8, rlp::binary>> = Ethers.Utils.hex_decode!(tx)
decoded = ExRLP.decode(rlp)
[
  <<1>>,
  <<3>>,
  <<2>>,
  <<4>>,
  <<164, 16>>,
  <<130, 97, 128, 84, 20, 18, 213, 116, 207, 19, 54, 210, 44, 12, 10, 40, 120, 34, 103, 138>>,
  "",
  <<169, 5, 156, 187, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 177, 34, 140, 33, 84, 110, 56, 72, 73,
    129, 105, 244, 36, 26, 182, 50, 121, 213, 2, 213, 0, 0, 0, 0, 0, 0, ...>>,
  [],
  "",
  <<179, 123, 112, 87, 234, 244, 36, 18, 248, 52, 180, 227, 241, 205, 0, 237, 74, 52, 99, 129, 172,
    43, 221, 125, 220, 47, 173, 72, 97, 148, 83, 179>>,
  <<8, 104, 211, 66, 59, 46, 54, 87, 147, 188, 105, 27, 225, 247, 97, 30, 61, 9, 200, 232, 131, 83,
    90, 29, 127, 37, 194, 210, 248, 238, 81, 76>>
]

Take RLP params, encode, add prefix and hash

hash =
  Enum.take(decoded, 9)
  |> ExRLP.encode()
  |> then(&(<<2>> <> &1))
  |> ExKeccak.hash_256()
<<54, 234, 115, 54, 216, 185, 93, 25, 194, 226, 69, 30, 130, 137, 71, 29, 196, 133, 252, 63, 23, 40,
  42, 90, 39, 190, 15, 7, 70, 67, 33, 244>>

Recover public key

r = Enum.at(decoded, 10)
s = Enum.at(decoded, 11)
y = Enum.at(decoded, 9) |> :binary.decode_unsigned()

{:ok, pub} = ExSecp256k1.recover(hash, r, s, y)

Ethers.Utils.public_key_to_address(pub)
"0xc503d317994D03dD708492e3Ef16A9F210b3DECF"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment