Blockchain foundations in Go · 5 MIN READ

Ethereum addresses: 20 bytes of Keccak-256, an EIP-55 checksum and strict input validation

Derive an address from a public key, produce and check EIP-55 checksums, and validate user-supplied addresses, including the zero address.

An Ethereum address is neither a public key nor a name. It is the last 20 bytes of the Keccak-256 hash of an uncompressed public key, written as 40 hex digits. Those digits carry no error detection unless their letter case follows EIP-55, so a validator has to decide what it accepts before value moves: the format, the checksum, and whether the zero address can ever be a destination.

blockchain · A MAP OF THE IDEA

  1. Keccak-256 of X and Y
  2. Keep the last 20 bytes
  3. Render with Address.Hex
  4. Parse input strictly

Useful when

  • Mixed-case checksums catch almost all typos at no extra length.
  • One parser at each boundary makes the policy reviewable.

Watch out

  • HexToAddress pads, crops and never fails.
  • Lowercase input and missing JSON fields carry no protection.

Implementation & operation cost: One Keccak-256 per check and a documented decision about lowercase input, applied the same way at every boundary.

01

From public key to address

The signatures lesson recovered a public key: an uncompressed secp256k1 point serialized as 0x04 followed by the 32-byte X and Y coordinates. Ethereum drops the 0x04 prefix, hashes the 64 coordinate bytes with Keccak-256 and keeps the last 20 bytes. crypto.PubkeyToAddress does exactly that, and so does go-ethereum's transaction sender recovery. The mapping is one-way, so an address never yields a key, and not every address belongs to a key at all: a contract's address comes from its creator's address and nonce (CREATE) or from a salt and the init code hash (CREATE2), and nothing in the 20 bytes says which kind you are looking at. Ask the chain for the code at that address when the difference matters.

02

Derive, checksum and validate in one program

The program derives the test key's address by hand and compares it with PubkeyToAddress, re-implements the EIP-55 rule and compares it with common.Address.Hex, then feeds six inputs through parseAddress. That validator requires the 0x prefix and exactly 40 hex digits, enforces the checksum when the input mixes cases, and rejects the zero address. The last three lines show library behavior that regularly surprises reviewers.

go
package main

import (
	"bytes"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"strings"

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/crypto"
)

var (
	errFormat   = errors.New("want 0x followed by 40 hex digits")
	errChecksum = errors.New("mixed-case input fails the EIP-55 checksum")
	errZero     = errors.New("zero address is not a valid destination")
)

// eip55 re-implements the checksum to show the rule: uppercase a letter when
// the matching nibble of keccak256(lowercase hex) is 8 or more.
func eip55(a common.Address) string {
	lower := hex.EncodeToString(a[:])
	h := crypto.Keccak256([]byte(lower))
	out := []byte(lower)
	for i, c := range out {
		nibble := h[i/2] >> 4
		if i%2 == 1 {
			nibble = h[i/2] & 0x0f
		}
		if c >= 'a' && nibble >= 8 {
			out[i] = c - 32
		}
	}
	return "0x" + string(out)
}

func parseAddress(s string) (common.Address, error) {
	if len(s) != 42 || !strings.HasPrefix(s, "0x") || !common.IsHexAddress(s) {
		return common.Address{}, errFormat
	}
	a := common.HexToAddress(s)
	body := s[2:]
	mixed := body != strings.ToLower(body) && body != strings.ToUpper(body)
	if mixed && s != a.Hex() {
		return common.Address{}, errChecksum
	}
	if a == (common.Address{}) {
		return common.Address{}, errZero
	}
	return a, nil
}

func main() {
	// TEST KEY ONLY: fixed bytes, never funded.
	key, _ := crypto.ToECDSA(bytes.Repeat([]byte{1}, 32))
	pub := crypto.FromECDSAPub(&key.PublicKey) // 0x04 || X || Y, 65 bytes
	derived := common.BytesToAddress(crypto.Keccak256(pub[1:])[12:])
	fmt.Println("pubkey bytes:", len(pub), "derived == PubkeyToAddress:", derived == crypto.PubkeyToAddress(key.PublicKey))
	fmt.Println("lowercase:", strings.ToLower(derived.Hex()))
	fmt.Println("EIP-55:   ", derived.Hex(), "manual matches:", eip55(derived) == derived.Hex())

	good := derived.Hex()
	lower := strings.ToLower(good)
	flipped := good[:9] + strings.ToLower(good[9:10]) + good[10:] // E written as e
	typo := lower[:41] + "0"                                      // last digit mistyped, all lowercase
	cases := []struct{ label, in string }{
		{"checksummed", good}, {"lowercase", lower}, {"one case flipped", flipped},
		{"lowercase typo", typo}, {"too short", "0x1a642f"}, {"zero", "0x" + strings.Repeat("0", 40)},
	}
	for _, c := range cases {
		a, err := parseAddress(c.in)
		if err != nil {
			fmt.Printf("%-16s reject: %v\n", c.label, err)
			continue
		}
		fmt.Printf("%-16s accept, signer: %v\n", c.label, a == derived)
	}

	m, _ := common.NewMixedcaseAddressFromString(strings.ToLower(good))
	fmt.Println("MixedcaseAddress.ValidChecksum(lowercase):", m.ValidChecksum())

	var req struct {
		To common.Address `json:"to"`
	}
	err := json.Unmarshal([]byte(`{"amount":"5"}`), &req)
	fmt.Println("missing field decodes to zero address:", err == nil && req.To == common.Address{})
	fmt.Println("HexToAddress(\"0xzz\") is zero:", common.HexToAddress("0xzz") == common.Address{})
}
Read the code

eip55 hashes the 40 lowercase ASCII hex characters, not the 20 raw bytes, and uppercases a letter when its nibble in that hash is 8 or more; digits never change. The flipped input differs from the signer only in the case of one letter and is rejected. The lowercase typo is accepted and names a different account, because lowercase input carries no checksum. MixedcaseAddress.ValidChecksum compares the input with Hex(), so it reports false for any all-lowercase input. A JSON body without a to field, and HexToAddress given non-hex text, both produce the zero address with no error.

03

What EIP-55 protects and what it cannot

EIP-55 stores its checksum in letter case: each of the letters a to f is uppercase exactly when the matching nibble of the hash is 8 or more. An address carries about 15 check bits on average, and the EIP estimates that a mistyped checksummed address passes by accident about 0.0247% of the time. An all-lowercase or all-uppercase string has no case information, so EIP-55 treats it as unchecked, and most wallets accept it. Your service has to choose: accept lowercase from machines that produced it, such as an RPC response or your own database, but for destinations a person typed or pasted, require the checksummed form or add a confirmation step. Always display addresses with Hex() so that whatever people copy is checksummed. A few networks use EIP-1191, which mixes the chain ID into the checksum, so a valid case pattern there can fail plain EIP-55.

04

Parsing is not validation

common.HexToAddress never fails. It strips an optional prefix, decodes what hex it can, and pads or crops to 20 bytes, so 0x1234 becomes an address ending in 1234 and garbage becomes the zero address; the abi-calls lesson already warned that it converts rather than validates. common.IsHexAddress checks length and digits but accepts input without a prefix or with 0X and ignores case. Address.UnmarshalJSON requires the prefix and 40 digits but not the checksum, and a missing field leaves the zero value. Put one parser like parseAddress at every boundary: HTTP handlers, CLI flags and configuration. Give the zero address an explicit policy, too. ERC-20 tokens emit it as the sender of a mint and conventionally as the recipient of a burn, and many token contracts reject transfers to it, so as a payout destination it almost always means a missing value rather than an intent.

05

Test the validator at its edges

Use the mixed-case vectors published in EIP-55, such as 0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed, as known answers for both Hex() and your parser. Add cases for a missing prefix, an uppercase 0X prefix, 39 and 41 digits, non-hex characters, surrounding whitespace, an all-uppercase body, the zero address, and a lowercase address with one digit changed, which passes format checks and must then be caught by an allow-list or a confirmation step downstream. Store addresses as 20 raw bytes or as the canonical Hex() string, never in whatever case the user typed, so that equality checks and unique indexes do not depend on letter case.

TAKE THIS WITH YOU

Derive addresses with PubkeyToAddress, display them with Hex(), and validate input with one explicit parser that checks prefix, length, the checksum on mixed case and the zero address.

Check your understanding

Why can an EIP-55 validator not catch a mistyped digit in an all-lowercase address?

Go to the source

Progress stays in this browser. No account needed.