From 1783900cb1176d4a10b87bd7e7c8a52c74a3035c Mon Sep 17 00:00:00 2001 From: Alexandre Paillier Date: Tue, 12 Mar 2024 17:22:00 +0100 Subject: [PATCH] Fix EIP-155 V reconstruction for ecrecover in client --- .../src/ledger_app_clients/ethereum/utils.py | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/client/src/ledger_app_clients/ethereum/utils.py b/client/src/ledger_app_clients/ethereum/utils.py index 196d011..b5cc9ef 100644 --- a/client/src/ledger_app_clients/ethereum/utils.py +++ b/client/src/ledger_app_clients/ethereum/utils.py @@ -24,15 +24,31 @@ def recover_transaction(tx_params, vrs: tuple) -> bytes: prefix = raw_tx[:1] raw_tx = raw_tx[len(prefix):] else: - # v is returned on one byte only so it might have overflowed - # in that case, we will reconstruct it to its full value if "chainId" in tx_params: + # v is returned on one byte only so it might have overflowed + # in that case, we will reconstruct it to its full value trunc_chain_id = tx_params["chainId"] while trunc_chain_id.bit_length() > 32: trunc_chain_id >>= 8 + trunc_target = trunc_chain_id * 2 + 35 - parity = int.from_bytes(vrs[0], "big") - (trunc_target & 0xff) - vrs = (parity + tx_params["chainId"] * 2 + 35, vrs[1], vrs[2]) + trunc_v = int.from_bytes(vrs[0], "big") + + if (trunc_target & 0xff) == trunc_v: + parity = 0 + elif ((trunc_target + 1) & 0xff) == trunc_v: + parity = 1 + else: + # should have matched with a previous if + assert False + + # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md + full_v = parity + tx_params["chainId"] * 2 + 35 + # 9 bytes would be big enough even for the biggest chain ID + vrs = (int(full_v).to_bytes(9, "big"), vrs[1], vrs[2]) + else: + # Pre EIP-155 TX + assert False decoded = rlp.decode(raw_tx) reencoded = rlp.encode(decoded[:-3] + list(vrs)) addr = Account.recover_transaction(prefix + reencoded)