{"guides":[],"hints":[{"hint":"The example encodes an address into an ABI word without contacting a node or signing anything.","lessonID":"blockchain.abi-calls","nuance":"No. Simulation observes selected state; inclusion, changed state, fees, nonce and execution can differ when a transaction is actually processed."},{"hint":"Look at what UTXOSet.Apply does to each input once validation passes.","lessonID":"blockchain.accounts-utxo","nuance":"The first spend deleted genesis:0 and created new outputs. A UTXO ledger keeps no per-account nonce or stored balance; the second spend names a coin that no longer exists."},{"hint":"Where does EIP-55 keep its check bits?","lessonID":"blockchain.addresses-checksums","nuance":"EIP-55 hides the checksum in letter case. An all-lowercase string has no case information, so it is valid unchecked hex, and a changed digit simply names a different 20-byte account."},{"hint":"One of the two caps starts to bind when the base fee is high.","lessonID":"blockchain.eip1559-fees","nuance":"The base fee is burned and the tip is whatever room the cap leaves: with a 62 gwei cap and a 61.5 gwei base fee, only 0.5 gwei of the 2 gwei tip reaches the producer."},{"hint":"The second block at height 11 does not extend the current canonical tip, so the model demands reconciliation.","lessonID":"blockchain.events-finality","nuance":"No. Backfill from a persisted canonical checkpoint with overlap, deduplicate and reconcile reorgs before advancing durable or irreversible effects."},{"hint":"The sample produces 1000000000000000001 exactly, without a floating-point intermediate.","lessonID":"blockchain.exact-units","nuance":"Reject it under the explicit precision policy instead of silently rounding or converting through float64; network, token and units must be verified."},{"hint":"Only one tag is backed by an economic penalty rather than an expectation.","lessonID":"blockchain.fork-choice","nuance":"latest can reorg, and safe reflects the consensus client's current view of justified checkpoints. A finalized block can only be reverted if at least a third of all stake is slashed."},{"hint":"Compare what the attacker can recompute with what the attacker cannot reach.","lessonID":"blockchain.hash-chains","nuance":"The tip hash commits to all of history. Relinking produces a different tip, so a copy held outside the attacker's reach no longer matches even though every internal link checks out."},{"hint":"Think about what a 64-byte leaf made of two sibling hashes would hash to.","lessonID":"blockchain.merkle-proofs","nuance":"Without prefixes, H(left || right) is also the leaf hash of the 64-byte string left || right, so a shorter forged list reaches the same root. Prefixes make leaf and node inputs disjoint; the odd-leaf rule is a separate fix."},{"hint":"The bytes and the signature are identical to the accepted login; only server state has changed.","lessonID":"blockchain.message-signing","nuance":"Recovery is stateless and succeeds again for the same bytes. Only the nonce record, deleted when the first login committed, distinguishes the replay from the original."},{"hint":"Repeating the same business intent reuses its reservation rather than consuming another nonce.","lessonID":"blockchain.nonces-outcomes","nuance":"No. The original outcome may be unknown. Reconcile the existing signed intent, hash and nonce before choosing a policy-controlled retry or replacement."},{"hint":"The table assigns a role rather than claiming one universal package is best.","lessonID":"blockchain.packages","nuance":"No. It provides RPC access to a node. Choose libraries by protocol and role, and separately verify network identity, data trust and release compatibility."},{"hint":"The winning nonce is inside the header; what does Valid do with it?","lessonID":"blockchain.proof-of-work","nuance":"The verifier does not search. It hashes the header, including the found nonce, once and compares the integer with the target. That asymmetry is what makes proof of work usable."},{"hint":"Ask what the transaction hash is computed from.","lessonID":"blockchain.raw-transactions","nuance":"Transaction.Hash is keccak256 of the signed EIP-2718 envelope, so it is fixed before broadcast and lets the service look up a receipt after a timeout instead of signing again with a new nonce."},{"hint":"Anyone can deploy a contract that emits the same event signature.","lessonID":"blockchain.receipts-logs","nuance":"Topic 0 only names the event shape. The emitting address proves which contract spoke, the topic count separates ERC-20 from ERC-721, and a reverted receipt has no effects to credit."},{"hint":"Think about what happens to a transaction hash when two byte strings mean the same value.","lessonID":"blockchain.rlp-encoding","nuance":"0x05 and 0x820005 would decode to the same integer but hash differently. Accepting both gives one transaction two identities, and nodes that disagree about acceptance split consensus."},{"hint":"The client calls a local HTTP test server and preserves the JSON-RPC request ID in its reply.","lessonID":"blockchain.rpc-boundaries","nuance":"No. Verify the expected chain ID and supply an explicit context/budget for each operation; classify transport, RPC and chain outcomes separately."},{"hint":"Think about what names one chain state unambiguously, even across forks.","lessonID":"blockchain.rpc-providers","nuance":"A block number can name different blocks on different forks and latest moves between calls; a hash names one block, and a provider that lacks it fails loudly instead of answering from another state."},{"hint":"Recovery succeeds for both; look for the function that compares s with half the curve order.","lessonID":"blockchain.signatures","nuance":"Both signatures recover the same key, so the address comparison passes. ValidateSignatureValues(v, r, s, true) applies EIP-2's s <= N/2 rule, the same check go-ethereum's transaction signers run before recovery."},{"hint":"The unsigned intent carries a chain ID, nonce, destination, value and distinct fee fields.","lessonID":"blockchain.signing-boundaries","nuance":"No. They are distinct hash functions. Use the protocol’s reviewed primitives and validate domain, chain and replay policy separately from signature recovery."}],"id":"blockchain","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"blockchain.packages","designGuide":{"cautions":["An SDK’s address parser does not prove a network, token or contract is legitimate.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Choose protocol + role","Review module/API","Pin compatible versions","Test contracts + limits"],"ratings":[],"strengths":["Distinguish RPC applications, transaction tooling and consensus/application frameworks.","Makes the owner and the failure boundary explicit."]},"hint":"The table assigns a role rather than claiming one universal package is best.","id":"blockchain.packages","introduction":"Go is used for blockchain nodes and infrastructure, but a backend that reads balances is not the same system as a validator or a signing service. Start with the target network and the operation you must perform. Prefer the protocol’s maintained libraries, inspect their module boundaries and pin a reviewed release. Adding every blockchain SDK increases dependencies without proving correctness.","nuance":"No. It provides RPC access to a node. Choose libraries by protocol and role, and separately verify network identity, data trust and release compatibility.","objective":"Distinguish RPC applications, transaction tooling and consensus/application frameworks.","question":"How should a Go library be selected for a blockchain integration?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient","https://github.com/btcsuite/btcd","https://github.com/cosmos/cosmos-sdk","https://github.com/cometbft/cometbft"],"reviewAnswer":"Protocol + operation determine the library","reviewPrompt":"Blockchain package choice","sections":[{"body":"Go is used for blockchain nodes and infrastructure, but a backend that reads balances is not the same system as a validator or a signing service. Start with the target network and the operation you must perform. Prefer the protocol’s maintained libraries, inspect their module boundaries and pin a reviewed release. Adding every blockchain SDK increases dependencies without proving correctness.","title":"The contract and the failure"},{"body":"For Ethereum applications, use ethclient for typed RPC and accounts/abi or generated bindings for contract encoding; inspect core/types for transactions and receipts. For Bitcoin, distinguish wire/chaincfg from rpcclient and the reviewed btcec, btcutil and txscript module majors. Cosmos SDK builds chain applications and has release-specific compatible modules; it is not a universal Ethereum client. Check the chosen release’s go.mod and official migration guide.","code":"package main\n\nimport \"fmt\"\n\nfunc main() {\n\troles := []struct{ job, packages string }{\n\t\t{\"Ethereum RPC\", \"go-ethereum/ethclient, rpc\"},\n\t\t{\"Ethereum encoding\", \"go-ethereum/common, core/types, accounts/abi\"},\n\t\t{\"Bitcoin tooling\", \"btcsuite/btcd: wire, chaincfg, rpcclient; reviewed versioned submodules\"},\n\t\t{\"Application-specific chains\", \"cosmos-sdk with its compatible CometBFT and SDK modules\"},\n\t\t{\"Exact units and keys\", \"math/big; protocol signing library; external key custody\"},\n\t}\n\tfor _, role := range roles {\n\t\tfmt.Printf(\"%s -> %s\\n\", role.job, role.packages)\n\t}\n}","language":"go","title":"Work through the example","walkthrough":"The table assigns a role rather than claiming one universal package is best. go-ethereum common/types/abi are subpackages of its module; btcsuite also has separately versioned modules, whose current major path matters. The example is a selection map, not an installation of these libraries or a blockchain runtime in GopherForge."},{"body":"An SDK’s address parser does not prove a network, token or contract is legitimate. Package APIs, consensus rules, chain IDs and deployed contract ABIs all matter. Pin versions, run dependency verification and vulnerability analysis, and review transitive requirements. Full node, networking, signing and database workflows belong in your native development environment; these readings add no guest sockets, wallet or investment functionality to the app.","title":"Production decisions"},{"body":"Run these commands in a disposable native Go module after choosing a reviewed release. Version listing requires network access; it is not permission to upgrade a production dependency blindly. Keep the selected module version and toolchain in source control.","code":"go list -m -versions github.com/ethereum/go-ethereum\ngo list -m -json github.com/ethereum/go-ethereum\ngo mod why -m github.com/ethereum/go-ethereum\ngo mod verify\n# With the reviewed govulncheck tool installed:\ngovulncheck ./...","language":"bash","title":"Inspect a dependency before adopting it","walkthrough":"The first command lists candidate releases, the second explains the selected version, and why identifies why the module is needed. Verification and vulnerability analysis answer different questions; neither proves business invariants or validates an RPC endpoint."},{"body":"Does importing ethclient turn an application into an Ethereum consensus validator? No. It provides RPC access to a node. Choose libraries by protocol and role, and separately verify network identity, data trust and release compatibility. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Distinguish RPC applications, transaction tooling and consensus/application frameworks. No. It provides RPC access to a node. Choose libraries by protocol and role, and separately verify network identity, data trust and release compatibility.","title":"Go in blockchain: choose packages by the protocol and the job","unitID":"blockchain","wrongAnswers":["Every blockchain uses the same Go SDK","An RPC client is itself a consensus validator"]},{"conceptTag":"blockchain.rpc-boundaries","designGuide":{"cautions":["Providers can impose batch, rate and historical-range limits.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Configure expected chain","Dial owned client","Bound typed RPC","Validate result context"],"ratings":[],"strengths":["Use an explicit RPC client, operation deadline and expected chain identity.","Makes the owner and the failure boundary explicit."]},"hint":"The client calls a local HTTP test server and preserves the JSON-RPC request ID in its reply.","id":"blockchain.rpc-boundaries","introduction":"An Ethereum RPC endpoint is an external dependency with latency, availability and trust limits. A successful TCP connection does not prove that the endpoint serves the intended chain or that every call will finish. Use typed clients, time-bounded operations and an expected chain ID configured by the application. Keep node credentials out of logs and never treat RPC data as authenticated business authority by default.","nuance":"No. Verify the expected chain ID and supply an explicit context/budget for each operation; classify transport, RPC and chain outcomes separately.","objective":"Use an explicit RPC client, operation deadline and expected chain identity.","question":"Does a successful DialContext prove both the chain identity and deadlines for future calls?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient","https://pkg.go.dev/github.com/ethereum/go-ethereum/rpc","https://geth.ethereum.org/docs/interacting-with-geth/rpc"],"reviewAnswer":"Check chain ID and pass per-operation budgets","reviewPrompt":"Ethereum RPC boundary","sections":[{"body":"An Ethereum RPC endpoint is an external dependency with latency, availability and trust limits. A successful TCP connection does not prove that the endpoint serves the intended chain or that every call will finish. Use typed clients, time-bounded operations and an expected chain ID configured by the application. Keep node credentials out of logs and never treat RPC data as authenticated business authority by default.","title":"The contract and the failure"},{"body":"Share an appropriately configured client for its intended lifetime, close it at the owning boundary and pass a fresh operation context to each RPC. Distinguish a transport timeout, JSON-RPC error, missing object and on-chain revert. Read related state at a consistent block/hash where required and report archive/pruning limitations rather than silently substituting latest state.","code":"package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/ethclient\"\n)\n\nfunc main() {\n\t// Local mock of eth_chainId; no public network or real wallet is used.\n\tnode := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar q struct {\n\t\t\tID     json.RawMessage `json:\"id\"`\n\t\t\tMethod string          `json:\"method\"`\n\t\t}\n\t\tif err := json.NewDecoder(r.Body).Decode(&q); err != nil {\n\t\t\thttp.Error(w, \"bad request\", 400)\n\t\t\treturn\n\t\t}\n\t\tif q.Method != \"eth_chainId\" {\n\t\t\thttp.Error(w, \"unsupported\", 400)\n\t\t\treturn\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t_ = json.NewEncoder(w).Encode(map[string]any{\"jsonrpc\": \"2.0\", \"id\": q.ID, \"result\": \"0x539\"})\n\t}))\n\tdefer node.Close()\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tdefer cancel()\n\tclient, err := ethclient.DialContext(ctx, node.URL)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\tchain, err := client.ChainID(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(chain.String()) // 1337: the local mock chain\n}","language":"go","title":"Work through the example","walkthrough":"The client calls a local HTTP test server and preserves the JSON-RPC request ID in its reply. The hex result becomes an exact big.Int value. Production code must compare that value with the configured expected chain, rather than accepting any reachable endpoint. A dial context does not become the deadline for every later operation."},{"body":"Providers can impose batch, rate and historical-range limits. Bound concurrency and response sizes, classify retryable reads and treat a transaction-send timeout as an unknown outcome. A single RPC provider is also a trust and availability assumption. Test wrong chain ID, unavailable history, malformed responses, cancellation and provider disagreement in a local or test-network environment.","title":"Production decisions"},{"body":"Does a successful DialContext prove both the chain identity and deadlines for future calls? No. Verify the expected chain ID and supply an explicit context/budget for each operation; classify transport, RPC and chain outcomes separately. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Use an explicit RPC client, operation deadline and expected chain identity. No. Verify the expected chain ID and supply an explicit context/budget for each operation; classify transport, RPC and chain outcomes separately.","title":"Ethereum RPC: verify the chain and bound every operation","unitID":"blockchain","wrongAnswers":["DialContext sets every future call deadline","Any reachable RPC endpoint is the right chain"]},{"conceptTag":"blockchain.exact-units","designGuide":{"cautions":["Symbols are not unique token identifiers, and decimal metadata can be surprising or unsupported.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Verify token + scale","Bound decimal input","Parse integer units","Test precision boundaries"],"ratings":[],"strengths":["Convert validated decimal text to bounded integer base units with an explicit scale.","Makes the owner and the failure boundary explicit."]},"hint":"The sample produces 1000000000000000001 exactly, without a floating-point intermediate.","id":"blockchain.exact-units","introduction":"Token amounts frequently exceed the exact integer range of float64, even when the human-readable value looks small. Converting through a float before math/big permanently loses information. Parse text under an explicit decimal-scale policy, reject unsupported precision and preserve the integer base-unit value. Token metadata is input to validate, not an instruction to allocate unbounded memory.","nuance":"Reject it under the explicit precision policy instead of silently rounding or converting through float64; network, token and units must be verified.","objective":"Convert validated decimal text to bounded integer base units with an explicit scale.","question":"Which representation path preserves a token amount according to its declared decimal scale?","references":["https://pkg.go.dev/math/big#Int","https://pkg.go.dev/encoding/json#Number","https://ethereum.org/en/developers/docs/standards/tokens/erc-20/"],"reviewAnswer":"Validated decimal text -> exact bounded integer","reviewPrompt":"Token base units","sections":[{"body":"Token amounts frequently exceed the exact integer range of float64, even when the human-readable value looks small. Converting through a float before math/big permanently loses information. Parse text under an explicit decimal-scale policy, reject unsupported precision and preserve the integer base-unit value. Token metadata is input to validate, not an instruction to allocate unbounded memory.","title":"The contract and the failure"},{"body":"Obtain and verify the correct token contract, network and decimal metadata, then define supported scales and input length. Keep amounts in base units for arithmetic and serialize large integers as exact strings where the wire contract needs them. math/big.Int methods mutate the receiver; use Set for independent copies before sharing values between owners.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n\t\"strings\"\n)\n\nfunc units(text string, scale uint8) (*big.Int, error) {\n\tif scale > 36 || len(text) > 80 {\n\t\treturn nil, fmt.Errorf(\"input budget\")\n\t}\n\tp := strings.Split(text, \".\")\n\tif len(p) > 2 || p[0] == \"\" {\n\t\treturn nil, fmt.Errorf(\"decimal required\")\n\t}\n\tfrac := \"\"\n\tif len(p) == 2 {\n\t\tfrac = p[1]\n\t\tif frac == \"\" {\n\t\t\treturn nil, fmt.Errorf(\"empty fraction\")\n\t\t}\n\t}\n\tif len(frac) > int(scale) {\n\t\treturn nil, fmt.Errorf(\"precision exceeds scale\")\n\t}\n\tdigits := p[0] + frac\n\tfor _, c := range digits {\n\t\tif c < '0' || c > '9' {\n\t\t\treturn nil, fmt.Errorf(\"digits only\")\n\t\t}\n\t}\n\tvalue, ok := new(big.Int).SetString(digits+strings.Repeat(\"0\", int(scale)-len(frac)), 10)\n\tif !ok || value.BitLen() > 256 {\n\t\treturn nil, fmt.Errorf(\"amount out of range\")\n\t}\n\treturn value, nil\n}\nfunc main() { n, err := units(\"1.000000000000000001\", 18); fmt.Println(n, err) }","language":"go","title":"Work through the example","walkthrough":"The sample produces 1000000000000000001 exactly, without a floating-point intermediate. It rejects signs, exponents, excess fractional precision and values outside its stated 256-bit policy. The 36-decimal cap is this example’s application budget, not a claim that every token uses at most that scale."},{"body":"Symbols are not unique token identifiers, and decimal metadata can be surprising or unsupported. Do not round away an extra fractional digit silently. Test zero, leading zeros, maximum value, too many digits, unsupported scale and the same symbol on different networks. Fees, token transfers and fiat conversions are different quantities with separately defined units and rounding policies.","title":"Production decisions"},{"body":"An amount has one more fractional digit than the supported token scale. What should this parser do? Reject it under the explicit precision policy instead of silently rounding or converting through float64; network, token and units must be verified. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Convert validated decimal text to bounded integer base units with an explicit scale. Reject it under the explicit precision policy instead of silently rounding or converting through float64; network, token and units must be verified.","title":"Token amounts: parse exact base units without float64","unitID":"blockchain","wrongAnswers":["Convert via float64 then restore precision","Assume all tokens have 18 decimals"]},{"conceptTag":"blockchain.abi-calls","designGuide":{"cautions":["A method name, ABI file or token symbol does not authenticate deployed code, particularly with upgradeable contracts.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Verify chain + contract","Pack reviewed ABI","Select state for read","Validate decoded result"],"ratings":[],"strengths":["Distinguish ABI packing, read simulation, signed transactions and deployment identity.","Makes the owner and the failure boundary explicit."]},"hint":"The example encodes an address into an ABI word without contacting a node or signing anything.","id":"blockchain.abi-calls","introduction":"An ABI describes how to encode a call and decode its result. It does not prove that the target address has the expected code or that a read result will remain true in a future transaction. An eth_call evaluates a call against a selected chain state without committing it. State-changing execution requires a separate signed transaction lifecycle and can fail even after a successful simulation.","nuance":"No. Simulation observes selected state; inclusion, changed state, fees, nonce and execution can differ when a transaction is actually processed.","objective":"Distinguish ABI packing, read simulation, signed transactions and deployment identity.","question":"A simulated call succeeds. Does that prove a later signed transaction will succeed?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/accounts/abi","https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient#Client.CallContractAtHash","https://geth.ethereum.org/docs/developers/dapp-developer/native-bindings-v2"],"reviewAnswer":"Encoding + selected-state simulation, not a commit","reviewPrompt":"ABI and eth_call","sections":[{"body":"An ABI describes how to encode a call and decode its result. It does not prove that the target address has the expected code or that a read result will remain true in a future transaction. An eth_call evaluates a call against a selected chain state without committing it. State-changing execution requires a separate signed transaction lifecycle and can fail even after a successful simulation.","title":"The contract and the failure"},{"body":"For reads, use ethclient.CallContract with an explicit block, or an appropriate hash-pinned call when reproducibility requires it. Decode with the same ABI and validate the returned shape. Generated bindings can make the Go surface clearer, but review the generated version and deployed contract compatibility; the newer bind/v2 API is not interchangeable with older binding examples.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/accounts/abi\"\n\t\"github.com/ethereum/go-ethereum/common\"\n)\n\nfunc main() {\n\tschema := `[{\"type\":\"function\",\"name\":\"balanceOf\",\"stateMutability\":\"view\",\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}]}]`\n\tparsed, err := abi.JSON(strings.NewReader(schema))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\traw := \"0x0000000000000000000000000000000000000001\"\n\tif !common.IsHexAddress(raw) {\n\t\tpanic(\"invalid address\")\n\t}\n\tdata, err := parsed.Pack(\"balanceOf\", common.HexToAddress(raw))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(len(data)) // 4-byte selector + one 32-byte ABI word = 36\n}","language":"go","title":"Work through the example","walkthrough":"The example encodes an address into an ABI word without contacting a node or signing anything. HexToAddress is used only after validation, since conversion alone is not an input validator. The encoded bytes must still be paired with a verified chain, contract address and reviewed ABI before a native RPC call."},{"body":"A method name, ABI file or token symbol does not authenticate deployed code, particularly with upgradeable contracts. A successful simulation is not a promise about inclusion, fees or future state. Test malformed return data, wrong contract/network, a changed implementation, a reverted call and unavailable historical state. Keep signing policy outside a generic ABI helper.","title":"Production decisions"},{"body":"A simulated call succeeds. Does that prove a later signed transaction will succeed? No. Simulation observes selected state; inclusion, changed state, fees, nonce and execution can differ when a transaction is actually processed. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Distinguish ABI packing, read simulation, signed transactions and deployment identity. No. Simulation observes selected state; inclusion, changed state, fees, nonce and execution can differ when a transaction is actually processed.","title":"Contract ABI: encoding is not permission and eth_call is not a transaction","unitID":"blockchain","wrongAnswers":["ABI packing authorizes a transaction","A successful eth_call guarantees later inclusion"]},{"conceptTag":"blockchain.nonces-outcomes","designGuide":{"cautions":["A send timeout is not proof that the transaction was rejected.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Stable business intent","Reserve nonce durably","Sign + record identity","Send then reconcile"],"ratings":[],"strengths":["Coordinate transaction intent and account nonce allocation before retrying a send.","Makes the owner and the failure boundary explicit."]},"hint":"Repeating the same business intent reuses its reservation rather than consuming another nonce.","id":"blockchain.nonces-outcomes","introduction":"Two Go workers can read the same pending nonce and sign conflicting transactions. A process-local mutex helps only while one process owns the account; it does not coordinate replicas or survive a crash. Give each business intent a stable identity, persist its nonce and signed transaction identity under one ownership protocol, and reconcile unknown send outcomes before allocating new work.","nuance":"No. The original outcome may be unknown. Reconcile the existing signed intent, hash and nonce before choosing a policy-controlled retry or replacement.","objective":"Coordinate transaction intent and account nonce allocation before retrying a send.","question":"SendTransaction timed out. Is allocating a fresh nonce and sending the transfer again safe?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient#Client.PendingNonceAt","https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types","https://ethereum.org/en/developers/docs/transactions/"],"reviewAnswer":"Persist intent + reservation and reconcile sends","reviewPrompt":"Account nonce owner","sections":[{"body":"Two Go workers can read the same pending nonce and sign conflicting transactions. A process-local mutex helps only while one process owns the account; it does not coordinate replicas or survive a crash. Give each business intent a stable identity, persist its nonce and signed transaction identity under one ownership protocol, and reconcile unknown send outcomes before allocating new work.","title":"The contract and the failure"},{"body":"Distinguish prepared, submitted, pending, included, reverted and finalized states. An inclusion receipt with failed status is not a successful business effect. EIP-1559 fee cap, priority fee, gas limit and value have different meanings. A replacement may use the same nonce but a different transaction hash and policy-approved fees; keep the business intent stable and record the replacement chain.","code":"package main\n\nimport \"fmt\"\n\ntype Allocator struct {\n\tnext     uint64\n\treserved map[string]uint64\n}\n\nfunc (a *Allocator) Reserve(intent string) uint64 {\n\tif nonce, ok := a.reserved[intent]; ok {\n\t\treturn nonce\n\t}\n\tnonce := a.next\n\ta.next++\n\ta.reserved[intent] = nonce\n\treturn nonce\n}\nfunc main() {\n\t// Single-owner model: the durable multi-process implementation is separate.\n\ta := Allocator{next: 42, reserved: map[string]uint64{}}\n\tfmt.Println(a.Reserve(\"invoice-7\"), a.Reserve(\"invoice-7\"), a.Reserve(\"invoice-8\")) // 42 42 43\n}","language":"go","title":"Work through the example","walkthrough":"Repeating the same business intent reuses its reservation rather than consuming another nonce. The model assumes one owner and intentionally does not persist or sign transactions. A production allocator must atomically store intent and reservation, prevent concurrent owners from diverging and reconcile reservations after restart or account activity outside the service."},{"body":"A send timeout is not proof that the transaction was rejected. Retrying with a fresh nonce can repeat a transfer; blindly retrying the same underpriced transaction may not solve inclusion. PendingNonceAt is an observation, not a distributed reservation. Test concurrent intents, duplicate requests, external account activity, fee replacement, receipt absence, reorg and restart between signing and send.","title":"Production decisions"},{"body":"SendTransaction timed out. Is allocating a fresh nonce and sending the transfer again safe? No. The original outcome may be unknown. Reconcile the existing signed intent, hash and nonce before choosing a policy-controlled retry or replacement. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Coordinate transaction intent and account nonce allocation before retrying a send. No. The original outcome may be unknown. Reconcile the existing signed intent, hash and nonce before choosing a policy-controlled retry or replacement.","title":"Nonces, fees and unknown outcomes: one durable owner per account","unitID":"blockchain","wrongAnswers":["Each worker independently trusts PendingNonceAt","A send timeout proves the transfer failed"]},{"conceptTag":"blockchain.signing-boundaries","designGuide":{"cautions":["Do not invent cryptographic signing or log seed phrases for debugging.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Build unsigned intent","Validate policy + domain","Delegate key custody","Record approved outcome"],"ratings":[],"strengths":["Validate transaction intent before delegating signing to an explicitly owned key service.","Makes the owner and the failure boundary explicit."]},"hint":"The unsigned intent carries a chain ID, nonce, destination, value and distinct fee fields.","id":"blockchain.signing-boundaries","introduction":"A signing key is authority, not an ordinary configuration string. An RPC URL, ABI helper or generic retry function should not automatically receive it. Separate construction and policy validation from key custody, bind transactions to the intended chain, and record what was approved without logging private keys or seed material. Read-only blockchain work does not require a signer at all.","nuance":"No. They are distinct hash functions. Use the protocol’s reviewed primitives and validate domain, chain and replay policy separately from signature recovery.","objective":"Validate transaction intent before delegating signing to an explicitly owned key service.","question":"Which boundary should surround construction and signing of a blockchain transaction?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/crypto","https://geth.ethereum.org/docs/tools/clef/introduction","https://eips.ethereum.org/EIPS/eip-712"],"reviewAnswer":"Validate intent; isolate key custody and replay policy","reviewPrompt":"Signing boundary","sections":[{"body":"A signing key is authority, not an ordinary configuration string. An RPC URL, ABI helper or generic retry function should not automatically receive it. Separate construction and policy validation from key custody, bind transactions to the intended chain, and record what was approved without logging private keys or seed material. Read-only blockchain work does not require a signer at all.","title":"The contract and the failure"},{"body":"Use reviewed protocol signing libraries and choose custody appropriate to the threat model, such as a tightly scoped external signer, keystore or hardware-backed process. Plan key rotation, backup, access control and audit records. Off-chain signed messages need domain separation, intended action, expiry and replay protection too; an address recovered from a signature does not automatically prove authorization for every action.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/types\"\n)\n\nfunc main() {\n\tto := common.HexToAddress(\"0x0000000000000000000000000000000000000001\")\n\ttx := types.NewTx(&types.DynamicFeeTx{ChainID: big.NewInt(1337), Nonce: 7, GasTipCap: big.NewInt(1), GasFeeCap: big.NewInt(2), Gas: 21000, To: &to, Value: big.NewInt(1)})\n\t// Unsigned local teaching intent; no key, signer or broadcast is used.\n\tfmt.Println(tx.ChainId(), tx.Nonce(), tx.Value())\n}","language":"go","title":"Work through the example","walkthrough":"The unsigned intent carries a chain ID, nonce, destination, value and distinct fee fields. Constructing it does not authorize or broadcast anything, and the tiny fee values are illustration only. A signer boundary must validate the actual chain, destination, function arguments, amount and fee ceilings against an explicit policy before signing."},{"body":"Do not invent cryptographic signing or log seed phrases for debugging. Ethereum’s historical Keccak-256 and standardized SHA3-256 are different functions; substituting one silently changes hashes. Chain-bound transaction signatures do not solve every cross-contract or off-chain replay. Test rejection of wrong chain, modified destination, excessive fees, duplicate intent and an unavailable signer without sending real funds.","title":"Production decisions"},{"body":"Can Ethereum Keccak-256 be replaced by standard SHA3-256 because both output 256 bits? No. They are distinct hash functions. Use the protocol’s reviewed primitives and validate domain, chain and replay policy separately from signature recovery. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Validate transaction intent before delegating signing to an explicitly owned key service. No. They are distinct hash functions. Use the protocol’s reviewed primitives and validate domain, chain and replay policy separately from signature recovery.","title":"Signing policy: bind the chain and keep key custody separate","unitID":"blockchain","wrongAnswers":["A recovered address grants every permission","SHA3-256 can replace Ethereum Keccak-256"]},{"conceptTag":"blockchain.events-finality","designGuide":{"cautions":["A receipt or one observed block is not universal finality.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"blockchain","flow":["Read canonical checkpoint","Backfill bounded overlap","Apply idempotent projection","Reconcile hash + finality"],"ratings":[],"strengths":["Persist canonical checkpoints and reconcile removed or missing events before final effects.","Makes the owner and the failure boundary explicit."]},"hint":"The second block at height 11 does not extend the current canonical tip, so the model demands reconciliation.","id":"blockchain.events-finality","introduction":"A WebSocket subscription is a live notification channel, not a durable ledger cursor. A process can disconnect, a provider can drop a slow subscriber and a chain can reorganize recently observed blocks. Store a checkpoint that includes chain identity and block hash, backfill a bounded range after reconnect and make the projection’s rollback or rebuild behavior explicit.","nuance":"No. Backfill from a persisted canonical checkpoint with overlap, deduplicate and reconcile reorgs before advancing durable or irreversible effects.","objective":"Persist canonical checkpoints and reconcile removed or missing events before final effects.","question":"After reconnecting, can an indexer continue from only the next live WebSocket event?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient#Client.FilterLogs","https://geth.ethereum.org/docs/interacting-with-geth/rpc/pubsub","https://ethereum.org/developers/docs/consensus-mechanisms/pos/#finality"],"reviewAnswer":"Backfill, canonical hash, reversible projection","reviewPrompt":"Reorg-safe event indexing","sections":[{"body":"A WebSocket subscription is a live notification channel, not a durable ledger cursor. A process can disconnect, a provider can drop a slow subscriber and a chain can reorganize recently observed blocks. Store a checkpoint that includes chain identity and block hash, backfill a bounded range after reconnect and make the projection’s rollback or rebuild behavior explicit.","title":"The contract and the failure"},{"body":"Use FilterLogs for bounded backfill and SubscribeFilterLogs for live delivery where supported. Record chain ID, block hash/number, transaction hash and log index as required by the projection. Treat removed logs as a signal to reconcile; reconnect with overlap and deduplicate. Bound queues and scan ranges, and checkpoint only after the corresponding durable effect is safe to replay.","code":"package main\n\nimport \"fmt\"\n\ntype Block struct {\n\tHeight       uint64\n\tHash, Parent string\n}\n\nfunc appendBlock(chain []Block, b Block) ([]Block, error) {\n\tif len(chain) > 0 {\n\t\ttip := chain[len(chain)-1]\n\t\tif b.Height != tip.Height+1 || b.Parent != tip.Hash {\n\t\t\treturn chain, fmt.Errorf(\"reconcile canonical ancestor before append\")\n\t\t}\n\t}\n\treturn append(chain, b), nil\n}\nfunc main() {\n\tchain := []Block{{Height: 10, Hash: \"A10\", Parent: \"A9\"}}\n\tchain, _ = appendBlock(chain, Block{Height: 11, Hash: \"A11\", Parent: \"A10\"})\n\t_, err := appendBlock(chain, Block{Height: 11, Hash: \"B11\", Parent: \"A10\"})\n\tfmt.Println(err) // replacement is not silently appended\n}","language":"go","title":"Work through the example","walkthrough":"The second block at height 11 does not extend the current canonical tip, so the model demands reconciliation. It is not a full fork-choice algorithm. A real indexer locates the common ancestor, reverses or rebuilds affected projection state and checkpoints atomically before continuing along the new canonical branch."},{"body":"A receipt or one observed block is not universal finality. Finality guarantees and acceptable confirmation policy depend on the network, consensus state and business consequence. Do not permanently credit an irreversible external effect solely from an unfinalized subscription event. Test a missed block, duplicate event, removed log, competing hash at one height, crash during projection update and provider history limits.","title":"Production decisions"},{"body":"After reconnecting, can an indexer continue from only the next live WebSocket event? No. Backfill from a persisted canonical checkpoint with overlap, deduplicate and reconcile reorgs before advancing durable or irreversible effects. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Persist canonical checkpoints and reconcile removed or missing events before final effects. No. Backfill from a persisted canonical checkpoint with overlap, deduplicate and reconcile reorgs before advancing durable or irreversible effects.","title":"Index events through disconnects and reorgs, not just the happy subscription","unitID":"blockchain","wrongAnswers":["A WebSocket subscription is a durable cursor","One receipt guarantees universal finality"]},{"conceptTag":"blockchain.hash-chains","designGuide":{"cautions":["Without a trusted tip, a rewritten chain verifies cleanly.","Re-serializing JSON before hashing breaks honest data."],"cost":"One hash per block to write and to verify, an encoding you can never change casually, and a separate place to keep the trusted tip.","family":"blockchain","flow":["Encode block canonically","Hash with SHA-256","Verify links from genesis","Compare tip with anchor"],"ratings":[],"strengths":["Any edit to history changes the tip hash.","Verification is linear and needs only the standard library."]},"hint":"Compare what the attacker can recompute with what the attacker cannot reach.","id":"blockchain.hash-chains","introduction":"A blockchain's first job is evidence, not consensus: if a past record changes, the change must show. Each block stores the hash of its predecessor, so editing one block breaks the link that points at it. That guarantee holds only when every party hashes the same bytes for the same block, and only when the newest hash is kept somewhere the editor cannot rewrite.","nuance":"The tip hash commits to all of history. Relinking produces a different tip, so a copy held outside the attacker's reach no longer matches even though every internal link checks out.","objective":"Link blocks with SHA-256 over a canonical byte encoding, verify the chain from genesis and report the first link that breaks.","question":"An attacker edits an old block and recomputes every later hash so that all links verify again. What still exposes the edit?","references":["https://pkg.go.dev/crypto/sha256#Sum256","https://developer.bitcoin.org/reference/block_chain.html","https://www.rfc-editor.org/rfc/rfc8785"],"reviewAnswer":"A trusted copy of the tip hash from before the edit","reviewPrompt":"What exposes a relinked chain?","sections":[{"body":"A database row or a log line can be updated in place, and nothing about its neighbors changes. A hash pointer removes that silence. Block n stores H(block n-1), where H is SHA-256, a function for which no one knows how to find two different inputs with the same output. Change one byte of an old block and its hash changes, so the pointer stored in the next block no longer matches. This is tamper evidence, not tamper prevention: the bytes can still be edited, but a verifier notices. The rest of this unit adds the other pieces in order: Merkle trees commit to many transactions at once, signatures say who authorized them, proof of work makes extending the chain expensive, and fork choice decides which extension counts.","title":"Why a stored hash exposes an edit"},{"body":"The program defines a block as a height, the previous block's hash and a payload. encode turns a block into bytes with a fixed field order, big-endian fixed-width integers and a length prefix in front of the variable payload; hash is sha256.Sum256 over exactly those bytes. firstBrokenLink checks every block against its predecessor and returns the first height where either the height sequence or the hash pointer fails. The run records the tip, edits an old payload, and then plays an attacker who rewrites every later pointer.","code":"package main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n)\n\ntype Block struct {\n\tHeight uint64\n\tPrev   [32]byte\n\tData   string\n}\n\n// encode is the canonical byte form: fixed-width fields first, then a\n// length-prefixed payload, so two different blocks never share bytes.\nfunc encode(b Block) []byte {\n\tbuf := binary.BigEndian.AppendUint64(nil, b.Height)\n\tbuf = append(buf, b.Prev[:]...)\n\tbuf = binary.BigEndian.AppendUint32(buf, uint32(len(b.Data)))\n\treturn append(buf, b.Data...)\n}\n\nfunc hash(b Block) [32]byte { return sha256.Sum256(encode(b)) }\n\nfunc build(payloads ...string) []Block {\n\tvar chain []Block\n\tvar prev [32]byte // genesis points at the all-zero hash\n\tfor i, p := range payloads {\n\t\tb := Block{Height: uint64(i), Prev: prev, Data: p}\n\t\tchain = append(chain, b)\n\t\tprev = hash(b)\n\t}\n\treturn chain\n}\n\n// firstBrokenLink returns the height of the first block that does not commit\n// to its predecessor, or -1 when every link holds.\nfunc firstBrokenLink(chain []Block) int {\n\tfor i := 1; i < len(chain); i++ {\n\t\tif chain[i].Height != chain[i-1].Height+1 || chain[i].Prev != hash(chain[i-1]) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n\nfunc short(h [32]byte) string { return hex.EncodeToString(h[:4]) }\n\nfunc main() {\n\tchain := build(\"genesis\", \"alice->bob:5\", \"bob->carol:2\", \"carol->dave:1\")\n\ttrustedTip := hash(chain[len(chain)-1])\n\tfmt.Println(\"links ok:\", firstBrokenLink(chain) == -1, \"tip:\", short(trustedTip))\n\n\tchain[1].Data = \"alice->bob:500\"\n\tfmt.Println(\"after edit, first broken link at height\", firstBrokenLink(chain))\n\n\tfor i := 2; i < len(chain); i++ {\n\t\tchain[i].Prev = hash(chain[i-1])\n\t}\n\ttip := hash(chain[len(chain)-1])\n\tfmt.Println(\"relinked:\", firstBrokenLink(chain) == -1, \"tip:\", short(tip))\n\tfmt.Println(\"matches trusted tip:\", tip == trustedTip)\n}","language":"go","title":"Build and verify a chain with crypto/sha256","walkthrough":"build starts from the all-zero hash for genesis and feeds each block's hash into the next block. After the payload at height 1 changes, height 2 is the first block whose Prev no longer equals hash(chain[1]), so the verifier reports 2 rather than a bare false. Rewriting Prev at heights 2 and 3 makes every link consistent again, so the chain on its own looks valid; only the comparison with the tip recorded before the edit exposes it. The printed values are the first four bytes of each 32-byte digest."},{"body":"The hash covers bytes, not meaning. Two nodes that agree a block says alice pays bob 5 but serialize it differently compute different hashes and then disagree about the whole chain. encode avoids that by construction, and its length prefix also removes ambiguity at field boundaries: without it, a payload \"ab\" followed by a field \"c\" and a payload \"a\" followed by \"bc\" would hash identical bytes. Text formats are where this usually goes wrong. JSON objects are unordered, whitespace is insignificant, a number has several spellings (5, 5.0, 5e0), and Go's encoding/json adds its own choices: it sorts map keys, writes struct fields in declaration order and escapes <, > and & unless told otherwise.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n)\n\nfunc main() {\n\t// One logical transfer, three byte strings a JSON parser treats as equal.\n\tforms := []string{\n\t\t`{\"from\":\"alice\",\"to\":\"bob\",\"amount\":5}`,\n\t\t`{\"amount\":5,\"from\":\"alice\",\"to\":\"bob\"}`,\n\t\t`{\"amount\": 5, \"from\": \"alice\", \"to\": \"bob\"}`,\n\t}\n\tfor _, f := range forms {\n\t\tsum := sha256.Sum256([]byte(f))\n\t\tfmt.Println(hex.EncodeToString(sum[:4]), f)\n\t}\n\n\t// encoding/json sorts map keys, but it also escapes HTML characters.\n\tplain, _ := json.Marshal(map[string]any{\"to\": \"bob\", \"memo\": \"a<b\", \"amount\": 5})\n\tvar buf bytes.Buffer\n\tenc := json.NewEncoder(&buf)\n\tenc.SetEscapeHTML(false)\n\t_ = enc.Encode(map[string]any{\"to\": \"bob\", \"memo\": \"a<b\", \"amount\": 5})\n\tfmt.Println(string(plain))\n\tfmt.Println(string(bytes.TrimSpace(buf.Bytes())))\n}","language":"go","title":"Pick one byte encoding and never let it drift","walkthrough":"The three literal strings decode to the same object yet print three different digests, 8cd4d93c, 560a0696 and 39350022, so a verifier that re-serializes before hashing accepts or rejects data depending on which form it happens to produce. json.Marshal sorts the map keys and writes the memo as a\\u003cb; an Encoder with SetEscapeHTML(false) writes a<b and appends a newline, trimmed here. Both outputs are valid JSON, and neither is a hashing format unless one canonicalization scheme, such as RFC 8785, is applied everywhere."},{"body":"The relinking step in the first program is the realistic attack. Whoever can rewrite one block can usually recompute every later hash in microseconds. What the chain buys you is that one 32-byte value, the tip hash, commits to the entire history, so protecting history reduces to protecting that value. Publish it, sign it, store it in a system with different administrators, or make producing a replacement expensive, which is what proof of work and proof of stake do later in this unit. Audit logs, release manifests and blockchains share this structure and differ in who is trusted to produce or hold the tip. When verification fails, report the first broken height and treat every later block as unverified until it is checked against a trusted tip again; an operator needs to know which record and which neighbor disagree.","title":"Anchor the tip, or the chain proves nothing"},{"body":"Check in known-answer vectors: a fixed block and its expected digest, so a refactor that reorders fields or changes an integer width fails a test instead of silently forking your history. Mutate each field in turn and assert that the hash changes. Fuzz pairs of blocks with go test -fuzz and assert that different blocks never encode to the same bytes, which catches a missing length prefix. Keep a single encode function shared by writer and verifier; two implementations of one format is how nodes come to disagree. Test the verifier on an empty chain, a lone genesis block, a height gap and an edited genesis. SHA-256 appears here because it is in the standard library; Ethereum uses Keccak-256, a different function, as the signing-boundaries lesson explains.","title":"Test the encoding like a consensus rule"}],"takeaway":"Hash one canonical byte encoding of each block, verify every link from genesis, report the first break, and keep the trusted tip hash out of reach of anyone who can edit the data.","title":"Hash chains: every block commits to the exact bytes of the block before it","unitID":"blockchain-foundations","wrongAnswers":["The first broken link that the verifier reports","Nothing, because consistent links prove integrity"]},{"conceptTag":"blockchain.merkle-proofs","designGuide":{"cautions":["Duplicating odd nodes lets two different lists share a root.","A root taken from the same untrusted response proves nothing."],"cost":"About 2n hashes to build the tree and log2(n) per proof, plus a tree shape that becomes a frozen consensus rule once roots are published.","family":"blockchain","flow":["Hash leaves with 0x00","Hash nodes with 0x01","Collect one sibling a level","Recompute root from index"],"ratings":[],"strengths":["A proof costs about log2(n) hashes, not the whole block.","Verification needs only the leaf, index, size and a trusted root."]},"hint":"Think about what a 64-byte leaf made of two sibling hashes would hash to.","id":"blockchain.merkle-proofs","introduction":"A block header cannot carry every transaction, but it can carry one 32-byte Merkle root that commits to all of them. A client that trusts the header can then check that a particular transaction is included from a handful of sibling hashes instead of the whole block. The tree shape and hashing rules are consensus rules, and two classic mistakes let different transaction lists produce the same root.","nuance":"Without prefixes, H(left || right) is also the leaf hash of the 64-byte string left || right, so a shorter forged list reaches the same root. Prefixes make leaf and node inputs disjoint; the odd-leaf rule is a separate fix.","objective":"Build a domain-separated Merkle tree, generate and verify inclusion proofs, and explain the duplicate-leaf and second-preimage pitfalls.","question":"A Merkle tree hashes leaves as H(data) and interior nodes as H(left || right). Which attack do distinct leaf and node prefixes stop?","references":["https://www.rfc-editor.org/rfc/rfc6962","https://github.com/bitcoin/bitcoin/blob/master/src/consensus/merkle.cpp","https://developer.bitcoin.org/reference/block_chain.html","https://eips.ethereum.org/EIPS/eip-1186"],"reviewAnswer":"So no interior node can pose as a leaf","reviewPrompt":"Why prefix Merkle leaves?","sections":[{"body":"The previous lesson chained blocks. Inside a block the problem is different: thousands of transactions, and a wallet or indexer that wants to check one of them without downloading the rest. A Merkle tree hashes each transaction into a leaf, then hashes pairs of nodes level by level until one root remains, and the header stores only that root. To prove leaf i, the prover sends the sibling at each level on the path from the leaf to the root, and the verifier recomputes the path and compares. For n leaves that is about log2(n) hashes, so 20 hashes cover a million transactions. A proof shows that the leaf is committed by this root; it says nothing about whether the header itself is canonical, which is the job of the chain and fork-choice lessons.","title":"One root for many transactions"},{"body":"The program hashes leaves with a 0x00 prefix and interior nodes with a 0x01 prefix, and promotes a lone last node to the next level unchanged instead of pairing it with a copy of itself. prove collects one sibling per level when one exists; verify walks up from the leaf and uses the claimed index and the tree size to decide, at every level, whether the sibling sits left or right. The second half builds the classic tree, with no prefixes and duplication of the last hash, to show what the two rules prevent.","code":"package main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n)\n\ntype Hash = [32]byte\n\n// Domain separation: a leaf hash can never be confused with an interior node.\nfunc leafHash(data []byte) Hash { return sha256.Sum256(append([]byte{0x00}, data...)) }\n\nfunc nodeHash(l, r Hash) Hash {\n\treturn sha256.Sum256(append(append([]byte{0x01}, l[:]...), r[:]...))\n}\n\n// levels builds the tree bottom-up. A lone last node is promoted unchanged,\n// never paired with a copy of itself.\nfunc levels(leaves [][]byte) [][]Hash {\n\tlevel := make([]Hash, len(leaves))\n\tfor i, d := range leaves {\n\t\tlevel[i] = leafHash(d)\n\t}\n\ttree := [][]Hash{level}\n\tfor len(level) > 1 {\n\t\tvar next []Hash\n\t\tfor i := 0; i < len(level); i += 2 {\n\t\t\tif i+1 < len(level) {\n\t\t\t\tnext = append(next, nodeHash(level[i], level[i+1]))\n\t\t\t} else {\n\t\t\t\tnext = append(next, level[i])\n\t\t\t}\n\t\t}\n\t\ttree = append(tree, next)\n\t\tlevel = next\n\t}\n\treturn tree\n}\n\nfunc root(leaves [][]byte) Hash {\n\tt := levels(leaves)\n\treturn t[len(t)-1][0]\n}\n\nfunc prove(leaves [][]byte, index int) []Hash {\n\tvar proof []Hash\n\tfor _, level := range levels(leaves) {\n\t\tsibling := index ^ 1\n\t\tif sibling < len(level) {\n\t\t\tproof = append(proof, level[sibling])\n\t\t}\n\t\tindex /= 2\n\t}\n\treturn proof\n}\n\n// verify recomputes the root from the leaf, its index and the tree size, so\n// left/right order comes from the claimed position, not from the proof.\nfunc verify(leaf []byte, index, size int, proof []Hash, want Hash) bool {\n\tif index < 0 || index >= size {\n\t\treturn false\n\t}\n\th := leafHash(leaf)\n\tfor n := size; n > 1; n = (n + 1) / 2 {\n\t\tif index%2 == 1 || index+1 < n {\n\t\t\tif len(proof) == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tif index%2 == 1 {\n\t\t\t\th = nodeHash(proof[0], h)\n\t\t\t} else {\n\t\t\t\th = nodeHash(h, proof[0])\n\t\t\t}\n\t\t\tproof = proof[1:]\n\t\t}\n\t\tindex /= 2\n\t}\n\treturn len(proof) == 0 && h == want\n}\n\n// naiveRoot is the classic shape: no prefixes, odd levels duplicate the last hash.\nfunc naiveRoot(leaves [][]byte) Hash {\n\tlevel := make([]Hash, len(leaves))\n\tfor i, d := range leaves {\n\t\tlevel[i] = sha256.Sum256(d)\n\t}\n\tfor len(level) > 1 {\n\t\tif len(level)%2 == 1 {\n\t\t\tlevel = append(level, level[len(level)-1])\n\t\t}\n\t\tvar next []Hash\n\t\tfor i := 0; i < len(level); i += 2 {\n\t\t\tnext = append(next, sha256.Sum256(append(level[i][:], level[i+1][:]...)))\n\t\t}\n\t\tlevel = next\n\t}\n\treturn level[0]\n}\n\nfunc split(s ...string) [][]byte {\n\tout := make([][]byte, len(s))\n\tfor i, v := range s {\n\t\tout[i] = []byte(v)\n\t}\n\treturn out\n}\n\nfunc main() {\n\ttxs := split(\"tx-a\", \"tx-b\", \"tx-c\", \"tx-d\", \"tx-e\")\n\tr := root(txs)\n\tfmt.Println(\"root:\", hex.EncodeToString(r[:4]), \"leaves:\", len(txs))\n\n\tproof := prove(txs, 2)\n\tfmt.Println(\"proof for leaf 2:\", len(proof), \"hashes, valid:\", verify(txs[2], 2, len(txs), proof, r))\n\tfmt.Println(\"tampered leaf valid:\", verify([]byte(\"tx-x\"), 2, len(txs), proof, r))\n\tfmt.Println(\"wrong index valid:\", verify(txs[2], 3, len(txs), proof, r))\n\n\tthree, four := split(\"a\", \"b\", \"c\"), split(\"a\", \"b\", \"c\", \"c\")\n\tha, hb := sha256.Sum256([]byte(\"a\")), sha256.Sum256([]byte(\"b\"))\n\thc, hd := sha256.Sum256([]byte(\"c\")), sha256.Sum256([]byte(\"d\"))\n\thonest := split(\"a\", \"b\", \"c\", \"d\")\n\tforged := [][]byte{append(ha[:], hb[:]...), append(hc[:], hd[:]...)}\n\n\tfmt.Println(\"naive [a b c] == [a b c c]:\", naiveRoot(three) == naiveRoot(four))\n\tfmt.Println(\"naive 4 leaves == 2 forged leaves:\", naiveRoot(honest) == naiveRoot(forged))\n\tfmt.Println(\"separated [a b c] == [a b c c]:\", root(three) == root(four))\n\tfmt.Println(\"separated 4 leaves == 2 forged leaves:\", root(honest) == root(forged))\n}","language":"go","title":"Build, prove and verify in Go","walkthrough":"With five leaves, leaf 2 needs three siblings: leaf 3, the hash of leaves 0 and 1, and leaf 4, which was promoted from below. A changed leaf or a claimed index of 3 recomputes a different path and fails. verify derives each direction from index and size instead of trusting flags inside the proof, and it rejects proofs with too few or too many hashes. naiveRoot gives [a b c] and [a b c c] one root and accepts two 64-byte forged leaves built from interior hashes; the separated tree rejects both. Promotion yields the same tree shape as RFC 6962, which splits at the largest power of two below n."},{"body":"Bitcoin's tree pairs an odd last hash with a copy of itself, so the transaction lists [a, b, c] and [a, b, c, c] produce the same root, exactly as naiveRoot shows. This became CVE-2012-2459. The list with the repeated transaction is an invalid block, but its header hash equals the honest block's. A node that received the mutated version first, rejected it and remembered the header hash as invalid would then refuse the honest block too. Bitcoin Core now detects the mutation while computing the root and treats the block as malformed rather than marking the header invalid, and the comment above its Merkle code warns new designs not to copy the algorithm. In your own trees, promote the lone node or use the RFC 6962 split, and include the leaf count in whatever you sign or publish next to the root.","title":"The duplicate-last-leaf trap"},{"body":"Without domain separation an interior node is SHA-256 of 64 bytes and a leaf is SHA-256 of arbitrary bytes. Anyone who knows two sibling hashes can present their 64-byte concatenation as a leaf, and the shorter, forged list reaches the same root: that is the second-preimage result in the program. Prefixing leaves with 0x00 and nodes with 0x01, as Certificate Transparency does in RFC 6962, makes the two kinds of input disjoint, so no interior node can satisfy a leaf proof. Bitcoin's tree has no such separation, and its known ambiguity around 64-byte transactions follows from that. Ethereum headers use Merkle-Patricia tries for transactions, receipts and state rather than this binary tree, and eth_getProof (EIP-1186) returns account and storage proofs. The principle is the same: verify the proof against a root you already trust, never against a root delivered in the same response.","title":"Separate leaves from interior nodes"},{"body":"Take the root from a header you have already validated. Bind the index and tree size into verification so a proof for one position cannot be replayed for another. Reject proofs that are too long or too short instead of ignoring extra hashes. Hash leaves from their canonical bytes, as in the hash-chain lesson. Test every index for many sizes, including 1 and powers of two plus and minus one; a wrong index; swapped sibling order; truncated and extended proofs; and a leaf whose bytes equal an interior node. Fuzz verify with random proofs and require that it never panics. These tests are cheap: checking every index and every wrong index for all sizes from 1 to 40 runs in well under a second.","title":"Review checklist for proof code"}],"takeaway":"Prefix leaves and interior nodes differently, never duplicate an odd node, and verify a proof from the leaf, its index and the tree size against a root you already trust.","title":"Merkle proofs: show one transaction is in a block with about log2(n) hashes","unitID":"blockchain-foundations","wrongAnswers":["Two lists sharing a root when the last leaf is duplicated","Finding SHA-256 preimages by brute force"]},{"conceptTag":"blockchain.signatures","designGuide":{"cautions":["Recovery returns some key for any digest; compare the address.","SigToPub and Ecrecover accept high-s twins; validate values first."],"cost":"One Keccak-256 and one public-key recovery per verification, plus explicit normalization of v at every boundary that accepts signatures.","family":"blockchain","flow":["Hash the message yourself","Sign the 32-byte digest","Recover and compare address","Reject high-s and bad v"],"ratings":[],"strengths":["The signer is computed, so no public key travels with the data.","Deterministic RFC 6979 nonces make signing reproducible in tests."]},"hint":"Recovery succeeds for both; look for the function that compares s with half the curve order.","id":"blockchain.signatures","introduction":"A hash chain shows that data changed; a signature shows who approved it. Ethereum and Bitcoin use ECDSA over the secp256k1 curve, and Ethereum appends a recovery byte so that a verifier can compute the signer's public key from the signature instead of receiving it. Recovery always produces some key, so the code that matters is the comparison with the address you expected and the checks that reject malleable signatures.","nuance":"Both signatures recover the same key, so the address comparison passes. ValidateSignatureValues(v, r, s, true) applies EIP-2's s <= N/2 rule, the same check go-ethereum's transaction signers run before recovery.","objective":"Sign a Keccak-256 digest with go-ethereum's crypto package, recover and check the signer's address, and enforce the low-s rule on untrusted signatures.","question":"crypto.SigToPub recovers the same signer from a signature (r, s) and its twin (r, N-s). Which check rejects the twin before you trust it?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/crypto#Sign","https://pkg.go.dev/github.com/ethereum/go-ethereum/crypto#ValidateSignatureValues","https://eips.ethereum.org/EIPS/eip-2","https://www.rfc-editor.org/rfc/rfc6979"],"reviewAnswer":"ValidateSignatureValues with homestead true","reviewPrompt":"What rejects a high-s twin?","sections":[{"body":"crypto.Sign returns 65 bytes: r and s, 32 bytes each, followed by a recovery id v of 0 or 1. r and s form an ordinary ECDSA signature; v tells the recovery algorithm which candidate curve point the signer used, so crypto.SigToPub and crypto.Ecrecover return exactly one public key. That is why an Ethereum transaction carries no public key and no from field: the sender is computed from the signature. The byte encoding of v varies by context. Legacy transactions store 27 or 28, EIP-155 transactions store chainID*2+35 or +36, typed transactions store a yParity of 0 or 1, and personal_sign signatures usually end in 27 or 28. Normalize to 0 or 1 at the boundary before calling the crypto package, and leave transaction encodings to the signers in core/types.","title":"What a recoverable signature contains"},{"body":"The program derives a test key from 32 bytes of 0x01, a well-known throwaway value that must never hold funds, and it never contacts a network. It signs a Keccak-256 digest, recovers the public key, then edits the message and recovers again. Finally it builds the mirror-image signature (r, N-s) with the recovery bit flipped, where N is the curve order, and runs it through the checks go-ethereum offers.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math/big\"\n\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\nfunc main() {\n\t// TEST KEY ONLY: fixed bytes, never funded, never used on a real network.\n\tkey, err := crypto.ToECDSA(bytes.Repeat([]byte{1}, 32))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsigner := crypto.PubkeyToAddress(key.PublicKey)\n\tfmt.Println(\"test signer:\", signer.Hex())\n\n\tif _, err := crypto.Sign([]byte(\"not a digest\"), key); err != nil {\n\t\tfmt.Println(\"raw message:\", err)\n\t}\n\n\tdigest := crypto.Keccak256([]byte(\"chain 1337: pay bob 5, nonce 7\"))\n\tsig, err := crypto.Sign(digest, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tagain, _ := crypto.Sign(digest, key)\n\tfmt.Println(\"signature:\", len(sig), \"bytes, v =\", sig[64], \"deterministic:\", bytes.Equal(sig, again))\n\n\tpub, err := crypto.SigToPub(digest, sig)\n\tfmt.Println(\"recovered == signer:\", err == nil && crypto.PubkeyToAddress(*pub) == signer)\n\n\tedited := crypto.Keccak256([]byte(\"chain 1337: pay bob 500, nonce 7\"))\n\tother, err := crypto.SigToPub(edited, sig)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"edited message: no error, recovered == signer:\", crypto.PubkeyToAddress(*other) == signer)\n\n\t// Build the high-s twin (r, N-s) with the recovery bit flipped.\n\tn := crypto.S256().Params().N\n\tr := new(big.Int).SetBytes(sig[:32])\n\ts := new(big.Int).SetBytes(sig[32:64])\n\ttwinS := new(big.Int).Sub(n, s)\n\ttwin := make([]byte, 65)\n\tcopy(twin, sig[:32])\n\ttwinS.FillBytes(twin[32:64])\n\ttwin[64] = sig[64] ^ 1\n\n\ttwinPub, err := crypto.SigToPub(digest, twin)\n\tfmt.Println(\"twin recovers signer:\", err == nil && crypto.PubkeyToAddress(*twinPub) == signer)\n\tpubBytes := crypto.FromECDSAPub(&key.PublicKey)\n\tfmt.Println(\"low-s rule accepts original:\", crypto.ValidateSignatureValues(sig[64], r, s, true),\n\t\t\"twin:\", crypto.ValidateSignatureValues(twin[64], r, twinS, true))\n\tfmt.Println(\"VerifySignature original:\", crypto.VerifySignature(pubBytes, digest, sig[:64]),\n\t\t\"twin:\", crypto.VerifySignature(pubBytes, digest, twin[:64]))\n}","language":"go","title":"Sign and recover with a fixed test key","walkthrough":"crypto.Sign refuses the 12-byte string because it requires exactly 32 bytes, so callers must hash first. Signing the same digest twice yields identical bytes because the nonce is derived from the key and the digest as in RFC 6979, with no random source. SigToPub on the edited digest returns no error and a valid but different public key; only the address comparison catches it. The twin recovers the same signer, so recovery alone does not make signatures unique. ValidateSignatureValues with homestead set to true and VerifySignature both reject the twin because its s is above N/2."},{"body":"ECDSA signs a number smaller than the curve order, so it needs fixed-size input; Ethereum uses Keccak-256 and Bitcoin uses double SHA-256. Size is the smaller reason. The go-ethereum documentation for Sign warns that the hash must not be chosen by an adversary. A service that signs whatever 32 bytes a caller supplies is a signing oracle, and those bytes may be the hash of a transaction that spends the service's funds. Hash your own structured message with a prefix that says what it is: accounts.TextHash implements the EIP-191 prefix \"\\x19Ethereum Signed Message:\\n\" plus the message length, and EIP-712 hashes typed data under a domain. The signing-boundaries lesson covers key custody and domain policy; the rule at the primitive level is that the signer owns the hashing step.","title":"Why you sign a digest, never raw input"},{"body":"For every valid ECDSA signature (r, s), the pair (r, N-s) is also valid for the same key and message. If any part of a system identifies data by the hash of its signed bytes, a third party can flip s and produce a second valid encoding with a different identifier, without the key. Bitcoin suffered this as transaction-ID malleability, and Ethereum's Homestead upgrade (EIP-2) made transactions with s above N/2 invalid. In go-ethereum the rule is crypto.ValidateSignatureValues(v, r, s, homestead), which the transaction signers call before recovering, and VerifySignature also rejects high s. Ecrecover and SigToPub do not, and EIP-2 deliberately left the on-chain ecrecover precompile accepting high s, so contracts must check it too. When you accept signatures from users, for logins or off-chain orders, validate the values yourself and never key a record by signature bytes.","title":"Malleability and the low-s rule"},{"body":"Keep the test key fixed and labeled, and assert known answers: the 0x01-repeated key has the address 0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1, so a regression in key derivation fails at once. Write negative tests for a wrong digest, a wrong expected address, the high-s twin, v outside 0 and 1, r or s equal to zero or N, a 64-byte signature without v and a digest of the wrong length. If you ship builds with and without cgo, run the suite both ways: go-ethereum uses the decred secp256k1 package when cgo is off and libsecp256k1 when it is on, and your checks should not depend on which one recovered the key. Prefer fixed vectors to crypto.GenerateKey in tests so that every failure is reproducible.","title":"Test the verifier, not just the signer"}],"takeaway":"Sign only digests you computed, recover the key and compare its address with the one you expected, and reject high-s or malformed values with ValidateSignatureValues before trusting a signature.","title":"secp256k1 signatures: sign a 32-byte digest, recover the signer and reject high-s twins","unitID":"blockchain-foundations","wrongAnswers":["Comparing the recovered address with the expected one","crypto.Ecrecover, which returns an error for high s"]},{"conceptTag":"blockchain.addresses-checksums","designGuide":{"cautions":["HexToAddress pads, crops and never fails.","Lowercase input and missing JSON fields carry no protection."],"cost":"One Keccak-256 per check and a documented decision about lowercase input, applied the same way at every boundary.","family":"blockchain","flow":["Keccak-256 of X and Y","Keep the last 20 bytes","Render with Address.Hex","Parse input strictly"],"ratings":[],"strengths":["Mixed-case checksums catch almost all typos at no extra length.","One parser at each boundary makes the policy reviewable."]},"hint":"Where does EIP-55 keep its check bits?","id":"blockchain.addresses-checksums","introduction":"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.","nuance":"EIP-55 hides the checksum in letter case. An all-lowercase string has no case information, so it is valid unchecked hex, and a changed digit simply names a different 20-byte account.","objective":"Derive an address from a public key, produce and check EIP-55 checksums, and validate user-supplied addresses, including the zero address.","question":"Why can an EIP-55 validator not catch a mistyped digit in an all-lowercase address?","references":["https://eips.ethereum.org/EIPS/eip-55","https://pkg.go.dev/github.com/ethereum/go-ethereum/common#Address.Hex","https://pkg.go.dev/github.com/ethereum/go-ethereum/crypto#PubkeyToAddress","https://ethereum.org/en/developers/docs/accounts/"],"reviewAnswer":"None; a typo just names another valid address","reviewPrompt":"Lowercase address: checksum?","sections":[{"body":"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.","title":"From public key to address"},{"body":"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.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\nvar (\n\terrFormat   = errors.New(\"want 0x followed by 40 hex digits\")\n\terrChecksum = errors.New(\"mixed-case input fails the EIP-55 checksum\")\n\terrZero     = errors.New(\"zero address is not a valid destination\")\n)\n\n// eip55 re-implements the checksum to show the rule: uppercase a letter when\n// the matching nibble of keccak256(lowercase hex) is 8 or more.\nfunc eip55(a common.Address) string {\n\tlower := hex.EncodeToString(a[:])\n\th := crypto.Keccak256([]byte(lower))\n\tout := []byte(lower)\n\tfor i, c := range out {\n\t\tnibble := h[i/2] >> 4\n\t\tif i%2 == 1 {\n\t\t\tnibble = h[i/2] & 0x0f\n\t\t}\n\t\tif c >= 'a' && nibble >= 8 {\n\t\t\tout[i] = c - 32\n\t\t}\n\t}\n\treturn \"0x\" + string(out)\n}\n\nfunc parseAddress(s string) (common.Address, error) {\n\tif len(s) != 42 || !strings.HasPrefix(s, \"0x\") || !common.IsHexAddress(s) {\n\t\treturn common.Address{}, errFormat\n\t}\n\ta := common.HexToAddress(s)\n\tbody := s[2:]\n\tmixed := body != strings.ToLower(body) && body != strings.ToUpper(body)\n\tif mixed && s != a.Hex() {\n\t\treturn common.Address{}, errChecksum\n\t}\n\tif a == (common.Address{}) {\n\t\treturn common.Address{}, errZero\n\t}\n\treturn a, nil\n}\n\nfunc main() {\n\t// TEST KEY ONLY: fixed bytes, never funded.\n\tkey, _ := crypto.ToECDSA(bytes.Repeat([]byte{1}, 32))\n\tpub := crypto.FromECDSAPub(&key.PublicKey) // 0x04 || X || Y, 65 bytes\n\tderived := common.BytesToAddress(crypto.Keccak256(pub[1:])[12:])\n\tfmt.Println(\"pubkey bytes:\", len(pub), \"derived == PubkeyToAddress:\", derived == crypto.PubkeyToAddress(key.PublicKey))\n\tfmt.Println(\"lowercase:\", strings.ToLower(derived.Hex()))\n\tfmt.Println(\"EIP-55:   \", derived.Hex(), \"manual matches:\", eip55(derived) == derived.Hex())\n\n\tgood := derived.Hex()\n\tlower := strings.ToLower(good)\n\tflipped := good[:9] + strings.ToLower(good[9:10]) + good[10:] // E written as e\n\ttypo := lower[:41] + \"0\"                                      // last digit mistyped, all lowercase\n\tcases := []struct{ label, in string }{\n\t\t{\"checksummed\", good}, {\"lowercase\", lower}, {\"one case flipped\", flipped},\n\t\t{\"lowercase typo\", typo}, {\"too short\", \"0x1a642f\"}, {\"zero\", \"0x\" + strings.Repeat(\"0\", 40)},\n\t}\n\tfor _, c := range cases {\n\t\ta, err := parseAddress(c.in)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%-16s reject: %v\\n\", c.label, err)\n\t\t\tcontinue\n\t\t}\n\t\tfmt.Printf(\"%-16s accept, signer: %v\\n\", c.label, a == derived)\n\t}\n\n\tm, _ := common.NewMixedcaseAddressFromString(strings.ToLower(good))\n\tfmt.Println(\"MixedcaseAddress.ValidChecksum(lowercase):\", m.ValidChecksum())\n\n\tvar req struct {\n\t\tTo common.Address `json:\"to\"`\n\t}\n\terr := json.Unmarshal([]byte(`{\"amount\":\"5\"}`), &req)\n\tfmt.Println(\"missing field decodes to zero address:\", err == nil && req.To == common.Address{})\n\tfmt.Println(\"HexToAddress(\\\"0xzz\\\") is zero:\", common.HexToAddress(\"0xzz\") == common.Address{})\n}","language":"go","title":"Derive, checksum and validate in one program","walkthrough":"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."},{"body":"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.","title":"What EIP-55 protects and what it cannot"},{"body":"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.","title":"Parsing is not validation"},{"body":"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.","title":"Test the validator at its edges"}],"takeaway":"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.","title":"Ethereum addresses: 20 bytes of Keccak-256, an EIP-55 checksum and strict input validation","unitID":"blockchain-foundations","wrongAnswers":["Lowercase input always fails the EIP-55 check","HexToAddress returns an error for the typo"]},{"conceptTag":"blockchain.accounts-utxo","designGuide":{"cautions":["Skipping the duplicate-input check creates money.","Contract-internal transfers never appear as top-level transactions."],"cost":"UTXO indexers maintain an owner index over outputs and spends; account indexers need logs or traces and per-block undo journals.","family":"blockchain","flow":["Check inputs or nonce","Reject before mutating","Apply debits and credits","Derive balances from history"],"ratings":[],"strengths":["UTXO spends are explicit, so provenance and undo are mechanical.","Account balances are a direct read at a chosen block."]},"hint":"Look at what UTXOSet.Apply does to each input once validation passes.","id":"blockchain.accounts-utxo","introduction":"Every ledger must answer one question before it accepts a payment: has this value already been spent? Bitcoin answers with a set of unspent transaction outputs that each transaction consumes and creates. Ethereum answers with a balance and a nonce per account that each transaction updates. Neither stores a wallet's balance as a primary fact; both derive it from accepted history, and that choice shapes every indexer built on top.","nuance":"The first spend deleted genesis:0 and created new outputs. A UTXO ledger keeps no per-account nonce or stored balance; the second spend names a coin that no longer exists.","objective":"Implement minimal UTXO and account ledgers in Go, reject double spends in each, and explain what each model makes easy or hard for an indexer.","question":"In the UTXO ledger, why is a second transaction that spends genesis:0 rejected?","references":["https://developer.bitcoin.org/devguide/transactions.html","https://ethereum.org/en/developers/docs/accounts/","https://developer.bitcoin.org/devguide/block_chain.html","https://eips.ethereum.org/EIPS/eip-20"],"reviewAnswer":"The spent output is deleted from the set","reviewPrompt":"How does UTXO stop a double spend?","sections":[{"body":"In the UTXO model the state is a set of coins: outputs of earlier transactions, each with an amount and a locking condition. Bitcoin locks outputs with scripts; this lesson uses an owner name. A transaction names the exact outputs it consumes, which disappear, and creates new outputs, usually including change back to the sender, and whatever the inputs hold beyond the outputs is the fee. In the account model the state maps each address to an account with a balance, a nonce and, for contracts, code and storage. A transaction says from, to, value and nonce, and the ledger debits one balance and credits another. The double-spend defense follows from the shape: a UTXO ledger deletes the coin, so a second spend names something that no longer exists; an account ledger demands the next nonce, so a replay is stale.","title":"Two shapes of state"},{"body":"UTXOSet.Apply checks every input before it changes anything: each must exist, belong to the signer and appear only once, and the outputs may not exceed the inputs. Ledger.Apply checks the nonce and the balance, then debits, credits and increments the nonce. Owner fields stand in for the signature checks that the signatures lesson covers. After the transfers, the program rebuilds the account state from the history of accepted transfers and compares it with the live state.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// ---- UTXO model: state is the set of unspent outputs ----\n\ntype OutPoint struct {\n\tTx    string\n\tIndex int\n}\n\ntype Output struct {\n\tOwner  string\n\tAmount uint64\n}\n\ntype Tx struct {\n\tID      string\n\tOwner   string // stands in for a signature check on every input\n\tInputs  []OutPoint\n\tOutputs []Output\n}\n\ntype UTXOSet map[OutPoint]Output\n\nfunc (u UTXOSet) Apply(tx Tx) error {\n\tvar in, out uint64\n\tseen := map[OutPoint]bool{}\n\tfor _, op := range tx.Inputs {\n\t\tif seen[op] {\n\t\t\treturn fmt.Errorf(\"input %s:%d used twice\", op.Tx, op.Index)\n\t\t}\n\t\tseen[op] = true\n\t\tprev, ok := u[op]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"input %s:%d is spent or unknown\", op.Tx, op.Index)\n\t\t}\n\t\tif prev.Owner != tx.Owner {\n\t\t\treturn fmt.Errorf(\"input %s:%d not owned by %s\", op.Tx, op.Index, tx.Owner)\n\t\t}\n\t\tin += prev.Amount\n\t}\n\tfor _, o := range tx.Outputs {\n\t\tout += o.Amount\n\t}\n\tif out > in {\n\t\treturn fmt.Errorf(\"outputs %d exceed inputs %d\", out, in)\n\t}\n\t// Validate everything first, then mutate: a rejected tx leaves no trace.\n\tfor _, op := range tx.Inputs {\n\t\tdelete(u, op)\n\t}\n\tfor i, o := range tx.Outputs {\n\t\tu[OutPoint{tx.ID, i}] = o\n\t}\n\treturn nil\n}\n\n// Balance is derived: nobody stores it, an indexer sums unspent outputs.\nfunc (u UTXOSet) Balance(owner string) uint64 {\n\tvar sum uint64\n\tfor _, o := range u {\n\t\tif o.Owner == owner {\n\t\t\tsum += o.Amount\n\t\t}\n\t}\n\treturn sum\n}\n\n// ---- Account model: state is a balance and a nonce per account ----\n\ntype Account struct{ Balance, Nonce uint64 }\n\ntype Transfer struct {\n\tFrom, To      string\n\tAmount, Nonce uint64\n}\n\ntype Ledger map[string]*Account\n\nvar errUnknown = errors.New(\"unknown sender\")\n\nfunc (l Ledger) Apply(t Transfer) error {\n\tfrom := l[t.From]\n\tif from == nil {\n\t\treturn errUnknown\n\t}\n\tif t.Nonce != from.Nonce {\n\t\treturn fmt.Errorf(\"nonce %d rejected, next is %d\", t.Nonce, from.Nonce)\n\t}\n\tif from.Balance < t.Amount {\n\t\treturn fmt.Errorf(\"balance %d < %d\", from.Balance, t.Amount)\n\t}\n\tif l[t.To] == nil {\n\t\tl[t.To] = &Account{}\n\t}\n\tfrom.Balance -= t.Amount\n\tl[t.To].Balance += t.Amount\n\tfrom.Nonce++\n\treturn nil\n}\n\nfunc report(label string, err error) {\n\tif err != nil {\n\t\tfmt.Printf(\"%-28s rejected: %v\\n\", label, err)\n\t\treturn\n\t}\n\tfmt.Printf(\"%-28s ok\\n\", label)\n}\n\nfunc main() {\n\tutxo := UTXOSet{{\"genesis\", 0}: {\"alice\", 50}}\n\tpay := Tx{ID: \"t1\", Owner: \"alice\", Inputs: []OutPoint{{\"genesis\", 0}},\n\t\tOutputs: []Output{{\"bob\", 30}, {\"alice\", 19}}} // 1 unit left over is the fee\n\treport(\"utxo: alice pays bob 30\", utxo.Apply(pay))\n\treport(\"utxo: spend genesis:0 again\", utxo.Apply(Tx{ID: \"t2\", Owner: \"alice\",\n\t\tInputs: []OutPoint{{\"genesis\", 0}}, Outputs: []Output{{\"carol\", 50}}}))\n\treport(\"utxo: same input twice\", utxo.Apply(Tx{ID: \"t3\", Owner: \"alice\",\n\t\tInputs: []OutPoint{{\"t1\", 1}, {\"t1\", 1}}, Outputs: []Output{{\"carol\", 38}}}))\n\tfmt.Println(\"utxo balances: alice\", utxo.Balance(\"alice\"), \"bob\", utxo.Balance(\"bob\"), \"outputs\", len(utxo))\n\n\tgenesis := func() Ledger { return Ledger{\"alice\": {Balance: 50}} }\n\tledger := genesis()\n\tvar history []Transfer\n\tfor _, step := range []struct {\n\t\tlabel string\n\t\tt     Transfer\n\t}{\n\t\t{\"account: alice pays bob 30\", Transfer{\"alice\", \"bob\", 30, 0}},\n\t\t{\"account: replay nonce 0\", Transfer{\"alice\", \"bob\", 30, 0}},\n\t\t{\"account: alice pays carol 30\", Transfer{\"alice\", \"carol\", 30, 1}},\n\t} {\n\t\terr := ledger.Apply(step.t)\n\t\tif err == nil {\n\t\t\thistory = append(history, step.t)\n\t\t}\n\t\treport(step.label, err)\n\t}\n\tfmt.Println(\"account balances: alice\", ledger[\"alice\"].Balance, \"bob\", ledger[\"bob\"].Balance, \"alice nonce\", ledger[\"alice\"].Nonce)\n\n\trebuilt := genesis()\n\tfor _, t := range history {\n\t\tif err := rebuilt.Apply(t); err != nil {\n\t\t\tpanic(err) // accepted history must always replay\n\t\t}\n\t}\n\tfmt.Println(\"rebuilt from history matches:\", *rebuilt[\"alice\"] == *ledger[\"alice\"] && *rebuilt[\"bob\"] == *ledger[\"bob\"])\n}","language":"go","title":"Both ledgers in one program","walkthrough":"Alice spends the 50-unit genesis output into 30 for bob and 19 change, and the missing 1 is the fee. Spending genesis:0 again fails because the first Apply deleted it. A transaction listing t1:1 twice would count those 19 units twice; the seen map rejects it before any sum is used. The account ledger rejects the replayed nonce 0 and then a correctly numbered transfer that exceeds the 20 remaining. UTXO balances are computed on demand by summing unspent outputs, and the account state rebuilt from history matches."},{"body":"The seen map in UTXOSet.Apply looks redundant until you remove it. Without it, one transaction can reference the same output twice, the input sum counts the coin twice, and the ledger creates money. This is not hypothetical: CVE-2018-17144 was a Bitcoin Core bug in which an optimization skipped the duplicate-input check during block validation. Nodes running 0.14 could be crashed by such a block, and versions 0.15.0 to 0.16.2 would have accepted one that inflated the supply. Validate everything first and mutate only after every check passes, as both Apply functions do, so that a rejected transaction leaves no partial state. Production code also range-checks every amount (Bitcoin caps values at 21 million coins) and guards unsigned addition against overflow; this model uses small numbers and leaves that out.","title":"The duplicate-input check is not optional"},{"body":"UTXO makes provenance easy: every payment names its inputs, so tracing where a coin came from is a direct walk, and undoing a block is mechanical, re-adding the outputs it spent and deleting the ones it created, which is what Bitcoin Core's per-block undo data stores. Per-address balance and history are the hard part. An indexer must maintain an owner index over outputs and their spends, and one wallet uses many addresses and change outputs, so a user's balance is an aggregation the chain knows nothing about. The account model makes balances easy, a single read at a chosen block, and hides history: value moves inside contract execution without a top-level transaction, token balances live in contract storage and surface only through logs such as the ERC-20 Transfer event, and full history needs logs or traces. Undoing a block needs the previous value of every key it touched, which the fork-choice lesson uses.","title":"What each model means for an indexer"},{"body":"The rebuild at the end of the program is the most valuable test either model can have: start from genesis, replay accepted history and compare with the live state. Run it in CI against fixtures and periodically against production projections. Add property tests: total supply stays constant apart from issuance and fees in the UTXO model, or explicit mints and burns in the account model; a rejected transaction changes nothing; applying an accepted transaction a second time is rejected. If a projection keeps a balance column, treat it as a cache of a derivation and keep the means to recompute it, because the chain will never tell you the column drifted.","title":"Balances are derived; test that they stay derivable"}],"takeaway":"Validate every input or nonce before mutating state, treat balances as derived from accepted history, and choose indexing structures that match how the model records spends.","title":"Account model versus UTXO: two ledgers and two ways to stop a double spend","unitID":"blockchain-foundations","wrongAnswers":["Its nonce is lower than alice's next nonce","Alice's stored balance is too low for it"]},{"conceptTag":"blockchain.rlp-encoding","designGuide":{"cautions":["rlp.Decode on an arbitrary io.Reader sets no input limit.","Typed decode errors do not match ErrCanonInt with errors.Is."],"cost":"Reflection-based encoding is slower than generated code, and a format without field names makes every schema change a versioning decision.","family":"blockchain","flow":["Map Go types to RLP","Cap raw input size","Decode with stream limit","Bound decoded values"],"ratings":[],"strengths":["One canonical byte form per value keeps hashes and signatures stable.","The decoder rejects non-canonical sizes, integers and trailing data."]},"hint":"Think about what happens to a transaction hash when two byte strings mean the same value.","id":"blockchain.rlp-encoding","introduction":"Ethereum hashes and signs bytes, so every value needs exactly one byte form. On the execution layer that form is Recursive Length Prefix (RLP): transactions, headers and receipts are RLP, and typed transactions are a type byte followed by an RLP payload. RLP encodes byte strings and nested lists and nothing else. go-ethereum's decoder is deliberately strict, because accepting a second spelling of a value means accepting a second hash for it.","nuance":"0x05 and 0x820005 would decode to the same integer but hash differently. Accepting both gives one transaction two identities, and nodes that disagree about acceptance split consensus.","objective":"Encode and decode Go structs with go-ethereum's rlp package, recognize the canonical-form rules, and bound untrusted input before decoding it.","question":"A lax decoder reads the bytes 0x820005 as the integer 5. Why must a consensus decoder reject them?","references":["https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/","https://pkg.go.dev/github.com/ethereum/go-ethereum/rlp","https://pkg.go.dev/github.com/ethereum/go-ethereum/rlp#NewStream"],"reviewAnswer":"One value must have exactly one encoding","reviewPrompt":"Why reject 0x820005 as uint 5?","sections":[{"body":"A single byte below 0x80 is its own encoding. A string of 0 to 55 bytes is 0x80 plus its length followed by the bytes; a longer string is 0xb7 plus the length of the length, the length in big-endian, then the bytes. Lists follow the same pattern from 0xc0 and 0xf7. Integers are not a separate type: they are big-endian strings with no leading zero bytes, so zero is the empty string 0x80. go-ethereum maps Go types onto this. Structs become lists of their exported fields in declaration order, unsigned integers and *big.Int become minimal strings, byte slices and arrays become strings, other slices become lists. Signed integers, floats and maps are refused because they have no canonical form, and a negative big.Int returns an error. The hash-chain lesson made these choices by hand; RLP is the standardized version.","title":"Two kinds of item and a length prefix"},{"body":"The program prints the specification's own examples, round-trips a struct holding an address, a *big.Int and an empty byte slice, then decodes five malformed inputs into a uint64 and one oversized value from a reader with an explicit limit. No network or chain is involved; these are pure functions over bytes.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/big\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/rlp\"\n)\n\ntype Transfer struct {\n\tNonce uint64\n\tTo    common.Address\n\tValue *big.Int\n\tData  []byte\n}\n\nfunc enc(v any) string {\n\tb, err := rlp.EncodeToBytes(v)\n\tif err != nil {\n\t\treturn \"error: \" + err.Error()\n\t}\n\treturn hex.EncodeToString(b)\n}\n\nfunc main() {\n\t// Vectors from the RLP specification.\n\tfmt.Println(\"0:\", enc(uint64(0)), \"15:\", enc(uint64(15)), \"1024:\", enc(uint64(1024)))\n\tfmt.Println(\"dog:\", enc(\"dog\"), \"[cat dog]:\", enc([]string{\"cat\", \"dog\"}), \"[]:\", enc([]uint64{}))\n\tfmt.Println(\"negative big.Int:\", enc(big.NewInt(-1)))\n\n\tt := Transfer{Nonce: 7, To: common.HexToAddress(\"0x00000000000000000000000000000000000000aa\"), Value: big.NewInt(1000)}\n\traw, _ := rlp.EncodeToBytes(t)\n\tfmt.Println(\"transfer:\", len(raw), \"bytes\", hex.EncodeToString(raw[:4])+\"...\")\n\tvar back Transfer\n\terr := rlp.DecodeBytes(raw, &back)\n\tagain, _ := rlp.EncodeToBytes(back)\n\tfmt.Println(\"round trip:\", err == nil && bytes.Equal(raw, again))\n\n\t// Each input below decodes to 5 or 15 in a lax decoder; rlp rejects them.\n\tfor _, in := range []string{\"8105\", \"820005\", \"b80105\", \"0f0f\", \"bbffffffff\"} {\n\t\tb, _ := hex.DecodeString(in)\n\t\tvar n uint64\n\t\tfmt.Printf(\"%-10s %v\\n\", in, rlp.DecodeBytes(b, &n))\n\t}\n\n\t// A stream from the network has no length; cap it explicitly.\n\tbig100 := append([]byte{0xb8, 100}, make([]byte, 100)...)\n\tvar payload []byte\n\ts := rlp.NewStream(io.MultiReader(bytes.NewReader(big100)), 64)\n\tfmt.Println(\"stream limit 64:\", s.Decode(&payload))\n}","language":"go","title":"Encode, decode and feed the decoder bad input","walkthrough":"0 encodes as 80, 15 as the single byte 0f and 1024 as 82 04 00; dog is 83 followed by its ASCII bytes, and [cat dog] is the list header c8 over two strings. The 27-byte transfer starts with da (0xc0 + 26), then 07 for the nonce and 94 for the 20-byte address. Each malformed input breaks a different rule: 8105 wraps a byte that must stand alone, 820005 has a leading zero, b80105 uses the long form for a short string, 0f0f leaves trailing bytes, and bbffffffff claims a 4 GiB string inside 5 bytes. io.MultiReader hides the underlying bytes.Reader, as a network connection would, so only the explicit 64-byte limit stops the 100-byte value, and it does so before allocating."},{"body":"Each rejected input is something a lax decoder could interpret: 8105 and 820005 as the integer 5, b80105 as the one-byte string 05. If a node accepted them, one transaction would have several byte forms and therefore several hashes. A node that accepted a form and a node that rejected it would disagree about a block's validity, which is a consensus split. The property that protects everyone is a bijection: decoding b succeeds only if encoding the result gives back b. go-ethereum's Stream enforces it with ErrCanonSize for a size that should have used a shorter form, ErrCanonInt for leading zeros and, in DecodeBytes, ErrMoreThanOneValue for trailing data. Struct decoding also rejects too few or too many list elements unless trailing fields carry the optional or tail tags.","title":"Why consensus decoders refuse non-canonical bytes"},{"body":"An RLP header can claim a length up to 2^64-1, and a naive decoder allocates what the header says. DecodeBytes, and NewStream over a bytes.Reader, bytes.Buffer or strings.Reader, know the input length and return ErrValueTooLarge for larger claims. Over any other io.Reader, such as a connection or an HTTP body, the stream has no limit unless you pass one, and rlp.Decode offers no way to pass one, as its documentation warns. Cap the raw message first (go-ethereum's eth protocol caps messages at 10 MiB, and its legacy transaction pool refuses transactions over 128 KiB), then decode with NewStream(r, limit). After decoding, bound the values: RLP puts no size limit on *big.Int, so check BitLen, as the transaction pool does for fee caps over 256 bits. One API surprise: when DecodeBytes fills a typed value, canonical-form failures come back wrapped in a descriptive error that errors.Is does not match against ErrCanonInt or ErrCanonSize, so treat any decode error as invalid input.","title":"Bound untrusted input before you decode it"},{"body":"Check in the specification examples and the RLP fixtures from the ethereum/tests repository as known answers. For every type you decode from outside, fuzz with go test -fuzz: when DecodeBytes succeeds, re-encode and require identical bytes; when it fails, require no panic and no large allocation. Add cases for each rule above, for a nested list whose inner length exceeds its parent (ErrElemTooLarge), for structs with missing or extra elements, and for optional trailing fields. For hot paths, go-ethereum's rlpgen generates reflection-free encoders. Keep RLP where it belongs: it is the execution layer's consensus encoding, the consensus layer uses SSZ, and your own service APIs are better served by formats with field names and explicit schemas.","title":"Test with vectors and round trips"}],"takeaway":"Let the rlp package define the bytes, cap untrusted input and decode with an explicit stream limit, bound decoded big integers, and treat every non-canonical form as invalid.","title":"RLP: Ethereum's canonical encoding, and why its decoder rejects every other spelling","unitID":"blockchain-foundations","wrongAnswers":["RLP stores integers as fixed 8-byte words","Leading zeros are legal but slower to parse"]},{"conceptTag":"blockchain.proof-of-work","designGuide":{"cautions":["Security is probabilistic and assumes an honest hash-rate majority.","Timestamps are miner-supplied and need explicit bounds."],"cost":"Real proof of work spends energy and hardware in proportion to the security it buys; the toy costs milliseconds only because its difficulty is tiny.","family":"blockchain","flow":["Commit header fields","Search nonce below target","Verify with one hash","Retarget from timestamps"],"ratings":[],"strengths":["Verification cost is constant regardless of difficulty.","Cumulative work gives an objective rule for comparing chains."]},"hint":"The winning nonce is inside the header; what does Valid do with it?","id":"blockchain.proof-of-work","introduction":"A hash chain reveals that history changed, but anyone can rebuild a chain. Proof of work makes rebuilding expensive: a block counts only if its header hashes below a target, and the only known way to find such a header is to try nonces. Bitcoin still works this way; Ethereum left proof of work at the Merge in 2022. The idea to keep is the asymmetry between expensive search and cheap verification.","nuance":"The verifier does not search. It hashes the header, including the found nonce, once and compares the integer with the target. That asymmetry is what makes proof of work usable.","objective":"Mine a toy block against a big.Int target, verify it with one hash, compute its expected work and retarget from observed block times.","question":"A miner needed about 2^16 attempts to find a valid nonce. How much work does a node spend verifying that header's proof of work?","references":["https://bitcoin.org/bitcoin.pdf","https://developer.bitcoin.org/devguide/block_chain.html","https://pkg.go.dev/math/big#Int.Cmp","https://eips.ethereum.org/EIPS/eip-3675"],"reviewAnswer":"One header hash compared with the target","reviewPrompt":"PoW: cost to verify a block?","sections":[{"body":"Read a SHA-256 digest as a 256-bit unsigned integer. A header is valid when that number is below a target, and lowering the target makes valid headers rarer. With a target of 2^(256-k), a valid hash starts with k zero bits, so a miner expects about 2^k attempts while a verifier hashes once and compares. The nonce is the field the miner is free to change. Everything else in the header is fixed: the parent hash, the height, the difficulty and a commitment to the body, such as the Merkle root from the second lesson. Finding a nonce therefore proves work spent on this exact header. Change the body and the commitment changes, the old nonce stops working, and the cheap relinking attack from the first lesson now costs a fresh search for every block rewritten.","title":"A target turns hashing into a lottery"},{"body":"Header.Hash encodes fixed-width fields in a fixed order, as in the hash-chain lesson, and Valid compares the digest with target(Bits) using math/big. Mine increments the nonce from zero, so the run is deterministic: the same header always yields the same nonce. Work reports the expected number of hashes a target represents, and Retarget scales the target by observed over expected time, clamped to a factor of four. Difficulty stays at 16 bits or less so the run takes milliseconds.","code":"package main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"math/big\"\n)\n\ntype Header struct {\n\tParent [32]byte\n\tHeight uint64\n\tData   [32]byte // commitment to the block body, e.g. a Merkle root\n\tBits   uint     // difficulty: the target is 2^(256-Bits)\n\tNonce  uint64\n}\n\nfunc (h Header) Hash() [32]byte {\n\tbuf := append([]byte(nil), h.Parent[:]...)\n\tbuf = binary.BigEndian.AppendUint64(buf, h.Height)\n\tbuf = append(buf, h.Data[:]...)\n\tbuf = binary.BigEndian.AppendUint64(buf, uint64(h.Bits))\n\tbuf = binary.BigEndian.AppendUint64(buf, h.Nonce)\n\treturn sha256.Sum256(buf)\n}\n\nfunc target(bits uint) *big.Int { return new(big.Int).Lsh(big.NewInt(1), 256-bits) }\n\n// Valid costs one hash, whatever the difficulty.\nfunc Valid(h Header) bool {\n\tsum := h.Hash()\n\treturn new(big.Int).SetBytes(sum[:]).Cmp(target(h.Bits)) < 0\n}\n\n// Mine is the expensive side: about 2^Bits attempts on average.\nfunc Mine(h Header) (Header, uint64) {\n\tfor attempts := uint64(1); ; attempts++ {\n\t\tif Valid(h) {\n\t\t\treturn h, attempts\n\t\t}\n\t\th.Nonce++\n\t}\n}\n\n// Work is the expected number of hashes a header represents: 2^256 / (target+1).\nfunc Work(bits uint) *big.Int {\n\tt := target(bits)\n\treturn new(big.Int).Div(new(big.Int).Lsh(big.NewInt(1), 256), t.Add(t, big.NewInt(1)))\n}\n\n// Retarget scales the target by actual/expected time, clamped to a factor of 4.\nfunc Retarget(old *big.Int, actual, expected int64) *big.Int {\n\tactual = max(expected/4, min(actual, expected*4))\n\tt := new(big.Int).Mul(old, big.NewInt(actual))\n\treturn t.Div(t, big.NewInt(expected))\n}\n\nfunc main() {\n\tbody := sha256.Sum256([]byte(\"toy block body\"))\n\tvar last Header\n\tfor _, bits := range []uint{8, 12, 16} {\n\t\th, attempts := Mine(Header{Height: 1, Data: body, Bits: bits})\n\t\tsum := h.Hash()\n\t\tfmt.Printf(\"bits %2d: nonce %6d after %6d attempts, hash %s..., work %d\\n\",\n\t\t\tbits, h.Nonce, attempts, hex.EncodeToString(sum[:3]), Work(bits))\n\t\tlast = h\n\t}\n\n\tfmt.Println(\"verify mined header:\", Valid(last))\n\tlast.Data[0] ^= 1 // change one bit of the body commitment\n\tfmt.Println(\"verify after edit:\", Valid(last))\n\n\t// Ten blocks were expected to take 6000 s (fixed numbers, not a clock).\n\told := target(16)\n\tfor _, actual := range []int64{6000, 3000, 100} {\n\t\tnext := Retarget(old, actual, 6000)\n\t\tfmt.Printf(\"span %4ds: new target = old * %s\\n\", actual, new(big.Rat).SetFrac(next, old).RatString())\n\t}\n}","language":"go","title":"Mine, verify and retarget a toy chain","walkthrough":"At 8, 12 and 16 bits the expected work is 255, 4095 and 65535 hashes, computed as 2^256 divided by target+1, the formula Bitcoin Core uses for chain work. The 16-bit search took 205064 attempts, about three times the mean; attempt counts are geometrically distributed, so single blocks vary widely. Verification is one Valid call, and flipping one bit of the body commitment makes the same nonce fail. Retarget keeps the target when ten blocks take the expected 6000 seconds, halves it when they take half as long, and clamps a 60-fold speed-up to a factor of four. The spans are fixed numbers, not clock readings."},{"body":"Hash rate rises and falls as hardware joins or leaves, so a fixed target would let block intervals drift from seconds to days. Bitcoin recomputes its target every 2016 blocks from the time those blocks took, aiming at ten minutes per block, and limits each adjustment to a factor of four in either direction; Retarget is that rule in miniature. Timestamps are written by miners, so real rules also bound them: Bitcoin rejects a header whose time is not later than the median of the previous eleven blocks or lies more than two hours in the future. A toy that reads the wall clock is neither deterministic nor representative. Treat timestamps as untrusted data, as the program does, and test the rules that bound them.","title":"Difficulty adjustment keeps block time, not security, constant"},{"body":"Because work is costly to produce, nodes follow the valid chain with the most cumulative work, and rewriting a block buried under k later blocks means outpacing the rest of the network for k blocks. That security is probabilistic: an attacker with a minority of hash rate can still win a short race, and one with a majority can rewrite at will. Bitcoin's real header is 80 bytes hashed with double SHA-256, its target is packed into a 4-byte bits field, and it accepts a hash equal to the target, where this toy uses a strict comparison so that Bits reads as leading zero bits. Ethereum's proof-of-work era ended with the Merge (EIP-3675); validators now propose blocks and stake finalizes them, which the next lesson relies on. And do not reinvent proof of work as an API rate limiter: puzzles cost honest low-end devices more than attackers with GPUs.","title":"What proof of work does and does not secure"},{"body":"Keep difficulty tiny in tests and pin the expected nonce for a fixed header as a known answer, so a changed encoding changes the nonce and fails loudly. Test Valid at the boundary: under a strict comparison a hash equal to the target must fail, and a target of zero or above 2^256 must be refused before use; real chains also enforce a maximum target, the proof-of-work limit. Test Retarget at, above and below both clamps, and check integer division, whose rounding compounds over many periods. Benchmark mining separately from unit tests, and never let a test search at a difficulty whose runtime depends on luck you have not measured: the 16-bit search here already needed three times its average.","title":"Testing work-based code"}],"takeaway":"Proof of work is asymmetric: a nonce below a 2^(256-k) target takes about 2^k hashes to find and one hash to check, so chains compare cumulative work and retarget from timestamps treated as data.","title":"Proof of work: finding a nonce takes thousands of hashes, checking it takes one","unitID":"blockchain-foundations","wrongAnswers":["About 2^16 hashes, repeating the search","About 2^8 hashes, the square root of the search"]},{"conceptTag":"blockchain.fork-choice","designGuide":{"cautions":["Confirmations are a probability; recompute them from the head.","latest and safe can both move backwards; only finalized is final."],"cost":"Undo journals for every block, an atomic undo-apply-checkpoint transaction, and roughly 13 minutes of waiting for finality on Ethereum.","family":"blockchain","flow":["Store blocks by hash","Pick head by total work","Undo to common ancestor","Credit at finalized"],"ratings":[],"strengths":["Cumulative work makes every honest node converge on one head.","Per-block undo data turns a reorg into a mechanical replay."]},"hint":"Only one tag is backed by an economic penalty rather than an expectation.","id":"blockchain.fork-choice","introduction":"Two valid blocks can extend the same parent, and nodes need a rule that makes them converge on one branch. Proof-of-work chains follow the branch with the most cumulative work; when a heavier branch appears, the node reorganizes, and blocks it had accepted stop being canonical. Anything an indexer derived from those blocks must be undone, and anything irreversible should have waited for finality.","nuance":"latest can reorg, and safe reflects the consensus client's current view of justified checkpoints. A finalized block can only be reverted if at least a third of all stake is slashed.","objective":"Implement a heaviest-chain fork-choice rule, compute a reorganization's undo and apply path, apply confirmation depth, and use Ethereum's safe and finalized tags.","question":"After the Merge, which block tag should an indexer wait for before releasing an irreversible withdrawal?","references":["https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/","https://ethereum.org/en/developers/docs/apis/json-rpc/","https://pkg.go.dev/github.com/ethereum/go-ethereum/rpc#BlockNumber","https://bitcoin.org/bitcoin.pdf"],"reviewAnswer":"finalized: reverting it would slash stake","reviewPrompt":"Tag for an irreversible credit?","sections":[{"body":"Forks happen without any attacker: two miners find blocks at nearly the same moment, or a proposer's block arrives late. Each node keeps every valid block in a tree keyed by hash, and a fork-choice rule picks one leaf as the head. Longest chain is the informal name, but the rule that resists manipulation is most cumulative work, using the Work value from the proof-of-work lesson, so a branch of fewer, harder blocks beats a branch of more, easier ones. Ties keep the block seen first. The events-finality lesson in the next unit shows an indexer refusing a block that does not extend its tip; this lesson supplies the step that follows, walking both branches back to their common ancestor.","title":"Forks are normal; the rule decides"},{"body":"Node.Add rejects a block whose parent is unknown or whose height is not the parent's plus one, computes cumulative work and switches head only on strictly more work. route walks the old and new tips back to their common ancestor and returns the blocks to undo, newest first, and to apply, oldest first. The Indexer keeps a small projection, deposit to including block, that it applies and undoes per block, and computes confirmations as head height minus inclusion height plus one.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n)\n\ntype Block struct {\n\tID, Parent string\n\tHeight     uint64\n\tWork       uint64   // expected hashes for this block, from its target\n\tDeposits   []string // transactions the indexer cares about\n}\n\ntype Node struct {\n\tblocks map[string]Block\n\ttotal  map[string]uint64 // cumulative work from genesis\n\thead   string\n}\n\nfunc NewNode(genesis Block) *Node {\n\treturn &Node{blocks: map[string]Block{genesis.ID: genesis}, total: map[string]uint64{genesis.ID: 0}, head: genesis.ID}\n}\n\n// Add stores a block and applies the fork-choice rule: the tip with the most\n// cumulative work wins; on a tie the block seen first stays head.\nfunc (n *Node) Add(b Block) (ancestor string, undo, apply []string, err error) {\n\tparent, ok := n.blocks[b.Parent]\n\tif !ok || b.Height != parent.Height+1 {\n\t\treturn \"\", nil, nil, fmt.Errorf(\"%s rejected: unknown parent or wrong height\", b.ID)\n\t}\n\tn.blocks[b.ID] = b\n\tn.total[b.ID] = n.total[b.Parent] + b.Work\n\tif n.total[b.ID] <= n.total[n.head] {\n\t\treturn \"\", nil, nil, nil\n\t}\n\told := n.head\n\tn.head = b.ID\n\tancestor, undo, apply = n.route(old, b.ID)\n\treturn ancestor, undo, apply, nil\n}\n\n// route walks both tips back to their common ancestor.\nfunc (n *Node) route(from, to string) (string, []string, []string) {\n\ta, b := n.blocks[from], n.blocks[to]\n\tvar undo, apply []string\n\tfor a.Height > b.Height {\n\t\tundo, a = append(undo, a.ID), n.blocks[a.Parent]\n\t}\n\tfor b.Height > a.Height {\n\t\tapply, b = append(apply, b.ID), n.blocks[b.Parent]\n\t}\n\tfor a.ID != b.ID {\n\t\tundo, a = append(undo, a.ID), n.blocks[a.Parent]\n\t\tapply, b = append(apply, b.ID), n.blocks[b.Parent]\n\t}\n\tslices.Reverse(apply)\n\treturn a.ID, undo, apply\n}\n\n// Indexer keeps a projection that can be rolled back block by block.\ntype Indexer struct {\n\tnode     *Node\n\tincluded map[string]string // deposit -> canonical block containing it\n}\n\nfunc (ix *Indexer) Apply(id string) {\n\tfor _, d := range ix.node.blocks[id].Deposits {\n\t\tix.included[d] = id\n\t}\n}\n\nfunc (ix *Indexer) Undo(id string) {\n\tfor _, d := range ix.node.blocks[id].Deposits {\n\t\tdelete(ix.included, d)\n\t}\n}\n\nfunc (ix *Indexer) Add(b Block) {\n\tancestor, undo, apply, err := ix.node.Add(b)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tif len(undo) > 0 {\n\t\tfmt.Printf(\"%s arrives: reorg via %s, undo %v, apply %v\\n\", b.ID, ancestor, undo, apply)\n\t}\n\tfor _, id := range undo {\n\t\tix.Undo(id) // newest first: the reverse of how they were applied\n\t}\n\tfor _, id := range apply {\n\t\tix.Apply(id)\n\t}\n}\n\nfunc (ix *Indexer) Status(dep string, need uint64) {\n\thead := ix.node.blocks[ix.node.head]\n\tid, ok := ix.included[dep]\n\tif !ok {\n\t\tfmt.Printf(\"%s: not on the canonical chain (head %s)\\n\", dep, head.ID)\n\t\treturn\n\t}\n\tconf := head.Height - ix.node.blocks[id].Height + 1\n\tfmt.Printf(\"%s: in %s, confirmations %d, credit at %d: %v\\n\", dep, id, conf, need, conf >= need)\n}\n\nfunc main() {\n\tix := &Indexer{node: NewNode(Block{ID: \"G\"}), included: map[string]string{}}\n\tfor _, b := range []Block{\n\t\t{ID: \"A1\", Parent: \"G\", Height: 1, Work: 1},\n\t\t{ID: \"A2\", Parent: \"A1\", Height: 2, Work: 1},\n\t\t{ID: \"A3\", Parent: \"A2\", Height: 3, Work: 1, Deposits: []string{\"dep-7\"}},\n\t\t{ID: \"A4\", Parent: \"A3\", Height: 4, Work: 1},\n\t} {\n\t\tix.Add(b)\n\t}\n\tfmt.Println(\"head\", ix.node.head, \"work\", ix.node.total[ix.node.head])\n\tix.Status(\"dep-7\", 3)\n\n\tix.Add(Block{ID: \"B2\", Parent: \"A1\", Height: 2, Work: 2})\n\tfmt.Println(\"after B2 head\", ix.node.head, \"(B2 total work\", ix.node.total[\"B2\"], \"is not more)\")\n\tix.Add(Block{ID: \"B3\", Parent: \"B2\", Height: 3, Work: 2})\n\tfmt.Println(\"head\", ix.node.head, \"height 3 work\", ix.node.total[\"B3\"], \"beats A4 height 4 work\", ix.node.total[\"A4\"])\n\tix.Status(\"dep-7\", 3)\n\n\tix.Add(Block{ID: \"X9\", Parent: \"unknown\", Height: 9, Work: 100})\n\n\tix.Add(Block{ID: \"B4\", Parent: \"B3\", Height: 4, Work: 2, Deposits: []string{\"dep-7\"}})\n\tix.Status(\"dep-7\", 3)\n}","language":"go","title":"A node and an indexer that survive a reorg","walkthrough":"dep-7 lands in A3 and has two confirmations at head A4, below the policy of three, so it is not credited. B2 brings its branch to work 3, not more than 4, so the head stays. B3 brings it to 5, and the node reorganizes via A1: it undoes A4, A3 and A2 and applies B2 and B3, even though A4 is higher. dep-7 then has no canonical block. X9 is rejected because its parent is unknown; a real node would hold it as an orphan until the parent arrives. When B4 re-includes dep-7, its confirmations restart from one."},{"body":"Waiting for k confirmations means waiting until the including block and k-1 blocks after it are all canonical. Under proof of work, the chance that an attacker with a minority of hash rate overtakes a k-block lead falls exponentially with k; the Bitcoin whitepaper works through the numbers, and six confirmations became the convention. It is still a probability, and the right k depends on what is at stake. Recompute confirmations from the current canonical head on every change instead of storing a counter, because a reorg can remove the including block, as happened to dep-7 after B3, or move the transaction to a different height, as B4 did. Identify transactions by their hash, never by block and position.","title":"Confirmation depth is a probability policy"},{"body":"Ethereum's proof of stake picks the head with LMD-GHOST and finalizes checkpoints with Casper FFG. When validators holding two thirds of the stake attest to a checkpoint pair, the earlier checkpoint is finalized, and reverting it would require at least one third of all stake to be slashed. Normally that takes about two epochs, 64 slots of 12 seconds, a little under 13 minutes. The JSON-RPC tags expose this: latest is the head and can reorg; safe is the block the consensus client expects not to reorg under normal conditions, which clients derive from the latest justified checkpoint; finalized is the latest finalized block. Release irreversible effects such as withdrawals from finalized, and use safe or latest only for views that tolerate rollback.","code":"// Runs against your own node; not executed in the app.\nfinalized, err := client.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber)))\nif err != nil {\n\treturn fmt.Errorf(\"finalized head: %w\", err)\n}\nsafe, err := client.HeaderByNumber(ctx, big.NewInt(int64(rpc.SafeBlockNumber)))\nif err != nil {\n\treturn fmt.Errorf(\"safe head: %w\", err)\n}\n// Promote rows at or below the finalized height whose stored block hash\n// matches the canonical hash; a mismatch here is an incident, not a reorg.\nif err := store.Finalize(ctx, finalized.Number.Uint64(), finalized.Hash()); err != nil {\n\treturn err\n}\nlog.Printf(\"safe=%d finalized=%d\", safe.Number, finalized.Number)","language":"go","title":"After the Merge: credit from the finalized tag","walkthrough":"This fragment runs in the reader's own native environment against their own node; it is not executed by the app. ethclient turns the negative rpc.BlockNumber constants into the finalized and safe tags (FinalizedBlockNumber is -3 and SafeBlockNumber is -4 in go-ethereum v1.17.10), so no heights are guessed. store.Finalize is a placeholder for your projection. A stored hash that differs from the finalized hash at the same height means the indexer followed another chain or a misbehaving provider, which calls for an alert, not an automatic rollback."},{"body":"For every block the projection applied, keep enough to reverse it, keyed by block hash: the rows it inserted, or the previous values of rows it updated, like the account journal from the ledger lesson. Undo newest first, then apply the new branch oldest first, in one database transaction together with the checkpoint, so a crash cannot leave a half-reorganized state. Bound the depth you support: below finalized no reorg should happen, and a deeper one is an incident. Finality can also stall when too few validators participate, which has happened on mainnet; then finalized lags far behind latest, and the right response is to wait and alert, not to fall back to latest. Test with scripted block trees like the program's: a one-block replacement, a deep reorg, a heavier but shorter branch, an unknown parent, a re-included transaction and a crash between undo and apply.","title":"What an indexer undoes, and how to test it"}],"takeaway":"Choose the head by cumulative work, walk to the common ancestor to undo and apply atomically, recompute confirmations from the current head, and release irreversible effects only at finalized.","title":"Fork choice and reorgs: follow the heaviest chain and undo what the old branch indexed","unitID":"blockchain-foundations","wrongAnswers":["latest, once six blocks have built on top of it","safe, because safe blocks can never be reorganized"]},{"conceptTag":"blockchain.eip1559-fees","designGuide":{"cautions":["A capped transaction can wait indefinitely while the base fee keeps rising.","Blob gas has a separate fee market that this policy does not bound."],"cost":"A small fee module with table tests and one reviewed ceiling per chain; the price is occasional delayed inclusion during fee spikes.","family":"blockchain","flow":["Observe base fee + tip","Derive caps in wei","Enforce fee ceiling","Build type-2 tx unsigned"],"ratings":[],"strengths":["Exact integer arithmetic that agrees with go-ethereum's EffectiveGasTip.","A policy ceiling bounds spend even when an oracle or node misbehaves."]},"hint":"One of the two caps starts to bind when the base fee is high.","id":"blockchain.eip1559-fees","introduction":"Since the London upgrade an Ethereum transaction no longer names one gas price. It carries two caps chosen by the sender, while the protocol sets a per-block base fee that is burned. The price actually paid is decided only when a block includes the transaction, so the code that builds it has to reason about the worst case. This lesson computes those numbers exactly and puts a ceiling in front of the signer that no fee oracle can raise.","nuance":"The base fee is burned and the tip is whatever room the cap leaves: with a 62 gwei cap and a 61.5 gwei base fee, only 0.5 gwei of the 2 gwei tip reaches the producer.","objective":"Derive maxFeePerGas and maxPriorityFeePerGas with big.Int, predict the effective gas price for any base fee and enforce a fee ceiling before signing.","question":"What price per unit of gas does an included EIP-1559 transaction actually pay?","references":["https://eips.ethereum.org/EIPS/eip-1559","https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#Transaction.EffectiveGasTip","https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient#Client.FeeHistory","https://ethereum.org/en/developers/docs/gas/"],"reviewAnswer":"min(maxFeePerGas, baseFee + maxPriorityFeePerGas)","reviewPrompt":"EIP-1559 price paid per gas?","sections":[{"body":"A type-2 transaction, types.DynamicFeeTx in go-ethereum, carries GasTipCap (maxPriorityFeePerGas, the most the sender offers the block producer) and GasFeeCap (maxFeePerGas, the most it will pay per unit of gas in total). The block header carries BaseFee. A block can include the transaction only if maxFeePerGas is at least that base fee, and the price per gas is then min(maxFeePerGas, baseFee + maxPriorityFeePerGas). The base-fee part is burned; only the remainder reaches the producer. The base fee follows demand: geth's CalcBaseFee changes it by parentBaseFee * (gasUsed - target) / target / 8, so a completely full block raises it by 12.5 percent and an empty one lowers it by the same fraction. Every value here is an integer number of wei that can exceed 64 bits, which is why go-ethereum uses *big.Int throughout and why float64 has no place in the calculation; the exact-units lesson shows that failure for token amounts.","title":"Two caps from the sender, one price from the protocol"},{"body":"The program takes an observed base fee of 30 gwei and a 2 gwei tip and derives a fee cap of twice the base fee plus the tip, the same headroom go-ethereum's bind/v2 transactor uses when no cap is given. It runs the policy check a signing service would own, builds an unsigned DynamicFeeTx for local chain 1337, and replays the inclusion formula at three possible base fees, cross-checking each result against go-ethereum's own Transaction.EffectiveGasTip.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/types\"\n\t\"github.com/ethereum/go-ethereum/params\"\n)\n\n// FeePolicy is owned by the signing service, not by the fee oracle.\ntype FeePolicy struct {\n\tMaxFeePerGas *big.Int // highest maxFeePerGas the service will sign\n\tMaxTotalFee  *big.Int // highest gasLimit * maxFeePerGas, in wei\n}\n\nvar errAbovePolicy = errors.New(\"refusing to sign\")\n\nfunc gwei(n int64) *big.Int {\n\treturn new(big.Int).Mul(big.NewInt(n), big.NewInt(params.GWei))\n}\n\n// formatGwei prints a non-negative wei amount as gwei without floating point.\nfunc formatGwei(wei *big.Int) string {\n\tq, r := new(big.Int).QuoRem(wei, big.NewInt(params.GWei), new(big.Int))\n\tif r.Sign() == 0 {\n\t\treturn q.String() + \" gwei\"\n\t}\n\tfrac := strings.TrimRight(fmt.Sprintf(\"%09d\", r.Uint64()), \"0\")\n\treturn q.String() + \".\" + frac + \" gwei\"\n}\n\n// feeCapFor leaves room for the base fee to double before inclusion.\nfunc feeCapFor(baseFee, tip *big.Int) *big.Int {\n\tc := new(big.Int).Mul(baseFee, big.NewInt(2))\n\treturn c.Add(c, tip)\n}\n\n// effectivePrice is min(feeCap, baseFee+tipCap). Below baseFee it is not includable.\nfunc effectivePrice(baseFee, tipCap, feeCap *big.Int) (*big.Int, error) {\n\tif feeCap.Cmp(baseFee) < 0 {\n\t\treturn nil, errors.New(\"max fee below base fee\")\n\t}\n\tp := new(big.Int).Add(baseFee, tipCap)\n\tif p.Cmp(feeCap) > 0 {\n\t\tp.Set(feeCap)\n\t}\n\treturn p, nil\n}\n\nfunc checkPolicy(p FeePolicy, gas uint64, tipCap, feeCap *big.Int) error {\n\tif tipCap.Sign() < 0 || feeCap.Sign() <= 0 || tipCap.Cmp(feeCap) > 0 {\n\t\treturn errors.New(\"need 0 <= max priority fee <= max fee\")\n\t}\n\tif feeCap.Cmp(p.MaxFeePerGas) > 0 {\n\t\treturn fmt.Errorf(\"%w: max fee %s > limit %s\", errAbovePolicy, formatGwei(feeCap), formatGwei(p.MaxFeePerGas))\n\t}\n\tworst := new(big.Int).Mul(new(big.Int).SetUint64(gas), feeCap)\n\tif worst.Cmp(p.MaxTotalFee) > 0 {\n\t\treturn fmt.Errorf(\"%w: worst-case fee %s wei > limit %s wei\", errAbovePolicy, worst, p.MaxTotalFee)\n\t}\n\treturn nil\n}\n\nfunc main() {\n\tpolicy := FeePolicy{MaxFeePerGas: gwei(100), MaxTotalFee: big.NewInt(3_000_000_000_000_000)}\n\tconst gasLimit = 21_000\n\tbaseFee, tip := gwei(30), gwei(2) // observed from the latest header and a tip oracle\n\tfeeCap := feeCapFor(baseFee, tip)\n\tfmt.Println(\"max priority fee\", formatGwei(tip)+\", max fee\", formatGwei(feeCap))\n\n\tfmt.Println(checkPolicy(policy, gasLimit, tip, feeCapFor(gwei(120), tip)))\n\tfmt.Println(checkPolicy(policy, 200_000, tip, feeCap))\n\tif err := checkPolicy(policy, gasLimit, tip, feeCap); err != nil {\n\t\tpanic(err)\n\t}\n\n\tto := common.HexToAddress(\"0x00000000000000000000000000000000000000aa\")\n\ttx := types.NewTx(&types.DynamicFeeTx{\n\t\tChainID:   big.NewInt(1337),\n\t\tNonce:     0,\n\t\tGasTipCap: tip,\n\t\tGasFeeCap: feeCap,\n\t\tGas:       gasLimit,\n\t\tTo:        &to,\n\t\tValue:     big.NewInt(10_000_000_000_000_000), // 0.01 ether in wei\n\t})\n\tfmt.Println(\"built unsigned type\", tx.Type(), \"tx for chain\", tx.ChainId())\n\n\tfor _, b := range []*big.Int{gwei(30), big.NewInt(61_500_000_000), gwei(63)} {\n\t\tprice, err := effectivePrice(b, tip, feeCap)\n\t\tgethTip, gethErr := tx.EffectiveGasTip(b)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"base %s: not includable (%v)\\n\", formatGwei(b), gethErr)\n\t\t\tcontinue\n\t\t}\n\t\tourTip := new(big.Int).Sub(price, b)\n\t\tfmt.Printf(\"base %s: pays %s, producer tip %s, geth agrees: %t\\n\",\n\t\t\tformatGwei(b), formatGwei(price), formatGwei(ourTip), ourTip.Cmp(gethTip) == 0)\n\t}\n\tfmt.Println(\"upfront balance check:\", tx.Cost(), \"wei\")\n}","language":"go","title":"Compute the caps, check the policy, then build","walkthrough":"gwei multiplies by params.GWei (1e9) inside big.Int, and formatGwei divides with QuoRem so 61.5 gwei prints exactly. checkPolicy rejects a tip above the cap, a fee cap above 100 gwei and a worst case (gas limit * fee cap) above 0.003 ether: the oracle spike to a 120 gwei base fee yields a 242 gwei cap and is refused, and so is a 200000-gas call even at the normal cap. At base 30 the sender pays 32 gwei and the producer keeps 2. At 61.5 the cap binds, so the producer gets only 0.5. At 63 geth returns ErrGasFeeCapTooLow (fee cap less than base fee) and the transaction simply waits. tx.Cost() is gas * GasFeeCap + value, the balance a node demands up front, not the amount finally charged."},{"body":"In production the base fee comes from the latest header and the tip from the node's suggestion or from eth_feeHistory percentiles. Both are hints from an external dependency, so they are inputs to the policy rather than values the signer trusts. FeeHistory returns one more base fee than the number of blocks requested: the last entry is the node's projection for the next block, a better starting point than the latest header when blocks are full.","code":"head, err := client.HeaderByNumber(ctx, nil) // latest\nif err != nil {\n\treturn err\n}\nif head.BaseFee == nil {\n\treturn errors.New(\"no EIP-1559 base fee on this chain; use a legacy fee policy\")\n}\ntip, err := client.SuggestGasTipCap(ctx) // eth_maxPriorityFeePerGas\nif err != nil {\n\treturn err\n}\nhist, err := client.FeeHistory(ctx, 5, nil, []float64{50})\nif err != nil {\n\treturn err\n}\nnextBase := hist.BaseFee[len(hist.BaseFee)-1] // the node's projection for the next block\nfeeCap := feeCapFor(nextBase, tip)\nif err := checkPolicy(policy, gasLimit, tip, feeCap); err != nil {\n\treturn err // alert: the market moved beyond what this service may pay\n}","language":"go","title":"Take inputs from the node, but let the policy decide","walkthrough":"This fragment talks to a real node, so run it in your own native environment against an endpoint whose chain ID you have verified; it is not executed here. HeaderByNumber(ctx, nil) asks for the latest header, and BaseFee is nil before London, which deserves an explicit error instead of a nil-pointer panic. SuggestGasTipCap maps to eth_maxPriorityFeePerGas; the 50th-percentile rewards in hist.Reward are an alternative tip source. hist.BaseFee has blockCount+1 entries, the last one for the next block. Whatever the source, checkPolicy has the last word."},{"body":"Treat the fee ceiling as configuration with an owner, reviewed like any spending limit, and alert when the guard trips instead of raising it automatically. A transaction with 2x headroom can still wait if the base fee keeps climbing; that is the safe failure, because the alternative is paying whatever the market demands. When you do speed up a pending transaction, the replacement rules from the nonces lesson apply: geth's default pool accepts a same-nonce replacement only if both the fee cap and the tip rise by at least 10 percent, so bump both and pass the new values through the same policy. Reconcile budgets from the receipt, EffectiveGasPrice * GasUsed, not from the caps; unused gas and unused headroom are never charged. The gas limit is a separate guard: estimating it is a simulation against current state, and the worst-case fee multiplies it. Blob transactions add an independent fee market, maxFeePerBlobGas, that this policy does not bound.","title":"Ceilings, replacements and what is finally charged"},{"body":"The fee path needs no node to test. Table-test effectivePrice at base fees below, at and above the point where the cap binds, and assert agreement with EffectiveGasTip in each case so a library upgrade that changes the rules is noticed. Test the guard with a tip above the cap, a zero cap, a cap exactly at the limit (allowed) and one wei above it (refused), and a gas limit that pushes the worst case over the total ceiling. Add a regression test that oracle values are copied rather than aliased: big.Int methods mutate their receiver, so a helper that writes into a *big.Int taken from a header can silently change the next transaction's fees. types.NewTx copies its TxData, which protects the built transaction, but not the policy inputs you keep. In review, check that nothing between the policy check and the signer can change the fields.","title":"Test the guard at its edges"}],"takeaway":"Compute EIP-1559 fees in wei with big.Int: the price paid is min(maxFee, baseFee + tip), and a policy-owned ceiling on maxFee and on gasLimit * maxFee must reject a transaction before it is signed.","title":"EIP-1559 fees: compute the effective gas price exactly and refuse to sign above a ceiling","unitID":"blockchain","wrongAnswers":["baseFee + maxPriorityFeePerGas, even above the cap","maxFeePerGas; the producer keeps the whole cap"]},{"conceptTag":"blockchain.raw-transactions","designGuide":{"cautions":["Remote signers with random nonces produce new hashes for the same fields.","A fresh nonce on retry is a second payment, not a retry."],"cost":"A durable record per signed transaction (intent, nonce, raw bytes, hashes) and a receipt lookup before every resend.","family":"blockchain","flow":["Build typed intent","Sign with chain signer","Persist raw bytes + hash","Send, then look up hash"],"ratings":[],"strengths":["The hash is known before broadcast, so retries can be idempotent.","Decoding and recovering the sender verifies bytes from other systems offline."]},"hint":"Ask what the transaction hash is computed from.","id":"blockchain.raw-transactions","introduction":"eth_sendRawTransaction takes one opaque byte string. Everything that matters about a transfer, including its chain, nonce, fees, destination, the signer and its future on-chain hash, is fixed when those bytes are produced, before any node sees them. Producing, checking and storing the bytes offline turns a network call with an unknown outcome into a lookup you can repeat.","nuance":"Transaction.Hash is keccak256 of the signed EIP-2718 envelope, so it is fixed before broadcast and lets the service look up a receipt after a timeout instead of signing again with a new nonce.","objective":"Sign a typed transaction with a test key, round-trip its raw bytes, recover the sender and use the precomputed hash to make retries safe.","question":"A service signs a transaction and its eth_sendRawTransaction call times out. When could it first have known the hash to look up?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#SignTx","https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#Transaction.MarshalBinary","https://eips.ethereum.org/EIPS/eip-2718","https://ethereum.org/en/developers/docs/transactions/"],"reviewAnswer":"As soon as it is signed: keccak256 of the raw bytes","reviewPrompt":"When is a tx hash known?","sections":[{"body":"go-ethereum distinguishes three artifacts. The signing hash, returned by Signer.Hash, is keccak256 over the type byte and the RLP list of fields without a signature; that is what the private key signs. The raw transaction, returned by MarshalBinary, is the EIP-2718 envelope: one type byte (0x02 for EIP-1559) followed by the RLP list that now includes V, R and S. The transaction hash, Transaction.Hash, is keccak256 of exactly those raw bytes. Because the hash is a pure function of the signed bytes, it is known the moment signing finishes, before broadcast, and it does not depend on which node accepts it. The signing-boundaries lesson built an unsigned intent; here it goes through the whole offline lifecycle.","title":"One transaction, two hashes and a byte string"},{"body":"The example derives a throwaway key from 32 bytes of 0x01, a well-known test key that must never hold funds, and signs an EIP-1559 transfer for local chain 1337. It then plays the receiving side: decode the raw bytes into a fresh Transaction, recover the sender and compare hashes. Two final checks show what stays stable across signing and what changes.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math/big\"\n\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/types\"\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\nfunc main() {\n\t// TEST KEY ONLY: 32 bytes of 0x01. Never fund it or reuse it outside a local chain.\n\tkey, err := crypto.ToECDSA(bytes.Repeat([]byte{1}, 32))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfrom := crypto.PubkeyToAddress(key.PublicKey)\n\tsigner := types.LatestSignerForChainID(big.NewInt(1337))\n\n\tto := common.HexToAddress(\"0x00000000000000000000000000000000000000aa\")\n\tintent := &types.DynamicFeeTx{\n\t\tChainID:   big.NewInt(1337),\n\t\tNonce:     7,\n\t\tGasTipCap: big.NewInt(2_000_000_000),\n\t\tGasFeeCap: big.NewInt(62_000_000_000),\n\t\tGas:       21_000,\n\t\tTo:        &to,\n\t\tValue:     big.NewInt(1_000_000_000_000_000),\n\t}\n\tsigned, err := types.SignTx(types.NewTx(intent), signer, key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\traw, err := signed.MarshalBinary() // the bytes eth_sendRawTransaction carries\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"sender %s\\n\", from.Hex())\n\tfmt.Printf(\"raw: %d bytes, first byte 0x%02x (type %d)\\n\", len(raw), raw[0], signed.Type())\n\tfmt.Println(\"tx hash  \", signed.Hash().Hex())\n\tfmt.Println(\"sign hash\", signer.Hash(signed).Hex())\n\tfmt.Println(\"hash == keccak256(raw):\", signed.Hash() == crypto.Keccak256Hash(raw))\n\n\t// The receiving side: decode untrusted bytes, then recover who signed them.\n\tvar decoded types.Transaction\n\tif err := decoded.UnmarshalBinary(raw); err != nil {\n\t\tpanic(err)\n\t}\n\tgot, err := types.Sender(signer, &decoded)\n\tfmt.Println(\"recovered sender matches:\", got == from, err)\n\tfmt.Println(\"decoded hash matches:\", decoded.Hash() == signed.Hash())\n\n\t_, err = types.Sender(types.LatestSignerForChainID(big.NewInt(1)), &decoded)\n\tfmt.Println(\"verify as chain 1:\", err)\n\n\tagain, _ := types.SignTx(types.NewTx(intent), signer, key)\n\tfmt.Println(\"re-signed same fields, same hash:\", again.Hash() == signed.Hash())\n\n\tbump := *intent // shallow copy is enough: we replace the big.Int pointers\n\tbump.GasTipCap = big.NewInt(2_200_000_000)\n\tbump.GasFeeCap = big.NewInt(68_200_000_000)\n\treplacement, _ := types.SignTx(types.NewTx(&bump), signer, key)\n\tfmt.Println(\"replacement: same nonce\", replacement.Nonce() == signed.Nonce(),\n\t\t\"new hash\", replacement.Hash() != signed.Hash())\n}","language":"go","title":"Sign with a fixed test key and round-trip the bytes","walkthrough":"LatestSignerForChainID(1337) returns the newest signer in this release, the Prague signer, which accepts every typed transaction and binds signatures to chain 1337. SignTx computes signer.Hash, signs it with crypto.Sign and attaches V, R and S. MarshalBinary yields 119 bytes starting with 0x02, and keccak256 of those bytes equals Hash(). UnmarshalBinary rebuilds the transaction from untrusted bytes, and types.Sender recovers the address; the same bytes checked with a chain-1 signer fail with ErrInvalidChainId. Re-signing identical fields reproduces the hash because go-ethereum signs with deterministic RFC 6979 nonces. Raising both fee caps by 10 percent for the same nonce produces a new hash."},{"body":"The precomputed hash is what makes an unknown send outcome manageable. Store the intent, nonce, raw bytes and hash durably before the first network call, then treat sending as an attempt to publish those exact bytes. After a timeout, ask for a receipt by hash before deciding anything. If none exists yet, resending the stored bytes cannot create a second transfer, because the nonce allows at most one transaction from that account at that position to be included.","code":"// Native environment only: a real node and a durable store.\nif err := store.SaveSigned(ctx, intentID, signed.Nonce(), signed.Hash(), raw); err != nil {\n\treturn err // nothing was sent, so repeating this step is safe\n}\nsendErr := client.SendTransaction(ctx, signed) // MarshalBinary + eth_sendRawTransaction\nreceipt, err := client.TransactionReceipt(ctx, signed.Hash())\nswitch {\ncase err == nil:\n\treturn store.MarkIncluded(ctx, intentID, receipt.Status, receipt.BlockHash)\ncase errors.Is(err, ethereum.NotFound):\n\t// Pending, dropped or never received: resend the same raw bytes later.\n\treturn store.MarkSubmitted(ctx, intentID, sendErr)\ndefault:\n\treturn err // provider trouble: retry the lookup, never the signing\n}","language":"go","title":"Persist the bytes and the hash before you send","walkthrough":"This fragment needs a node and a database, so it runs in your own native environment; store is a placeholder for your persistence layer. SendTransaction is MarshalBinary plus eth_sendRawTransaction, so the bytes on the wire are the stored ones. The receipt lookup uses the precomputed hash whether or not the send returned an error, and ethclient reports ethereum.NotFound while no receipt exists. On a resend, geth answers already known for a transaction it holds and nonce too low once that nonce is used; the second means some transaction took the slot, so look up the receipt by hash to learn whether it was yours."},{"body":"Three retry strategies look alike and behave very differently. Resending the stored raw bytes is idempotent: same hash, same nonce. Re-signing the same fields is safe only because the result occupies the same nonce. With go-ethereum's deterministic signer it even reproduces the hash, but a remote signer, HSM or KMS that uses random ECDSA nonces returns a different valid signature and therefore a different hash for the same intent, so the record must accept several hashes per nonce. Building a transaction with a fresh nonce is a second payment and belongs to a new business intent, never to a retry; the nonces lesson covers who owns that decision. A fee-bumped replacement deliberately produces a new hash for the same nonce. Whichever version is included wins and the others become permanently invalid, so reconcile by account and nonce as well as by hash.","title":"Resend, re-sign or replace: three different retries"},{"body":"Services that receive raw transactions from elsewhere, such as a relayer, a co-signer or an approval queue, should decode and check them instead of forwarding bytes blindly. After UnmarshalBinary, compare Type, ChainId, To, Value, Data, Nonce, Gas and both fee caps with the approved intent, recover the sender with a signer for the configured chain and compare it with the expected account. Two details from go-ethereum 1.17 matter in review. Sender rejects a chain mismatch, but SignTx stamps the signer's chain ID onto a typed transaction whose ChainID is zero instead of failing, so the signer, not the intent, picks the chain unless your policy checks ChainID first. And LatestSignerForChainID follows the newest fork of each release, so pin the module version and rerun these round-trip tests on every upgrade.","title":"Decode untrusted bytes like a verifier"}],"takeaway":"Sign offline, persist the raw bytes and their hash before broadcast, and retry by resending those exact bytes; a fresh nonce is a second payment, not a retry.","title":"Raw transactions offline: sign, encode, decode and recover the sender before anything is broadcast","unitID":"blockchain","wrongAnswers":["Only after a node accepts it into its pool","Only after a block includes the transaction"]},{"conceptTag":"blockchain.receipts-logs","designGuide":{"cautions":["Log position fields come from the provider and are not consensus-checked.","Reversal works only while credits are internal; irreversible effects need finality."],"cost":"A per-chain token allow-list, an idempotency key per delivered log and reversal logic in every projection that consumes events.","family":"blockchain","flow":["Check receipt status","Match address + topic0","Decode topics and data","Key credit, honor Removed"],"ratings":[],"strengths":["Impostor contracts and look-alike events are rejected before money moves.","Duplicate and removed deliveries keep the projection consistent."]},"hint":"Anyone can deploy a contract that emits the same event signature.","id":"blockchain.receipts-logs","introduction":"A receipt is the node's report of what a transaction did: whether execution succeeded, how much gas it used and which events contracts emitted. Deposit detectors, payment processors and indexers turn those events into balances, which makes the decoding rules security rules. Anyone can deploy a contract that emits a log shaped exactly like a token transfer, and a log from a block that is later reorganized away has to be reversed.","nuance":"Topic 0 only names the event shape. The emitting address proves which contract spoke, the topic count separates ERC-20 from ERC-721, and a reverted receipt has no effects to credit.","objective":"Interpret receipt status and gas, decode an ERC-20 Transfer log with accounts/abi, and reject impostor or removed logs before crediting a balance.","question":"Which checks must pass before a log is credited as an ERC-20 deposit?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#Log","https://pkg.go.dev/github.com/ethereum/go-ethereum/core/types#Receipt","https://pkg.go.dev/github.com/ethereum/go-ethereum/accounts/abi#ParseTopics","https://eips.ethereum.org/EIPS/eip-20"],"reviewAnswer":"Success status, token address, topic0 and 3 topics","reviewPrompt":"Checks before crediting Transfer?","sections":[{"body":"Receipt.Status is 1 (types.ReceiptStatusSuccessful) or 0 (types.ReceiptStatusFailed). A failed transaction is still included: the sender paid GasUsed * EffectiveGasPrice, the nonce is consumed, and every state change and log from the execution was discarded, so Logs is empty. A successful status only says execution did not revert; whether your business effect happened depends on which logs were emitted and by which contract. Each Log carries the emitting contract Address, zero to four Topics and an opaque Data section. Its block number, block hash, transaction hash and log index are derived fields filled in by the node; go-ethereum's own comment says they are not secured by consensus, so they are only as trustworthy as the provider that served them.","title":"What a receipt proves, and what it does not"},{"body":"For a non-anonymous Solidity event, topic 0 is keccak256 of the canonical signature, Transfer(address,address,uint256) for ERC-20. Each indexed parameter takes one further topic as a 32-byte word, and the non-indexed parameters are ABI-encoded into Data. The program builds a successful receipt in memory with three logs (a genuine transfer from the expected token contract, the same bytes from an impostor contract and a four-topic log), adds a reverted receipt, then pushes the genuine log through a reorg.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math/big\"\n\t\"strings\"\n\n\t\"github.com/ethereum/go-ethereum/accounts/abi\"\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/types\"\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\nconst transferABI = `[{\"type\":\"event\",\"name\":\"Transfer\",\"anonymous\":false,\"inputs\":[\n{\"name\":\"from\",\"type\":\"address\",\"indexed\":true},\n{\"name\":\"to\",\"type\":\"address\",\"indexed\":true},\n{\"name\":\"value\",\"type\":\"uint256\",\"indexed\":false}]}]`\n\ntype Transfer struct {\n\tFrom  common.Address\n\tTo    common.Address\n\tValue *big.Int\n}\n\nfunc decodeTransfer(token abi.ABI, want common.Address, lg *types.Log) (Transfer, error) {\n\tev := token.Events[\"Transfer\"]\n\tif lg.Address != want {\n\t\treturn Transfer{}, fmt.Errorf(\"emitted by %s, not the token\", lg.Address.Hex())\n\t}\n\tif len(lg.Topics) != 3 || lg.Topics[0] != ev.ID {\n\t\treturn Transfer{}, fmt.Errorf(\"%d topics, not an ERC-20 Transfer\", len(lg.Topics))\n\t}\n\tvar out Transfer\n\tif err := token.UnpackIntoInterface(&out, \"Transfer\", lg.Data); err != nil {\n\t\treturn Transfer{}, err // fills Value from the data section\n\t}\n\tvar indexed abi.Arguments\n\tfor _, arg := range ev.Inputs {\n\t\tif arg.Indexed {\n\t\t\tindexed = append(indexed, arg)\n\t\t}\n\t}\n\tif err := abi.ParseTopics(&out, indexed, lg.Topics[1:]); err != nil {\n\t\treturn Transfer{}, err // fills From and To from topics 1 and 2\n\t}\n\treturn out, nil\n}\n\n// deposits credits each delivered log once, keyed by block hash and log index,\n// and reverses the credit when the same log comes back with Removed set.\ntype deposits struct {\n\ttoken    abi.ABI\n\tcontract common.Address\n\tapplied  map[string]bool\n\tbalance  map[common.Address]*big.Int\n}\n\nfunc (d *deposits) onLog(lg *types.Log) {\n\tt, err := decodeTransfer(d.token, d.contract, lg)\n\tif err != nil {\n\t\tfmt.Printf(\"log %d skipped: %v\\n\", lg.Index, err)\n\t\treturn\n\t}\n\tkey := fmt.Sprintf(\"%s/%d\", lg.BlockHash.Hex(), lg.Index)\n\tif d.balance[t.To] == nil {\n\t\td.balance[t.To] = new(big.Int)\n\t}\n\tswitch {\n\tcase lg.Removed && d.applied[key]:\n\t\td.balance[t.To].Sub(d.balance[t.To], t.Value)\n\t\tdelete(d.applied, key)\n\t\tfmt.Printf(\"log %d removed: reverse %s\\n\", lg.Index, t.Value)\n\tcase !lg.Removed && !d.applied[key]:\n\t\td.balance[t.To].Add(d.balance[t.To], t.Value)\n\t\td.applied[key] = true\n\t\tfmt.Printf(\"log %d: credit %s from %s\\n\", lg.Index, t.Value, t.From.Hex())\n\t}\n}\n\nfunc (d *deposits) onReceipt(r *types.Receipt) {\n\tfee := new(big.Int).Mul(new(big.Int).SetUint64(r.GasUsed), r.EffectiveGasPrice)\n\tfmt.Printf(\"status %d, gas used %d, fee %s wei, %d logs\\n\", r.Status, r.GasUsed, fee, len(r.Logs))\n\tif r.Status != types.ReceiptStatusSuccessful {\n\t\treturn // reverted: the fee was paid, but no token moved\n\t}\n\tfor _, lg := range r.Logs {\n\t\td.onLog(lg)\n\t}\n}\n\nfunc main() {\n\ttoken, err := abi.JSON(strings.NewReader(transferABI))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tev := token.Events[\"Transfer\"]\n\tfmt.Println(\"topic0\", ev.ID.Hex())\n\tfmt.Println(\"equals keccak256 of the signature:\", ev.ID == crypto.Keccak256Hash([]byte(ev.Sig)))\n\n\tcontract := common.HexToAddress(\"0x00000000000000000000000000000000000000c0\")\n\timpostor := common.HexToAddress(\"0x00000000000000000000000000000000000000ee\")\n\tfrom := common.HexToAddress(\"0x1a642f0E3c3aF545E7AcBD38b07251B3990914F1\")\n\tto := common.HexToAddress(\"0x00000000000000000000000000000000000000bb\")\n\tdata, err := ev.Inputs.NonIndexed().Pack(big.NewInt(2_500_000))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfromTopic, toTopic := common.BytesToHash(from.Bytes()), common.BytesToHash(to.Bytes())\n\tblockA := common.HexToHash(\"0xa1\")\n\tok := &types.Receipt{\n\t\tStatus: types.ReceiptStatusSuccessful, GasUsed: 51_000,\n\t\tEffectiveGasPrice: big.NewInt(32_000_000_000), BlockHash: blockA,\n\t\tLogs: []*types.Log{\n\t\t\t{Address: contract, Topics: []common.Hash{ev.ID, fromTopic, toTopic}, Data: data, BlockHash: blockA, Index: 4},\n\t\t\t{Address: impostor, Topics: []common.Hash{ev.ID, fromTopic, toTopic}, Data: data, BlockHash: blockA, Index: 5},\n\t\t\t{Address: contract, Topics: []common.Hash{ev.ID, fromTopic, toTopic, common.BigToHash(big.NewInt(9))}, BlockHash: blockA, Index: 6},\n\t\t},\n\t}\n\treverted := &types.Receipt{Status: types.ReceiptStatusFailed, GasUsed: 29_000, EffectiveGasPrice: big.NewInt(32_000_000_000)}\n\n\td := &deposits{token: token, contract: contract, applied: map[string]bool{}, balance: map[common.Address]*big.Int{}}\n\td.onReceipt(ok)\n\td.onLog(ok.Logs[0]) // a duplicate delivery changes nothing\n\td.onReceipt(reverted)\n\tfmt.Printf(\"credited to %s: %s\\n\", to.Hex(), d.balance[to])\n\n\t// Reorg: block A leaves the canonical chain, the log is re-sent with Removed\n\t// set, and the transaction is included again in block B at another index.\n\tgone := *ok.Logs[0]\n\tgone.Removed = true\n\td.onLog(&gone)\n\tagain := *ok.Logs[0]\n\tagain.BlockHash, again.Index = common.HexToHash(\"0xb1\"), 0\n\td.onLog(&again)\n\tfmt.Printf(\"credited after reorg: %s\\n\", d.balance[to])\n}","language":"go","title":"Indexed fields live in topics, the rest in data","walkthrough":"abi.JSON parses the event, and Event.ID is the topic-0 hash computed from Event.Sig. decodeTransfer checks the emitting address first, then requires exactly three topics with the right topic 0: an ERC-721 Transfer has the same signature and topic 0 but indexes tokenId as a fourth topic and leaves Data empty. UnpackIntoInterface fills only the non-indexed Value from Data, and abi.ParseTopics fills From and To from topics 1 and 2. The reverted receipt is charged a fee and credits nothing. Credits are keyed by block hash and log index, so the duplicate delivery is a no-op, the Removed copy reverses the credit, and the re-inclusion in block B is credited once under its new key."},{"body":"Unpacking event data never reads topics. ABI.UnpackIntoInterface and Arguments.Unpack skip indexed arguments entirely, so a struct decoded only from Data has zero-value From and To fields and no error. ParseTopics wants the indexed arguments alone and the topics after topic 0, and it sets struct fields by reflection from the camel-cased ABI names; if the struct lacks a field, it panics rather than returning an error, so keep the struct next to the ABI and cover it with a test. Indexed strings, bytes and arrays cannot be decoded at all, because the topic holds keccak256 of the value instead of the value. When the ABI comes from a third party, decode with the ABI you reviewed for that deployed address, not with whatever interface the contract claims; the abi-calls lesson makes the same point for calls.","title":"Two decoding traps in accounts/abi"},{"body":"Push the cheap filters to the node with an ethereum.FilterQuery: the contract address and topic 0 limit what you download, and a topic-2 filter restricts results to transfers into your own addresses. Then repeat every check in the handler anyway. A provider can be buggy or hostile, a query can be widened later by someone else, and the handler is where the money moves.","code":"transferID := token.Events[\"Transfer\"].ID\nwatched := common.BytesToHash(depositAddress.Bytes())\nq := ethereum.FilterQuery{\n\tFromBlock: new(big.Int).SetUint64(from),\n\tToBlock:   new(big.Int).SetUint64(to), // bounded range, never open-ended\n\tAddresses: []common.Address{tokenAddress},\n\tTopics:    [][]common.Hash{{transferID}, nil, {watched}},\n}\nlogs, err := client.FilterLogs(ctx, q)\nif err != nil {\n\treturn err\n}\nfor i := range logs {\n\td.onLog(&logs[i]) // the same checks as the offline example\n}","language":"go","title":"Filter in the query, verify again in the handler","walkthrough":"Run this fragment in your own native environment against a node for the expected chain. Topics is positional: the first inner slice matches topic 0, nil accepts any sender in position 1, and the third restricts topic 2, the recipient, to the watched address. FilterLogs returns []types.Log by value, so the loop passes the address of each element. Keep the range bounded, because providers cap block spans and result counts; the events-finality lesson covers backfill and checkpoints."},{"body":"Logs from FilterLogs reflect the canonical chain at query time. Logs delivered through SubscribeFilterLogs or polling filters can arrive twice: once when the block is imported and again with Removed set to true when a reorganization takes that block off the canonical chain. The handler must reverse exactly what it applied, which is why the example keys credits by the delivered log's block hash and log index rather than by transaction hash: the same transaction is often re-included on the new branch at another position and deserves its own credit. Reversal is only possible while the credit is still internal. Anything irreversible, such as shipping goods or withdrawing to another chain, should wait for the confirmation or finality policy from the events-finality lesson. Test the handler with a reverted receipt, an impostor contract, a four-topic Transfer, truncated Data, a duplicate delivery and a removed log whose credit was never applied.","title":"Removed logs and what a credit should wait for"}],"takeaway":"Credit a token transfer only from a successful receipt, the expected contract address, the exact topic 0 and topic count, and key the credit so a Removed log reverses precisely what was applied.","title":"Receipts and logs: decode ERC-20 transfers from the right contract and reverse them on reorg","unitID":"blockchain","wrongAnswers":["Topic 0 equals the Transfer event hash; nothing else","The ABI decodes the Data section without an error"]},{"conceptTag":"blockchain.message-signing","designGuide":{"cautions":["ecrecover cannot verify smart-contract wallets; EIP-1271 needs an RPC call.","A login signature must never double as authorization to move value."],"cost":"A nonce table with a TTL and atomic consume, a strict message parser and a test matrix for V, s, domain, expiry and concurrency.","family":"blockchain","flow":["Issue nonce with TTL","Check domain, chain, time","Recover and match address","Consume nonce atomically"],"ratings":[],"strengths":["Password-free logins verified offline with go-ethereum primitives.","Domain binding and single-use nonces defeat relayed and replayed signatures."]},"hint":"The bytes and the signature are identical to the accepted login; only server state has changed.","id":"blockchain.message-signing","introduction":"Wallets can sign arbitrary text as well as transactions, and many services use that to log users in without passwords. The cryptography is the easy part. A recovered address only says that some key signed some bytes; whether those bytes were meant for your site, for now and for exactly one login is decided by the message format and by state your server keeps. This lesson verifies both halves with a fixed test key and an in-memory nonce store.","nuance":"Recovery is stateless and succeeds again for the same bytes. Only the nonce record, deleted when the first login committed, distinguishes the replay from the original.","objective":"Verify an EIP-191 personal signature, normalize its V byte, and accept an EIP-4361 sign-in only for this domain, chain and expiry with an unused server nonce.","question":"An attacker resubmits a user's valid Sign-In with Ethereum message and signature a minute after the user logged in. What makes the server reject it?","references":["https://eips.ethereum.org/EIPS/eip-4361","https://eips.ethereum.org/EIPS/eip-191","https://pkg.go.dev/github.com/ethereum/go-ethereum/accounts#TextHash","https://eips.ethereum.org/EIPS/eip-1271"],"reviewAnswer":"A server-issued nonce consumed once, atomically","reviewPrompt":"What stops a SIWE replay?","sections":[{"body":"EIP-191 version 0x45, the personal_sign format, prefixes the message with \"\\x19Ethereum Signed Message:\\n\" and its decimal byte length, then hashes with keccak256; go-ethereum exposes exactly this as accounts.TextHash. The 0x19 prefix keeps the signed bytes from ever parsing as a valid transaction, so a site cannot get a wallet to sign a transfer by calling it a message. The signature is 65 bytes: R, S and a recovery byte V. crypto.Sign returns V as 0 or 1, while wallets and geth's own eth_sign return 27 or 28 for historical reasons, and crypto.SigToPub accepts only 0 or 1. The signing-boundaries lesson argued that recovery is not authorization; this lesson adds the rules that turn a recovery into a login.","title":"What personal_sign actually signs"},{"body":"The program plays both parties. The wallet side builds an EIP-4361 message, hashes it with TextHash, signs it with a fixed test key and shifts V to 27 or 28 as wallets do. The server side parses the fields it relies on, checks them against its own configuration and clock, recovers the signer and consumes the nonce last. Five attempts show which rule stops which attack.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum/accounts\"\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/crypto\"\n)\n\nconst header = \" wants you to sign in with your Ethereum account:\"\n\nvar fields = map[string]bool{\"URI\": true, \"Version\": true, \"Chain ID\": true,\n\t\"Nonce\": true, \"Issued At\": true, \"Expiration Time\": true}\n\n// recoverPersonal returns the address that produced an EIP-191 personal_sign signature.\nfunc recoverPersonal(message string, sig []byte) (common.Address, error) {\n\tif len(sig) != crypto.SignatureLength {\n\t\treturn common.Address{}, errors.New(\"signature must be 65 bytes\")\n\t}\n\ts := bytes.Clone(sig) // never mutate the caller's slice\n\tif s[64] == 27 || s[64] == 28 {\n\t\ts[64] -= 27 // wallets send 27/28; go-ethereum expects 0/1\n\t}\n\tr, sv := new(big.Int).SetBytes(s[:32]), new(big.Int).SetBytes(s[32:64])\n\tif !crypto.ValidateSignatureValues(s[64], r, sv, true) {\n\t\treturn common.Address{}, errors.New(\"invalid or high-s signature\")\n\t}\n\tpub, err := crypto.SigToPub(accounts.TextHash([]byte(message)), s)\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\treturn crypto.PubkeyToAddress(*pub), nil\n}\n\n// parse reads the EIP-4361 fields this server checks. A production parser\n// should implement the full ABNF, including field order and Resources.\nfunc parse(msg string) (map[string]string, error) {\n\tlines := strings.Split(msg, \"\\n\")\n\tif len(lines) < 8 || !strings.HasSuffix(lines[0], header) {\n\t\treturn nil, errors.New(\"not a sign-in message\")\n\t}\n\tf := map[string]string{\"Domain\": strings.TrimSuffix(lines[0], header), \"Address\": lines[1]}\n\tfor _, line := range lines[2:] {\n\t\tk, v, ok := strings.Cut(line, \": \")\n\t\tif !ok || !fields[k] {\n\t\t\tcontinue // blank lines and the free-text statement\n\t\t}\n\t\tif _, dup := f[k]; dup {\n\t\t\treturn nil, fmt.Errorf(\"duplicate field %q\", k)\n\t\t}\n\t\tf[k] = v\n\t}\n\treturn f, nil\n}\n\ntype Server struct {\n\tDomain, ChainID string\n\tmu              sync.Mutex\n\tnonces          map[string]bool // issued and not yet used\n}\n\nfunc (s *Server) Verify(msg string, sig []byte, now time.Time) (common.Address, error) {\n\tf, err := parse(msg)\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\tif f[\"Domain\"] != s.Domain {\n\t\treturn common.Address{}, fmt.Errorf(\"domain %q is not %q\", f[\"Domain\"], s.Domain)\n\t}\n\tif f[\"URI\"] != \"https://\"+s.Domain+\"/login\" || f[\"Version\"] != \"1\" || f[\"Chain ID\"] != s.ChainID {\n\t\treturn common.Address{}, errors.New(\"wrong URI, version or chain\")\n\t}\n\texp, err := time.Parse(time.RFC3339, f[\"Expiration Time\"])\n\tif err != nil || !now.Before(exp) {\n\t\treturn common.Address{}, errors.New(\"missing or past expiration time\")\n\t}\n\tclaimed := f[\"Address\"]\n\tif !common.IsHexAddress(claimed) || common.HexToAddress(claimed).Hex() != claimed {\n\t\treturn common.Address{}, errors.New(\"address is not EIP-55 checksummed\")\n\t}\n\tsigner, err := recoverPersonal(msg, sig)\n\tif err != nil {\n\t\treturn common.Address{}, err\n\t}\n\tif signer != common.HexToAddress(claimed) {\n\t\treturn common.Address{}, fmt.Errorf(\"signature recovers %s\", signer.Hex())\n\t}\n\ts.mu.Lock() // consuming the nonce is the commit point\n\tdefer s.mu.Unlock()\n\tif !s.nonces[f[\"Nonce\"]] {\n\t\treturn common.Address{}, errors.New(\"nonce unknown or already used\")\n\t}\n\tdelete(s.nonces, f[\"Nonce\"])\n\treturn signer, nil\n}\n\nfunc message(domain string, addr common.Address, nonce string, issued time.Time) string {\n\treturn domain + header + \"\\n\" + addr.Hex() + \"\\n\\n\" +\n\t\t\"Sign in to the dashboard.\\n\\n\" +\n\t\t\"URI: https://\" + domain + \"/login\\nVersion: 1\\nChain ID: 1337\\n\" +\n\t\t\"Nonce: \" + nonce + \"\\n\" +\n\t\t\"Issued At: \" + issued.Format(time.RFC3339) + \"\\n\" +\n\t\t\"Expiration Time: \" + issued.Add(5*time.Minute).Format(time.RFC3339)\n}\n\n// walletSign mimics personal_sign: EIP-191 hash, then V shifted to 27/28.\nfunc walletSign(msg string, key []byte) []byte {\n\tprv, err := crypto.ToECDSA(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsig, err := crypto.Sign(accounts.TextHash([]byte(msg)), prv)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsig[64] += 27\n\treturn sig\n}\n\nfunc main() {\n\ttestKey := bytes.Repeat([]byte{1}, 32) // TEST KEY ONLY, never funded\n\tprv, _ := crypto.ToECDSA(testKey)\n\tuser := crypto.PubkeyToAddress(prv.PublicKey)\n\tnow := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC) // fixed clock for the example\n\tsrv := &Server{Domain: \"app.example.com\", ChainID: \"1337\", nonces: map[string]bool{}}\n\n\t// In production each nonce comes from crypto/rand.Text and is stored with a TTL.\n\tsrv.nonces[\"K7Q2M9XW4PZ3\"], srv.nonces[\"H5R8T2LN6QVA\"] = true, true\n\tmsg := message(\"app.example.com\", user, \"K7Q2M9XW4PZ3\", now)\n\tsig := walletSign(msg, testKey)\n\tfmt.Println(strings.Split(msg, \"\\n\")[0])\n\tfmt.Println(\"wallet V byte:\", sig[64])\n\n\tflipped := bytes.Clone(sig)\n\tflipped[64] = 27 + 28 - flipped[64] // 27 <-> 28: valid, but for another key\n\ttry := func(label, m string, s []byte, at time.Time) {\n\t\taddr, err := srv.Verify(m, s, at)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%-9s rejected: %v\\n\", label, err)\n\t\t\treturn\n\t\t}\n\t\tfmt.Printf(\"%-9s signed in as %s\\n\", label, addr.Hex())\n\t}\n\ttry(\"flipped V\", msg, flipped, now)\n\ttry(\"login\", msg, sig, now.Add(30*time.Second))\n\ttry(\"replay\", msg, sig, now.Add(40*time.Second))\n\n\tphish := message(\"evil.example\", user, \"H5R8T2LN6QVA\", now)\n\ttry(\"phishing\", phish, walletSign(phish, testKey), now)\n\tlate := message(\"app.example.com\", user, \"H5R8T2LN6QVA\", now)\n\ttry(\"late\", late, walletSign(late, testKey), now.Add(6*time.Minute))\n}","language":"go","title":"Verify a sign-in end to end","walkthrough":"recoverPersonal copies the signature before normalizing V, rejects high-s values with ValidateSignatureValues and recovers with SigToPub over TextHash of the exact message text. Swapping V between 27 and 28 is not detected as malformed: it recovers a different, valid-looking address, so only the comparison with the claimed address catches it, and the nonce survives that failure. The genuine login succeeds and deletes the nonce, so the identical replay fails. A message signed for evil.example fails the domain check even though its signature is perfect, and a message presented six minutes later fails its five-minute expiration. The clock is a fixed value so the output is deterministic."},{"body":"A Sign-In with Ethereum message is plain text with a fixed layout: the requesting domain, the account in EIP-55 checksum form, an optional statement for the user, then URI, Version (1), Chain ID, Nonce, Issued At and optional Expiration Time, Not Before, Request ID and Resources lines. Every value the server compares must come from server state, never from the message: the expected domain and URI from configuration, the chain ID from the deployment, the time from the server clock and the nonce from the server's own store. EIP-4361 requires at least eight alphanumeric characters of nonce; crypto/rand.Text returns 26 base32 characters, which fits. The domain check defeats a phishing site that relays a genuine signature: the wallet shows the user which domain is asking, and your server refuses any domain but its own. Parse strictly against the specification's ABNF and reject duplicate fields, because two parsers that disagree about which Nonce line counts are a vulnerability. The example's parser is deliberately small and skips Issued At and Not Before checks that a real verifier performs with a bounded clock skew.","title":"The EIP-4361 fields the server must own"},{"body":"The in-memory map and mutex model a single process. A real deployment issues nonces from a shared store with a time-to-live and consumes them with one atomic operation, so two concurrent submissions of the same signed message cannot both succeed. Run the stateless checks and signature recovery first, and make the consume the final step that commits the login.","code":"// Issue: bind each nonce to the pre-login browser session that asked for it.\nnonce := rand.Text() // crypto/rand: 26 base32 characters\nif _, err := db.ExecContext(ctx,\n\t`INSERT INTO siwe_nonces (nonce, session_id, expires_at)\n\t VALUES ($1, $2, now() + interval '5 minutes')`, nonce, sessionID); err != nil {\n\treturn err\n}\n\n// Verify: only after domain, URI, chain, expiry and signature checks pass.\nres, err := db.ExecContext(ctx,\n\t`DELETE FROM siwe_nonces WHERE nonce = $1 AND session_id = $2 AND expires_at > now()`,\n\tfields[\"Nonce\"], sessionID)\nif err != nil {\n\treturn err\n}\nif n, err := res.RowsAffected(); err != nil || n != 1 {\n\treturn errors.New(\"nonce unknown, expired or already used\")\n}","language":"go","title":"Store nonces so a replay loses the race","walkthrough":"This fragment needs a PostgreSQL database, so it runs in your own native environment; db is a *sql.DB and sessionID identifies the pre-login browser session. Binding the nonce to that session stops a signed message captured from one session from being redeemed in another. The DELETE with the expiry condition is the atomic test-and-consume: when two requests race, exactly one sees RowsAffected equal to 1. After a successful login, issue a fresh session identifier instead of promoting the pre-login one."},{"body":"ecrecover verifies only externally owned accounts. A smart-contract wallet has no single private key; it validates signatures through EIP-1271 isValidSignature, which needs an eth_call on the chain named in the message, so supporting those wallets adds an RPC-dependent path with the timeouts and trust questions of the rpc-boundaries lesson. KMS and HSM signers can return a high s value; normalize it (s becomes n - s and V flips) before publishing, because EIP-2 makes high-s transactions invalid and many message verifiers, including this one, reject them. Sign-in proves control of an address at login time and nothing more: map it to an account, issue your own session with its own expiry, and require a fresh, purpose-specific signature or EIP-712 typed data for anything that moves value. Test the verifier with a wrong domain, URI or chain, a missing or past expiration, an unchecksummed address, V of 0, 1, 27 and 28, a high-s signature, a duplicate Nonce line and two concurrent submissions.","title":"Limits worth stating in a review"}],"takeaway":"A valid signature only recovers an address; a login also needs your domain, URI and chain, an unexpired message and a server-issued nonce that is consumed atomically exactly once.","title":"Signed messages and Sign-In with Ethereum: recover the right address and refuse replays","unitID":"blockchain","wrongAnswers":["The signature no longer recovers the same address","Wallets never produce the same signature twice"]},{"conceptTag":"blockchain.rpc-providers","designGuide":{"cautions":["Agreement among providers that share one upstream is a single vote.","AtHash helpers send requireCanonical false; use the raw client when it matters."],"cost":"Extra header calls per pinned read, a provider pool with health state and metrics, and a retry policy that must be tuned and reviewed.","family":"blockchain","flow":["Verify chain per provider","Pin block hash by majority","Read only at pinned hash","Bounded retry, then failover"],"ratings":[],"strengths":["A lagging or forked provider is detected instead of silently trusted.","Fakes behind the ethclient interface make outage drills instant and deterministic."]},"hint":"Think about what names one chain state unambiguously, even across forks.","id":"blockchain.rpc-providers","introduction":"Production services rarely trust one JSON-RPC endpoint: providers have outages, rate limits, stale replicas and occasionally wrong data. Adding a second URL does not fix that by itself. Reads must agree on which block they describe, a provider that disagrees must be detected rather than averaged in, and retries must stop before they turn a provider incident into your outage. This lesson models providers in memory behind the same interface ethclient implements.","nuance":"A block number can name different blocks on different forks and latest moves between calls; a hash names one block, and a provider that lacks it fails loudly instead of answering from another state.","objective":"Pin multi-provider reads to an agreed block hash, quarantine providers that disagree or lag, and fail over with bounded retries and backoff.","question":"Two providers answer latest for different blocks. What makes reads across several providers consistent?","references":["https://pkg.go.dev/github.com/ethereum/go-ethereum/ethclient#Client.BalanceAtHash","https://eips.ethereum.org/EIPS/eip-1898","https://pkg.go.dev/golang.org/x/time/rate#Limiter.Wait","https://sre.google/sre-book/addressing-cascading-failures/"],"reviewAnswer":"Pin every read to one agreed block hash","reviewPrompt":"Consistent multi-provider reads?","sections":[{"body":"Two providers asked for latest at the same moment can answer for different blocks, and a load-balanced endpoint can serve two consecutive calls from two different backends. A balance from one call and an allowance from the next may then describe states that never coexisted. Pick the block first, usually head minus your confirmation depth or the finalized tag, resolve it to a hash, and make every later read refer to that hash. A read by number lets a provider on another fork answer quietly from its own state; a read by hash, as EIP-1898 allows, fails loudly when the provider does not have that block. The rpc-boundaries lesson already verifies the chain ID and bounds each call; pinning is the next layer.","title":"Latest is not a coordinate"},{"body":"The program defines Reader as the two ethclient methods the service needs, and a compile-time assertion proves that *ethclient.Client satisfies it, so fakes and the real client are interchangeable. Five fake providers cover the cases: three agree on block 100, one serves a forked header, one is still at block 99, and the first healthy one is rate limited. pin computes each header hash locally and requires a strict majority of all configured providers; balance then reads at the pinned hash with bounded per-provider retries.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/ethereum/go-ethereum\"\n\t\"github.com/ethereum/go-ethereum/common\"\n\t\"github.com/ethereum/go-ethereum/core/types\"\n\t\"github.com/ethereum/go-ethereum/ethclient\"\n\t\"github.com/ethereum/go-ethereum/rpc\"\n)\n\n// Reader is the slice of *ethclient.Client this service depends on.\ntype Reader interface {\n\tHeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)\n\tBalanceAtHash(ctx context.Context, account common.Address, block common.Hash) (*big.Int, error)\n}\n\nvar _ Reader = (*ethclient.Client)(nil) // the real client fits the same interface\n\ntype Provider struct {\n\tName string\n\tReader\n}\n\n// fake is an in-memory node: a header per height, a balance per block hash and a\n// script of failures returned before any balance read succeeds.\ntype fake struct {\n\theaders  map[uint64]*types.Header\n\tbalances map[common.Hash]*big.Int\n\tfailures []error\n}\n\nfunc (f *fake) HeaderByNumber(ctx context.Context, n *big.Int) (*types.Header, error) {\n\tif h, ok := f.headers[n.Uint64()]; ok {\n\t\treturn h, nil\n\t}\n\treturn nil, ethereum.NotFound // what ethclient returns for a null block\n}\n\nfunc (f *fake) BalanceAtHash(ctx context.Context, _ common.Address, block common.Hash) (*big.Int, error) {\n\tif err := ctx.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\tif len(f.failures) > 0 {\n\t\terr := f.failures[0]\n\t\tf.failures = f.failures[1:]\n\t\treturn nil, err\n\t}\n\tif b, ok := f.balances[block]; ok {\n\t\treturn new(big.Int).Set(b), nil\n\t}\n\treturn nil, errors.New(\"header for hash not found\")\n}\n\n// pin asks every provider for the header at n and accepts a hash only if a strict\n// majority of all configured providers return it.\nfunc pin(ctx context.Context, ps []Provider, n uint64) (common.Hash, []Provider, error) {\n\tanswers := make([]common.Hash, len(ps))\n\tvotes := map[common.Hash]int{}\n\tvar best common.Hash\n\tfor i, p := range ps {\n\t\th, err := p.HeaderByNumber(ctx, new(big.Int).SetUint64(n))\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s: no header %d (%v), excluded\\n\", p.Name, n, err)\n\t\t\tcontinue\n\t\t}\n\t\tanswers[i] = h.Hash() // computed locally from the returned header fields\n\t\tvotes[answers[i]]++\n\t\tif votes[answers[i]] > votes[best] {\n\t\t\tbest = answers[i]\n\t\t}\n\t}\n\tif 2*votes[best] <= len(ps) {\n\t\treturn common.Hash{}, nil, fmt.Errorf(\"no majority for block %d\", n)\n\t}\n\tvar agreeing []Provider\n\tfor i, p := range ps {\n\t\tswitch answers[i] {\n\t\tcase best:\n\t\t\tagreeing = append(agreeing, p)\n\t\tcase common.Hash{}:\n\t\tdefault:\n\t\t\tfmt.Printf(\"%s: reports %s at %d, quarantined\\n\", p.Name, answers[i].TerminalString(), n)\n\t\t}\n\t}\n\treturn best, agreeing, nil\n}\n\nfunc retryable(err error) bool {\n\tvar httpErr rpc.HTTPError\n\tif errors.As(err, &httpErr) {\n\t\treturn httpErr.StatusCode == http.StatusTooManyRequests || httpErr.StatusCode >= 500\n\t}\n\treturn errors.Is(err, context.DeadlineExceeded)\n}\n\ntype Backoff struct {\n\tAttempts   int\n\tBase, Max  time.Duration\n\tSleep      func(context.Context, time.Duration) error\n\tPerAttempt time.Duration\n}\n\n// balance tries each agreeing provider in order with bounded, growing waits.\nfunc balance(ctx context.Context, ps []Provider, b Backoff, a common.Address, block common.Hash) (*big.Int, error) {\n\tfor _, p := range ps {\n\t\twait := b.Base\n\t\tfor attempt := 1; attempt <= b.Attempts; attempt++ {\n\t\t\tcallCtx, cancel := context.WithTimeout(ctx, b.PerAttempt)\n\t\t\tv, err := p.BalanceAtHash(callCtx, a, block)\n\t\t\tcancel()\n\t\t\tif err == nil {\n\t\t\t\tfmt.Printf(\"%s: balance at %s = %s wei\\n\", p.Name, block.TerminalString(), v)\n\t\t\t\treturn v, nil\n\t\t\t}\n\t\t\tif !retryable(err) || attempt == b.Attempts {\n\t\t\t\tfmt.Printf(\"%s: attempt %d: %v, next provider\\n\", p.Name, attempt, err)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tfmt.Printf(\"%s: attempt %d: %v, retry in %v\\n\", p.Name, attempt, err, wait)\n\t\t\tif err := b.Sleep(ctx, wait); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\twait = min(2*wait, b.Max)\n\t\t}\n\t}\n\treturn nil, errors.New(\"all providers failed\")\n}\n\nfunc main() {\n\theader := func(n uint64, root byte) *types.Header {\n\t\treturn &types.Header{Number: new(big.Int).SetUint64(n), Difficulty: new(big.Int), Root: common.Hash{root}}\n\t}\n\tcanonical, fork := header(100, 0xaa), header(100, 0xbb)\n\tlimited := rpc.HTTPError{StatusCode: 429, Status: \"429 Too Many Requests\"}\n\tfunds := map[common.Hash]*big.Int{canonical.Hash(): big.NewInt(5_000_000_000_000_000_000)}\n\n\tproviders := []Provider{\n\t\t{\"alpha\", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds,\n\t\t\tfailures: []error{limited, limited, limited}}},\n\t\t{\"beta\", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds}},\n\t\t{\"gamma\", &fake{headers: map[uint64]*types.Header{100: canonical}, balances: funds}},\n\t\t{\"delta\", &fake{headers: map[uint64]*types.Header{100: fork}}},\n\t\t{\"epsilon\", &fake{headers: map[uint64]*types.Header{99: header(99, 0xaa)}}},\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)\n\tdefer cancel()\n\n\thash, agreeing, err := pin(ctx, providers, 100)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"pinned block 100 = %s, agreed by %d of %d\\n\", hash.TerminalString(), len(agreeing), len(providers))\n\n\tvar slept time.Duration\n\tpolicy := Backoff{Attempts: 3, Base: 100 * time.Millisecond, Max: time.Second, PerAttempt: 500 * time.Millisecond,\n\t\tSleep: func(_ context.Context, d time.Duration) error { slept += d; return nil }}\n\tif _, err := balance(ctx, agreeing, policy, common.HexToAddress(\"0xbb\"), hash); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"total backoff:\", slept)\n}","language":"go","title":"Outvote, then fail over","walkthrough":"Header.Hash() is keccak256 over the RLP of the returned fields, so the client computes it rather than trusting a quoted hash. epsilon has no header 100 and returns ethereum.NotFound, which is what ethclient reports for a null block, so it is excluded rather than counted as dissent. delta's header differs and so does its hash; it is quarantined. Three of five agree, a strict majority. alpha answers every balance call with an rpc.HTTPError of status 429; retryable treats 429 and 5xx as transient, waits 100ms and then 200ms, and after the third attempt moves on. beta answers at the pinned hash. Sleep is injected, so the run is instant and the total backoff of 300ms can be asserted instead of waited for."},{"body":"With real endpoints the shape stays the same: dial each provider with an explicit HTTP client, verify its chain ID before it joins the pool, and wrap it with a client-side limiter so your own traffic stays under the provider's quota instead of discovering the quota through 429 responses.","code":"type limited struct {\n\tReader\n\tlim *rate.Limiter\n}\n\nfunc (l limited) BalanceAtHash(ctx context.Context, a common.Address, h common.Hash) (*big.Int, error) {\n\tif err := l.lim.Wait(ctx); err != nil { // errors out if the wait would pass the deadline\n\t\treturn nil, err\n\t}\n\treturn l.Reader.BalanceAtHash(ctx, a, h)\n}\n\nfunc dial(ctx context.Context, name, url string, want *big.Int) (Provider, error) {\n\trc, err := rpc.DialOptions(ctx, url, rpc.WithHTTPClient(&http.Client{Timeout: 10 * time.Second}))\n\tif err != nil {\n\t\treturn Provider{}, err\n\t}\n\tclient := ethclient.NewClient(rc)\n\tid, err := client.ChainID(ctx)\n\tif err != nil || id.Cmp(want) != 0 {\n\t\tclient.Close()\n\t\treturn Provider{}, fmt.Errorf(\"%s: chain %v, want %v (err %v)\", name, id, want, err)\n\t}\n\treturn Provider{Name: name, Reader: limited{client, rate.NewLimiter(20, 5)}}, nil\n}\n\n// After dialing: choose the coordinate once, then confirm it across providers.\nfin, err := providers[0].HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber)))\nif err != nil {\n\treturn err\n}\nhash, agreeing, err := pin(ctx, providers, fin.Number.Uint64())","language":"go","title":"Wire real clients behind the same interface","walkthrough":"This fragment dials real endpoints, so run it in your own native environment with URLs from configuration and never with credentials in source. rpc.WithHTTPClient supplies an http.Client whose Timeout caps every HTTP exchange, in addition to per-call contexts. A provider reporting another chain ID never joins the pool. rate.NewLimiter(20, 5) allows 20 requests per second with bursts of 5, and Wait returns an error instead of sleeping past the context deadline. rpc.FinalizedBlockNumber selects the finalized tag; pin then confirms that block hash across providers before any read."},{"body":"Agreement is evidence only if the providers are independent: three brands reselling one upstream are one vote, and the strongest single check is a node you operate or a light client that verifies consensus. Pinning by hash has a subtlety in this release: ethclient's BalanceAtHash, CallContractAtHash and the other AtHash helpers send requireCanonical as false, so a node may answer from a block it still stores after a reorg removed it from the canonical chain. When that matters, call the raw rpc.Client with rpc.BlockNumberOrHashWithHash(hash, true); geth then fails with hash is not currently canonical. Retry only reads and only transient classes (429, 5xx, timeouts), with a per-attempt timeout, an attempt cap per provider and an overall deadline, and add random jitter so many workers do not retry in lockstep; the example omits jitter to stay deterministic. go-ethereum's HTTPError carries the status and body but not response headers, so honoring Retry-After needs a custom http.RoundTripper. Never fail over a send by assuming a timeout meant failure; the raw-transactions lesson explains why.","title":"Quorum, canonical hashes and retry budgets"},{"body":"Because the service depends on an interface, failure modes are cheap to script: a provider one block behind, one on a fork, one returning 429 for a minute, one that hangs until the context expires, one that returns a malformed header, and all of them at once. Assert outcomes rather than just errors: which provider was quarantined, how many attempts ran, the total backoff, and that no read used a block other than the pinned hash. Export the same facts as production metrics: per-provider error rate by class, head lag in blocks, disagreements per hour and retry budget spent. A disagreement is an incident to investigate, not noise to retry away.","title":"Test the pool like a distributed system"}],"takeaway":"Choose one block, resolve it to a hash that a majority of independent providers agree on, read only at that hash, and retry transient failures within a fixed budget before failing over.","title":"Several RPC providers: pin reads to one block hash, outvote a lagging or lying node, retry within bounds","unitID":"blockchain","wrongAnswers":["Average the values returned by all providers","Retry each call until two providers return equal values"]}],"revision":"2026-11-18.1","schemaVersion":1,"solutions":{},"units":[{"id":"blockchain-foundations","lessons":[{"conceptTags":["blockchain.hash-chains"],"explanation":"A blockchain's first job is evidence, not consensus: if a past record changes, the change must show. Each block stores the hash of its predecessor, so editing one block breaks the link that points at it. That guarantee holds only when every party hashes the same bytes for the same block, and only when the newest hash is kept somewhere the editor cannot rewrite.","id":"blockchain.hash-chains","objective":"Link blocks with SHA-256 over a canonical byte encoding, verify the chain from genesis and report the first link that breaks.","task":{"reading":{}},"title":"Hash chains: every block commits to the exact bytes of the block before it"},{"conceptTags":["blockchain.merkle-proofs"],"explanation":"A block header cannot carry every transaction, but it can carry one 32-byte Merkle root that commits to all of them. A client that trusts the header can then check that a particular transaction is included from a handful of sibling hashes instead of the whole block. The tree shape and hashing rules are consensus rules, and two classic mistakes let different transaction lists produce the same root.","id":"blockchain.merkle-proofs","objective":"Build a domain-separated Merkle tree, generate and verify inclusion proofs, and explain the duplicate-leaf and second-preimage pitfalls.","task":{"reading":{}},"title":"Merkle proofs: show one transaction is in a block with about log2(n) hashes"},{"conceptTags":["blockchain.signatures"],"explanation":"A hash chain shows that data changed; a signature shows who approved it. Ethereum and Bitcoin use ECDSA over the secp256k1 curve, and Ethereum appends a recovery byte so that a verifier can compute the signer's public key from the signature instead of receiving it. Recovery always produces some key, so the code that matters is the comparison with the address you expected and the checks that reject malleable signatures.","id":"blockchain.signatures","objective":"Sign a Keccak-256 digest with go-ethereum's crypto package, recover and check the signer's address, and enforce the low-s rule on untrusted signatures.","task":{"reading":{}},"title":"secp256k1 signatures: sign a 32-byte digest, recover the signer and reject high-s twins"},{"conceptTags":["blockchain.addresses-checksums"],"explanation":"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.","id":"blockchain.addresses-checksums","objective":"Derive an address from a public key, produce and check EIP-55 checksums, and validate user-supplied addresses, including the zero address.","task":{"reading":{}},"title":"Ethereum addresses: 20 bytes of Keccak-256, an EIP-55 checksum and strict input validation"},{"conceptTags":["blockchain.accounts-utxo"],"explanation":"Every ledger must answer one question before it accepts a payment: has this value already been spent? Bitcoin answers with a set of unspent transaction outputs that each transaction consumes and creates. Ethereum answers with a balance and a nonce per account that each transaction updates. Neither stores a wallet's balance as a primary fact; both derive it from accepted history, and that choice shapes every indexer built on top.","id":"blockchain.accounts-utxo","objective":"Implement minimal UTXO and account ledgers in Go, reject double spends in each, and explain what each model makes easy or hard for an indexer.","task":{"reading":{}},"title":"Account model versus UTXO: two ledgers and two ways to stop a double spend"},{"conceptTags":["blockchain.rlp-encoding"],"explanation":"Ethereum hashes and signs bytes, so every value needs exactly one byte form. On the execution layer that form is Recursive Length Prefix (RLP): transactions, headers and receipts are RLP, and typed transactions are a type byte followed by an RLP payload. RLP encodes byte strings and nested lists and nothing else. go-ethereum's decoder is deliberately strict, because accepting a second spelling of a value means accepting a second hash for it.","id":"blockchain.rlp-encoding","objective":"Encode and decode Go structs with go-ethereum's rlp package, recognize the canonical-form rules, and bound untrusted input before decoding it.","task":{"reading":{}},"title":"RLP: Ethereum's canonical encoding, and why its decoder rejects every other spelling"},{"conceptTags":["blockchain.proof-of-work"],"explanation":"A hash chain reveals that history changed, but anyone can rebuild a chain. Proof of work makes rebuilding expensive: a block counts only if its header hashes below a target, and the only known way to find such a header is to try nonces. Bitcoin still works this way; Ethereum left proof of work at the Merge in 2022. The idea to keep is the asymmetry between expensive search and cheap verification.","id":"blockchain.proof-of-work","objective":"Mine a toy block against a big.Int target, verify it with one hash, compute its expected work and retarget from observed block times.","task":{"reading":{}},"title":"Proof of work: finding a nonce takes thousands of hashes, checking it takes one"},{"conceptTags":["blockchain.fork-choice"],"explanation":"Two valid blocks can extend the same parent, and nodes need a rule that makes them converge on one branch. Proof-of-work chains follow the branch with the most cumulative work; when a heavier branch appears, the node reorganizes, and blocks it had accepted stop being canonical. Anything an indexer derived from those blocks must be undone, and anything irreversible should have waited for finality.","id":"blockchain.fork-choice","objective":"Implement a heaviest-chain fork-choice rule, compute a reorganization's undo and apply path, apply confirmation depth, and use Ethereum's safe and finalized tags.","task":{"reading":{}},"title":"Fork choice and reorgs: follow the heaviest chain and undo what the old branch indexed"}],"summary":"Hash chains, Merkle proofs, signatures, addresses, account and UTXO ledgers, RLP, proof of work and fork choice.","title":"Blockchain foundations in Go","translationNote":"Local models with reviewed Go libraries and fixed test keys. Nothing here creates a wallet, connects to a node or signs a real transaction."},{"id":"blockchain","lessons":[{"conceptTags":["blockchain.packages"],"explanation":"Go is used for blockchain nodes and infrastructure, but a backend that reads balances is not the same system as a validator or a signing service. Start with the target network and the operation you must perform. Prefer the protocol’s maintained libraries, inspect their module boundaries and pin a reviewed release. Adding every blockchain SDK increases dependencies without proving correctness.","id":"blockchain.packages","objective":"Distinguish RPC applications, transaction tooling and consensus/application frameworks.","task":{"reading":{}},"title":"Go in blockchain: choose packages by the protocol and the job"},{"conceptTags":["blockchain.rpc-boundaries"],"explanation":"An Ethereum RPC endpoint is an external dependency with latency, availability and trust limits. A successful TCP connection does not prove that the endpoint serves the intended chain or that every call will finish. Use typed clients, time-bounded operations and an expected chain ID configured by the application. Keep node credentials out of logs and never treat RPC data as authenticated business authority by default.","id":"blockchain.rpc-boundaries","objective":"Use an explicit RPC client, operation deadline and expected chain identity.","task":{"reading":{}},"title":"Ethereum RPC: verify the chain and bound every operation"},{"conceptTags":["blockchain.exact-units"],"explanation":"Token amounts frequently exceed the exact integer range of float64, even when the human-readable value looks small. Converting through a float before math/big permanently loses information. Parse text under an explicit decimal-scale policy, reject unsupported precision and preserve the integer base-unit value. Token metadata is input to validate, not an instruction to allocate unbounded memory.","id":"blockchain.exact-units","objective":"Convert validated decimal text to bounded integer base units with an explicit scale.","task":{"reading":{}},"title":"Token amounts: parse exact base units without float64"},{"conceptTags":["blockchain.abi-calls"],"explanation":"An ABI describes how to encode a call and decode its result. It does not prove that the target address has the expected code or that a read result will remain true in a future transaction. An eth_call evaluates a call against a selected chain state without committing it. State-changing execution requires a separate signed transaction lifecycle and can fail even after a successful simulation.","id":"blockchain.abi-calls","objective":"Distinguish ABI packing, read simulation, signed transactions and deployment identity.","task":{"reading":{}},"title":"Contract ABI: encoding is not permission and eth_call is not a transaction"},{"conceptTags":["blockchain.nonces-outcomes"],"explanation":"Two Go workers can read the same pending nonce and sign conflicting transactions. A process-local mutex helps only while one process owns the account; it does not coordinate replicas or survive a crash. Give each business intent a stable identity, persist its nonce and signed transaction identity under one ownership protocol, and reconcile unknown send outcomes before allocating new work.","id":"blockchain.nonces-outcomes","objective":"Coordinate transaction intent and account nonce allocation before retrying a send.","task":{"reading":{}},"title":"Nonces, fees and unknown outcomes: one durable owner per account"},{"conceptTags":["blockchain.signing-boundaries"],"explanation":"A signing key is authority, not an ordinary configuration string. An RPC URL, ABI helper or generic retry function should not automatically receive it. Separate construction and policy validation from key custody, bind transactions to the intended chain, and record what was approved without logging private keys or seed material. Read-only blockchain work does not require a signer at all.","id":"blockchain.signing-boundaries","objective":"Validate transaction intent before delegating signing to an explicitly owned key service.","task":{"reading":{}},"title":"Signing policy: bind the chain and keep key custody separate"},{"conceptTags":["blockchain.events-finality"],"explanation":"A WebSocket subscription is a live notification channel, not a durable ledger cursor. A process can disconnect, a provider can drop a slow subscriber and a chain can reorganize recently observed blocks. Store a checkpoint that includes chain identity and block hash, backfill a bounded range after reconnect and make the projection’s rollback or rebuild behavior explicit.","id":"blockchain.events-finality","objective":"Persist canonical checkpoints and reconcile removed or missing events before final effects.","task":{"reading":{}},"title":"Index events through disconnects and reorgs, not just the happy subscription"},{"conceptTags":["blockchain.eip1559-fees"],"explanation":"Since the London upgrade an Ethereum transaction no longer names one gas price. It carries two caps chosen by the sender, while the protocol sets a per-block base fee that is burned. The price actually paid is decided only when a block includes the transaction, so the code that builds it has to reason about the worst case. This lesson computes those numbers exactly and puts a ceiling in front of the signer that no fee oracle can raise.","id":"blockchain.eip1559-fees","objective":"Derive maxFeePerGas and maxPriorityFeePerGas with big.Int, predict the effective gas price for any base fee and enforce a fee ceiling before signing.","task":{"reading":{}},"title":"EIP-1559 fees: compute the effective gas price exactly and refuse to sign above a ceiling"},{"conceptTags":["blockchain.raw-transactions"],"explanation":"eth_sendRawTransaction takes one opaque byte string. Everything that matters about a transfer, including its chain, nonce, fees, destination, the signer and its future on-chain hash, is fixed when those bytes are produced, before any node sees them. Producing, checking and storing the bytes offline turns a network call with an unknown outcome into a lookup you can repeat.","id":"blockchain.raw-transactions","objective":"Sign a typed transaction with a test key, round-trip its raw bytes, recover the sender and use the precomputed hash to make retries safe.","task":{"reading":{}},"title":"Raw transactions offline: sign, encode, decode and recover the sender before anything is broadcast"},{"conceptTags":["blockchain.receipts-logs"],"explanation":"A receipt is the node's report of what a transaction did: whether execution succeeded, how much gas it used and which events contracts emitted. Deposit detectors, payment processors and indexers turn those events into balances, which makes the decoding rules security rules. Anyone can deploy a contract that emits a log shaped exactly like a token transfer, and a log from a block that is later reorganized away has to be reversed.","id":"blockchain.receipts-logs","objective":"Interpret receipt status and gas, decode an ERC-20 Transfer log with accounts/abi, and reject impostor or removed logs before crediting a balance.","task":{"reading":{}},"title":"Receipts and logs: decode ERC-20 transfers from the right contract and reverse them on reorg"},{"conceptTags":["blockchain.message-signing"],"explanation":"Wallets can sign arbitrary text as well as transactions, and many services use that to log users in without passwords. The cryptography is the easy part. A recovered address only says that some key signed some bytes; whether those bytes were meant for your site, for now and for exactly one login is decided by the message format and by state your server keeps. This lesson verifies both halves with a fixed test key and an in-memory nonce store.","id":"blockchain.message-signing","objective":"Verify an EIP-191 personal signature, normalize its V byte, and accept an EIP-4361 sign-in only for this domain, chain and expiry with an unused server nonce.","task":{"reading":{}},"title":"Signed messages and Sign-In with Ethereum: recover the right address and refuse replays"},{"conceptTags":["blockchain.rpc-providers"],"explanation":"Production services rarely trust one JSON-RPC endpoint: providers have outages, rate limits, stale replicas and occasionally wrong data. Adding a second URL does not fix that by itself. Reads must agree on which block they describe, a provider that disagrees must be detected rather than averaged in, and retries must stop before they turn a provider incident into your outage. This lesson models providers in memory behind the same interface ethclient implements.","id":"blockchain.rpc-providers","objective":"Pin multi-provider reads to an agreed block hash, quarantine providers that disagree or lag, and fail over with bounded retries and backoff.","task":{"reading":{}},"title":"Several RPC providers: pin reads to one block hash, outvote a lagging or lying node, retry within bounds"}],"summary":"Package roles, RPC, exact units, ABI, nonces, key custody, reorg-safe indexing, fees, raw transactions, receipts, message signing and providers.","title":"Blockchain infrastructure","translationNote":"Developer preparation using local models, reviewed protocol libraries and test environments. This section does not add a wallet, node, signing service or guest networking to GopherForge."}]}