EIP-55 Checksums: How One Capital Letter Catches a Typo in Python
You are copying an Ethereum address by hand from a screenshot. Forty hex characters, and at position nine you type 4 instead of 3. Nothing about 0x5aAeb6054F3E94C9b9A09f33669435E7Ef1BeAed looks wrong. It has the right le
You are copying an Ethereum address by hand from a screenshot. Forty hex characters, and at position nine you type 4 instead of 3. Nothing about 0x5aAeb6054F3E94C9b9A09f33669435E7Ef1BeAed looks wrong. It has the right length, it starts with 0x, every character is valid hex. A library that validates EIP-55 rejects it before anything is signed, and the reason is the strange mix of capital and small letters you probably never paid attention to.
That mix is a checksum. It was proposed in EIP-55 by Vitalik Buterin and Alex Van de Sande on January 14, 2016 (EIP-55), and it costs nothing: the address is the same 20 bytes whether you write it in capitals, in lowercase, or in the checksummed mix. This post builds a checker in plain Python with no packages, including the Keccak-256 hash it needs, and then measures how many typos actually slip through.
Why case is free space
An Ethereum address is 20 bytes, written as 40 hex characters. Hex does not care about case: 0xAbC and 0xabc are the same number, so 0x5aaeb... and 0x5AAEB... point to the same account. That means the case of each letter is a bit of information nobody was using. EIP-55 puts it to work.
The rule from the spec, in short:
- Take the address as 40 lowercase hex characters, without
0x. - Hash that ASCII string with Keccak-256.
- Walk both strings in parallel. If the address character is a letter
atofand the hash character at the same position is8or higher, write the letter in uppercase. Otherwise leave it lowercase.
Digits have no case, so they carry no check. On average an address has 15 letters, which gives "15 check bits per address", and the spec estimates that a mistyped address passes with probability 0.0247%. We will test that number below.
Keccak-256 is not hashlib.sha3_256
This is the first trap. Python ships hashlib.sha3_256, and Ethereum documentation calls its hash "SHA3" in many places. They are not the same function. Ethereum uses the original Keccak submission, and the final FIPS 202 standard changed the padding byte. Same input, different output:
>>> import hashlib
>>> hashlib.sha3_256(b"").hexdigest()
'a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a'
>>> keccak256(b"").hex() # defined below
'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'
If you build the checksum on sha3_256, the mixed-case addresses you produce will fail validation in any wallet that checks EIP-55. In a real project install a library that has Keccak (pycryptodome or eth-utils). For learning, the permutation fits on one screen.
A standard-library Keccak-256
Keccak keeps a 5 by 5 grid of 64-bit lanes. Each of 24 rounds mixes columns (theta), rotates lanes (rho), moves them around the grid (pi), applies a non-linear step (chi) and XORs in a round constant (iota):
RC = [
0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
]
ROT = [
[0, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61],
[28, 55, 25, 21, 56], [27, 20, 39, 8, 14],
]
MASK = (1 << 64) - 1
def rol(x, n):
return ((x << n) | (x >> (64 - n))) & MASK if n else x
def keccak_f(a):
for rc in RC:
c = [a[x][0] ^ a[x][1] ^ a[x][2] ^ a[x][3] ^ a[x][4] for x in range(5)]
d = [c[(x - 1) % 5] ^ rol(c[(x + 1) % 5], 1) for x in range(5)]
a = [[a[x][y] ^ d[x] for y in range(5)] for x in range(5)]
b = [[0] * 5 for _ in range(5)]
for x in range(5):
for y in range(5):
b[y][(2 * x + 3 * y) % 5] = rol(a[x][y], ROT[x][y])
a = [[b[x][y] ^ (~b[(x + 1) % 5][y] & b[(x + 2) % 5][y])
for y in range(5)] for x in range(5)]
a[0][0] ^= rc
return a
The sponge around it absorbs the message in 136-byte blocks (the rate for a 256-bit output) and squeezes out 32 bytes. The single line that differs from SHA3-256 is the padding byte:
def keccak256(data: bytes) -> bytes:
rate = 136
msg = bytearray(data)
msg.append(0x01) # Keccak padding. FIPS 202 SHA3-256 uses 0x06 here.
while len(msg) % rate:
msg.append(0)
msg[-1] |= 0x80
a = [[0] * 5 for _ in range(5)]
for off in range(0, len(msg), rate):
block = msg[off:off + rate]
for i in range(rate // 8):
lane = int.from_bytes(block[8 * i:8 * i + 8], "little")
a[i % 5][i // 5] ^= lane
a = keccak_f(a)
return b"".join(a[i % 5][i // 5].to_bytes(8, "little") for i in range(4))
The checksum itself
With a hash in hand, EIP-55 is a few lines. Note that we hash the lowercase hex text, not the 20 raw bytes. That detail is in the spec and is easy to get wrong:
def to_checksum(address: str) -> str:
hex_addr = address.lower().removeprefix("0x")
if len(hex_addr) != 40 or any(ch not in "0123456789abcdef" for ch in hex_addr):
raise ValueError(f"not a 20-byte hex address: {address!r}")
digest = keccak256(hex_addr.encode("ascii")).hex()
return "0x" + "".join(
ch.upper() if ch in "abcdef" and int(digest[i], 16) >= 8 else ch
for i, ch in enumerate(hex_addr)
)
The spec lists eight test addresses: two in all caps, two in all lowercase (addresses whose checksum happens to produce one case) and four normal mixed ones. All eight round-trip:
vectors = [
"0x52908400098527886E0F7030069857D2E4169EE7",
"0x8617E340B3D01FA5F11F306F4090FD50E238070D",
"0xde709f2102306220921060314715629080e2fb77",
"0x27b1fdb04752bbc536007a920d24acb045561c26",
"0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed",
"0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359",
"0xdbF03B407c01E7cD3CBea99509d93f8DDDC8C6FB",
"0xD1220A0cf47c7B9Be7A2E6BA89F429762e7b9aDb",
]
for v in vectors:
assert to_checksum(v) == v
print("all 8 EIP-55 vectors pass")
Validation needs one more decision. An address written entirely in lowercase or entirely in uppercase carries no checksum at all, so you cannot say it is valid, only that it is unverified:
import sys
def check(address: str) -> str:
body = address.removeprefix("0x")
if body == body.lower() or body == body.upper():
return "no checksum (single case), cannot verify"
if to_checksum(address) == address:
return "valid checksum"
return "BAD CHECKSUM, do not send"
if __name__ == "__main__":
for addr in sys.argv[1:]:
print(f"{addr} {check(addr)}")
Running it on the correct address, a version where only the case of the last letter changed, and the lowercase form:
$ python -I eip55.py 0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed 0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD 0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed
0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed valid checksum
0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAeD BAD CHECKSUM, do not send
0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed no checksum (single case), cannot verify
The typo from the opening, 0x5aAeb6054F..., also comes back as BAD CHECKSUM.
How many typos get through?
The spec says 0.0247%. Here is a quick experiment: generate random addresses, checksum them, change one character to a different hex digit typed in lowercase, and count how often the result still validates.
import random
rng = random.Random(55)
trials, passed = 20000, 0
for _ in range(trials):
addr = to_checksum("".join(rng.choice("0123456789abcdef") for _ in range(40)))
body = list(addr[2:])
i = rng.randrange(40)
old = body[i].lower()
body[i] = rng.choice([c for c in "0123456789abcdef" if c != old])
typed = "0x" + "".join(body)
if to_checksum(typed) == typed:
passed += 1
print(f"single-char typos that still pass: {passed}/{trials}")
single-char typos that still pass: 8/20000
That is 0.04%, the same order as the spec's estimate. The misses are addresses with few letters: fewer letters, fewer check bits. A caveat: this pure-Python Keccak needs about a millisecond per hash, so the 20,000 trials take around half a minute. Fine for a tutorial, too slow for a backend that checks thousands of addresses per second.
What a checksum does not protect you from
EIP-55 catches accidents. It does nothing against an attacker, because a scammer's address is a perfectly valid address and comes with a perfectly valid checksum. In address poisoning, the attacker generates an address with the same first and last characters as one you use and plants it in your history. You copy it, the checksum passes, the money leaves. We wrote a detector for that case in an earlier post.
Two practical rules follow from the code above:
- Treat a single-case address as unverified, not as valid. Many explorers and exchanges print lowercase, and an app that accepts it silently has thrown the protection away.
- Store and display the checksummed form everywhere you control, so that the next person who retypes it gets the check for free.
We keep plain-language guides on wallet types and safe storage habits at Token Alphabet, and the open source wallet tools we trust are listed in awesome-crypto-wallets. If you turn this checker into a small package or a pre-send hook, a pull request adding it there is welcome.
Does your app reject a bad checksum, warn on lowercase input, or accept everything that is valid hex?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.