"""Offline decoding and signing-preimage reconstruction of EIP-155's public example.
No keys, signing, signature recovery, RPC calls or transaction submission.
"""
from pathlib import Path
import json, hashlib
RAW='f86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83'
EXPECTED='ec098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a764000080018080'
def decode(blob,at=0):
    lead=blob[at]
    if lead<128: return blob[at:at+1],at+1
    if lead<=183:
        size=lead-128;return blob[at+1:at+1+size],at+1+size
    if lead<=191:
        length=lead-183;size=int.from_bytes(blob[at+1:at+1+length],'big');start=at+1+length
        return blob[start:start+size],start+size
    if lead<=247: start=at+1;end=start+lead-192
    else:
        length=lead-247;size=int.from_bytes(blob[at+1:at+1+length],'big');start=at+1+length;end=start+size
    items=[]
    while start<end:
        item,start=decode(blob,start);items.append(item)
    if start!=end: raise ValueError('Invalid RLP length')
    return items,end
def integer(n): return n.to_bytes((n.bit_length()+7)//8,'big')
def encode(value):
    if isinstance(value,list):
        raw=b''.join(encode(v) for v in value);short,long=192,247
    else:
        raw=value
        if len(raw)==1 and raw[0]<128:return raw
        short,long=128,183
    if len(raw)<=55:return bytes([short+len(raw)])+raw
    length=integer(len(raw));return bytes([long+len(length)])+length+raw
def main():
    blob=bytes.fromhex(RAW);fields,end=decode(blob)
    assert end==len(blob) and len(fields)==9
    v=int.from_bytes(fields[6],'big');chain=(v-35)//2;parity=(v-35)%2
    preimage=encode(fields[:6]+[integer(chain),b'',b''])
    assert preimage.hex()==EXPECTED
    variants={str(chain_id):'0x'+encode(fields[:6]+[integer(chain_id),b'',b'']).hex() for chain_id in [1,61]}
    report={'source':'https://eips.ethereum.org/EIPS/eip-155','evidence_checked':'2026-11-27','scope':'Public specification fixture; not a user transaction','legacy_v':str(v),'derived_chain_id':str(chain),'derived_parity':str(parity),'signed_example_raw':'0x'+RAW,'reconstructed_signing_preimage':'0x'+preimage.hex(),'matches_specification_preimage':True,'unsigned_domain_variants':variants,'preimages_differ':variants['1']!=variants['61'],'sha256_of_reconstructed_preimage':hashlib.sha256(preimage).hexdigest(),'signature_verified':False,'transaction_broadcast':False,'limitations':'RLP reconstruction only. SHA-256 here is an artifact fingerprint, not the Ethereum signing hash. No Keccak or signature verification is claimed.'}
    out=Path(__file__).resolve().parent/'eip155-reproduction.json';out.write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
if __name__=='__main__':main()
