Skip to content
Tech Interview Prep
Technical interview guide

Blockchain & Distributed Ledger Fundamentals

What a blockchain actually is: a replicated, append-only ledger, and why that structure trades off against a conventional database.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: NISTIR 8202; Bitcoin white paper; Ethereum developer documentation and proof-of-stake behavior reviewed 2026-09-04; Hyperledger Fabric latest documentation; IPFS documentation reviewed 2026-09-04.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Explain tamper evidence and the limits of blockchain immutability.

Answer

Core answer (first 90 seconds).

Tamper evidence means any change to committed history is detectable by anyone holding the chain, because each block header commits to its parent's hash. Immutability is the stronger, economic claim: rewriting history costs more than it gains, under stated assumptions. Those assumptions are the whole answer: name the adversary threshold, the finality model, and the recovery path, or you are just asserting.

Mechanism.

A block header contains the parent block's hash. Change one byte in block N and its hash changes, so block N+1's parent pointer no longer matches; every later block must be re-mined or re-signed. Detection is mechanical: a full node checks (1) parent-hash linkage, (2) that the header meets the consensus rule (PoW below the difficulty target, or a valid signature set) and (3) state-transition validity. A light client checks headers and the PoW chain but trusts the heaviest chain.

Bitcoin (PoW)Ethereum (PoS, post-Merge)
Rewrite threshold>50% of hashrate≥1/3 of staked ETH signing conflicting checkpoints
CostRent/acquire majority hashrate; ~600 EH/s network (2024) makes this infeasible at scaleAttacker's stake is slashed, plus a correlation penalty; ~34M ETH staked makes this multi-billion-dollar
FinalityProbabilistic; 6 confirmations (~60 min) is convention for high-value settlementCasper FFG: 32 slots/epoch × 12 s = 6.4 min/epoch; justified then finalized ~2 epochs later (~12.8 min)

Finality is economic, not physical.

Failure modes, with detection.

  • 51% on small PoW chains. Ethereum Classic was reorged 7,000 blocks in Aug 2020, enabling double-spends ($5.6M reported). Detection: sudden deep reorg, orphaned blocks, exchange deposit reversals.
  • Governance override. Ethereum's 2016 hard fork moved ~3.6M ETH from the DAO attacker. Detection: client release with a state change at a fixed block; nodes that do not upgrade split off.
  • Software bug. Bitcoin's 2010 value-overflow bug minted 184 billion BTC in block 74638; patched by hard fork within hours. Detection: supply invariant violated, node divergence.
  • Weak subjectivity (PoS). A brand-new node cannot verify history from genesis alone; it needs a recent trusted checkpoint (weak-subjectivity period on the order of weeks). Detection: none from the node itself. It is a trust assumption.
  • Social recovery / key compromise. An exchange or foundation can freeze or move funds without touching consensus.

Trade-offs.

Chain-anchored hash vs full on-chain storage: anchoring a 32-byte hash proves a document existed at a block time, cheaply, but says nothing about availability or content. You still need the off-chain copy. Full on-chain storage makes content retrievable from the chain but costs gas per byte and is public. Decide by what you must prove: existence/timestamp → anchor; retrievability → store or use a data-availability layer; confidentiality → neither, use encryption or a private ledger.

Immutability also never establishes input truth (garbage in, committed garbage out), legality, or availability.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Compare UTXO and account-based ledger models.

Answer

Assume we're comparing Bitcoin's UTXO model with Ethereum's account model, both as full nodes validating a chain. The decisive difference is what "state" is: UTXO state is a set of immutable, single-use outputs; account state is a mutable mapping from address to {nonce, balance, code, storage}.

In UTXO, a transaction names inputs as txid:vout and creates new outputs. Validating an input is local: you need the referenced output and the spending transaction's script. There is no per-account counter; replay protection comes from the fact that an output can be spent only once, and the spending txid is unique. Bitcoin Core parallelizes signature verification across a script-check thread pool, but the UTXO set update is sequential because a transaction in a block can spend an output created earlier in the same block. So "parallelism" is real for script checks, not for the whole state transition.

In an account model, a transaction carries a nonce that must equal the sender's current nonce + 1. That makes transactions from one account strictly ordered. Validation touches shared mutable state: the sender's balance and nonce, and any contract storage the call touches. Ethereum's state root in each block header commits to all accounts, so a light client can verify an account's balance with a Merkle Patricia proof. Bitcoin's header commits to the transaction Merkle root but not to the UTXO set, so proving an output is unspent requires the UTXO set itself.

DimensionUTXO (Bitcoin)Account (Ethereum)
Stateset of unspent outputsmapping address -> {nonce, balance, code, storage}
Replay protectionoutput spent once; txid uniquenonce per account
Orderingnone between independent txsstrict per-account nonce order
Parallel validationscript checks parallel; UTXO update sequentialstate transition sequential per account; independent accounts can be parallel
Privacyfresh address per payment natural; change outputsone address per account, history linked
Proof shapeMerkle proof of tx in block; no UTXO commitmentMerkle Patricia proof against state root
Composabilitylimited script; atomic swapsEVM contract calls, atomic within tx
Indexerneed address->UTXO index (Electrum)node returns balance directly

Failure modes. UTXO: dust. Bitcoin Core's dust limit for P2PKH is 546 satoshis. An output below that costs more to spend than it's worth. Detection: the wallet's listunspent shows small outputs; cost: they sit unless fees drop. Coin selection: if you have many small UTXOs, tx size grows. Spending 100 inputs of 1,000 sats each at 10 sat/vB: a P2PKH input is ~148 vB, so 100 inputs ~14,800 vB, fee ~148,000 sats, more than the 100,000 sats total. Account: nonce gap. Send nonce 5 while nonce 4 is pending; if nonce 4 is evicted from the mempool (e.g., underpriced), nonce 5 is stuck. Detection: eth_getTransactionCount(addr, "pending") vs "latest"; the txpool shows queued. Fix: replace nonce 4 with the same nonce and a higher gas price.

Trade-offs. Prefer UTXO when you want parallel script validation, no global ordering, and fresh-address privacy for simple value transfer. Prefer account when you need a single global state, smart contracts, and direct balance queries. Finality and business idempotency come from the consensus layer and application design, not from the ledger model.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Explain gas limit, fee estimation, and reverted execution.

Answer

Assume mainnet, post-London (EIP-1559), one EOA calling a contract. The three terms answer different questions: the gas limit bounds how much work you'll pay for, the fee fields decide whether a validator includes you, and a revert decides what state survives.

Gas limit. Every opcode has a fixed price: 21000 for a plain ETH transfer, 20000 for an SSTORE that writes a zero slot to nonzero, 2100 for a cold SLOAD, 100 for a warm one (EIP-2929). The transaction's gasLimit is the ceiling on the sum of those. Unused gas is refunded, so you pay gasUsed × price, not gasLimit × price, but the limit is also the most you can lose. The block gas limit (30M on mainnet) caps aggregate work across all transactions, which is why one tx can't exceed it and why a full block prices inclusion.

Fee estimation. Under EIP-1559 you set maxFeePerGas (your per-gas ceiling) and maxPriorityFeePerGas (the tip). Effective price is min(maxFeePerGas, baseFee + maxPriorityFeePerGas); the base fee is burned, the tip goes to the validator. eth_estimateGas binary-searches the gas limit by re-executing the call against current state; eth_call simulates without committing. Both run against the state you point them at: usually latest.

Reverts. A require/revert/failed assert unwinds all state changes in the call and its subcalls, returns the revert reason, and refunds unused gas. Gas already consumed is charged regardless, because validators did the work. Out-of-gas is a distinct case: it consumes the entire gas limit, produces no reason string, and is the signature of an underestimated limit.

Worked trace: a stuck transaction. You send with maxFeePerGas = 30 gwei. Base fee climbs to 35 gwei. Your tx is now unincludable, 30 < 35, and sits in the mempool while nonces behind it stall. To unstick it you resend the same nonce with higher fees; most clients require at least a 10% bump on both fields, so maxFeePerGas ≥ 33 gwei and above the current base fee. Send a new nonce instead and you've just queued another stuck tx.

Failure modes and how you see them.

SymptomCauseDetection
out of gas, no reasonlimit below actual consumptioneth_estimateGas vs your hardcoded limit; gas-used ≈ gas-limit
revert with reasonbusiness rule faileddecode revert data; eth_call at the failing block
tx pending > N blocksmaxFeePerGas below base feecompare against base fee / eth_gasPrice
estimate passes, on-chain revertstate changed between estimate and inclusionestimate at latest, then simulate at the target block

Trade-offs. A generous gas limit costs nothing if unused, you're refunded, so the real tension is the fee fields, not the limit. Set maxFeePerGas high enough to survive a few blocks of base-fee spikes and you overpay if the base fee drops; set it tight and you risk a stuck nonce. The wrong call is a hardcoded gas limit copied from a testnet run: state-dependent paths (a balance check, a block.timestamp window, a pool ratio) make any estimate a snapshot, not a guarantee. Estimate, add a buffer for the paths that branch on state, and cap maxFeePerGas at what the transaction is actually worth to you.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

Compare full, archive, light-client, RPC-provider, and wallet responsibilities.

Answer

What a strong candidate says first

These five aren't a maturity ladder; they split on two axes: what the component verifies and what it retains. A full node verifies every block against consensus rules and keeps only recent state. An archive node does the same validation but never prunes, so every historical state stays queryable. A light client verifies a small cryptographic commitment to the chain and trusts an honest majority plus data availability for the rest. An RPC provider is someone else's node behind an API: you inherit their correctness, their freshness and their rate limits. A wallet holds keys and signs; it verifies nothing about chain state.

Mechanism, per role

Full node. Executes every transaction, maintains the state trie, and prunes old trie nodes. A snap-synced Geth full node on Ethereum mainnet sits around 1.2 TB (2025, order of magnitude). Pruning is why eth_getBalance at a block a few hundred thousand back fails with "missing trie node": that state was never kept.

Archive node. Same execution, no pruning: it retains the trie for every block. That is the entire cost difference. Erigon's flat key-value layout keeps an Ethereum archive near 2.5–3 TB; Geth's archive is roughly 12 TB. Sync is days, not hours.

Light client. Ethereum's Altair light client protocol has a 512-validator sync committee that signs each header. The committee rotates every 256 epochs: 256 × 32 slots × 12 s = 98,304 s ≈ 27.3 hours. The client verifies the header chain and the committee signature, then assumes ≥2/3 of the committee is honest and that the data behind the signed root is available. It does not execute, so it cannot answer eth_call.

RPC provider. Runs a full or archive node and answers queries. eth_getProof (EIP-1186) returns the account and storage Merkle branches, so you can recompute the path up to a state root you already trust and check the provider didn't lie. Without that, you trust.

Wallet. BIP-39 seed → BIP-32 derivation → sign. It builds an EIP-1559 transaction and signs it, but takes nonce, gas price and chain ID from the RPC.

Failure modes and how you detect them

  • Stale RPC head: compare eth_blockNumber and the latest block's timestamp across two or three providers; if one lags wall clock by more than a slot or two, it's stale. eth_syncing returning non-false confirms it.
  • Pruned state: a historical eth_call returns "missing trie node". The provider is full, not archive.
  • Rate limits: 429s under load; they show up as intermittent failures on batch requests, not as wrong answers.
  • Lying RPC: verify with eth_getProof against a trusted root, or read the same slot from two independent providers.
  • Wallet: chain-ID mismatch breaks replay protection; a nonce gap stalls every later transaction.

Trade-offs

Don't run a full node if you only sign transactions: a wallet plus a reputable RPC is cheaper and fine. Don't run archive unless you actually query historical state (indexers, analytics, tax tooling); otherwise you pay 2–12 TB and days of sync for queries you never make. Light clients are the right call when you need trust-minimized header verification on a phone or in a browser, and the wrong call when you need to execute contracts.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Explain smart-contract benefits and operational risks.

Answer

Assumptions first. I'll read "smart contract" as a program deployed to a replicated VM, EVM on Ethereum or an L2, where code and state are public and execution order is chosen by block producers. On a permissioned chain the risk profile changes a lot, so I'd flag that before answering.

Core answer. The benefit isn't "trustless" as a slogan; it's that the rules and the state live in one replicated object. Every node runs the same bytecode over the same ordered transactions and reaches the same state root, so you get deterministic shared execution and atomic composability: one transaction can call A, then B, then C, and either all of it commits or none does. No application server owns the state, so there's no privileged writer to compromise and no reconciliation between services. Settlement is final once a block is finalized: on Ethereum, 12-second slots and roughly 12.8 minutes to Casper FFG finality.

What that costs, mechanically. Public and ordered execution means anyone can see your pending transaction and place theirs around it: that's MEV. A sandwich is: the attacker sees your swap in the mempool, buys ahead of you, your trade moves the price, they sell behind you. Ordered public execution is the cause; private mempools and bundle relays are a mitigation, not a fix.

Immutability: deployed bytecode can't be edited in place, so upgrades go through a proxy that delegatecalls into a logic contract. That works, but proxy and logic share one storage layout, so inserting a variable in the middle of the logic's storage collides with the proxy's slots. Parity's 2017 library self-destruct froze ~513,774 ETH because a library contract could be killed and every wallet delegating to it stopped working.

Oracle dependence: the chain can't see off-chain prices. Mango Markets, October 2022, ~$116M: the attacker pushed MNGO's price on thin venues, and the protocol's oracle read that manipulated price as collateral value.

Failure modes and how you catch them.

  • Reentrancy: an external call before the state update. Trace the classic bug: attacker deposits 1 ETH, balances[attacker]=1; withdraw() reads bal=1, sends 1 ETH, the attacker's receive() re-enters withdraw() before the zeroing line, reads bal=1 again, sends another 1 ETH, and repeats until the contract is drained. Detect with invariant tests and fuzzing; fix with checks-effects-interactions or a reentrancy guard.
  • Key/governance concentration: Ronin bridge, March 2022, ~$625M. 5 of 9 validator keys compromised. Detect by monitoring signer activity and threshold changes.
  • Upgrade bugs: storage collisions, uninitialized proxy. Detect with storage-layout diffing in CI and fork tests against mainnet state.

Deciding criteria. Use on-chain execution when the value at stake justifies the cost and you need shared state or composability; keep it off-chain when you need low latency, private data, or frequent logic changes. A plain ETH transfer is 21,000 gas, a fresh storage write is 20,000 gas, a cold SLOAD is 2,100: that arithmetic is why you batch and cache.

Mitigations, sized to the risk. Pause and migration are the real lever: a pause() behind a multisig plus a migration path. USDC's blacklist shows the pattern: an issuer can freeze an address. Audit cost is real: a serious protocol audit runs weeks and five to six figures, and it is not a guarantee.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Choose between permissionless and permissioned ledger designs.

Answer

The 90-second answer

Ask two questions before choosing: do the participants already have a legal identity and a contract with each other, and does the application need deterministic finality? Yes to both points to permissioned. If the whole value is that no one can be excluded and no central party can rewrite history, choose permissionless.

Assume a consortium of 12 regulated banks settling interbank obligations, ~2,000 transfers/second at peak, trades confidential, disputes heard in court. Choose permissioned: Hyperledger Fabric or a CometBFT/Tendermint chain. Assume instead a public token with anonymous holders and no shared legal venue: permissionless, on a proof-of-stake L1.

Why the mechanism forces the choice

Permissionless admission means anyone can join, so the protocol must make identity costly, proof-of-work or staked capital, to resist Sybil attacks. That cost buys security and also forces probabilistic finality: Bitcoin reorgs, so you wait ~6 blocks (~60 min) for high confidence; Ethereum PoS finalizes in ~2 epochs (64 slots, ~12.8 min), and before that a reorg is possible. You cannot get instant, irreversible settlement from an open validator set.

Permissioned admission means validators are known and accountable, so you can run a BFT protocol (CometBFT, IBFT, Fabric's Raft or BFT ordering) that tolerates 1/3 Byzantine validators and commits in one block: sub-second to a few seconds. Known identities also let you scope data: Fabric channels and private data collections keep a trade visible only to its counterparties, which a public chain cannot do without heavy cryptography.

dimensionpermissionlesspermissioned
adversary threshold51% hashrate (PoW); 1/3 stake to stall finality, majority to reorg unfinalized blocks (PoS)1/3 Byzantine validators to halt; 2/3 to commit
finalityprobabilistic; Bitcoin ~6 blocks, Ethereum ~12.8 mindeterministic, one block, sub-second to seconds
throughputBitcoin ~7 tps, Ethereum L1 ~15–30 tpsthousands tps (Fabric, CometBFT)
confidentialityeverything public; privacy needs ZK/commitmentschannels/private collections, plaintext to members
membership recoverykey lost = funds lost, no recoursere-issue identity out of band, re-admit validator
governancediffuse, forks as escape hatchexplicit, but capturable by a quorum
legalpseudonymous, hard to hold accountablenamed parties, enforceable contracts

Failure modes and detection

Permissioned: governance capture. With 12 validators, 4 colluding (≥1/3) can stop finality: detect via finality lag and block-height stalls, alert when height has not advanced for more than two block times. Membership recovery: a validator loses its key; the chain keeps running but you are one failure from halting. Track live validator count against the fault budget. Client diversity: if all 12 run the same Fabric build, one bug halts everyone. Monitor for divergent state roots across implementations.

Permissionless: 51% attack or deep reorg. Detect via reorg-depth and hashrate/stake-concentration dashboards; MEV and front-running on public mempools, detect via sandwich-attack monitoring; gas spikes, Ethereum's base fee reached hundreds of gwei in 2021, pricing out small transactions.

What would change the decision

If the consortium cannot agree on a shared legal venue, or members must be able to join without anyone's permission, permissionless wins despite the latency. If regulators require the ability to freeze or reverse a transaction, only permissioned gives you that lever.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Critique the claim that a blockchain removes trust.

Answer

The 90-second answer

The claim is too strong, and the repair is to say what replaces the trust rather than that trust vanishes. A blockchain removes one operator's ability to unilaterally rewrite balances or drop your transaction, and substitutes a set of narrower assumptions you can enumerate: that a threshold of validators or miners behaves, that the client software you run is correct, that your keys are not compromised, that whoever holds the upgrade key does not use it, and that the RPC endpoint and oracle you read from are telling you the truth. "Trustless" is shorthand for trust-minimized relative to a specific alternative (a bank, a custodian, a single Postgres instance) and it means nothing until you name that alternative and the adversary you are defending against.

Where the trust actually sits

Residual trustConcrete anchorWhat it buys an attacker
Consensus thresholdEthereum PoS: 1/3 of stake halts finality, 2/3 can finalize conflicting checkpoints; Lido has held roughly a quarter of staked ETHCensorship, or a reorg that reverts your settlement
Client diversityA bug in a supermajority execution clientEvery node running it follows the bug, not the spec
Bridge / multisig custodyRonin, March 2022: 5-of-9 validator keys, ~$624M takenThe bridge is a 9-key multisig wearing a chain costume
Issuer controlCircle froze USDC at Tornado Cash addresses within days of the August 2022 OFAC designationYour "permissionless" dollar can be blacklisted
Block buildingFor a stretch in late 2022, a majority of Ethereum blocks came from MEV-Boost relays filtering OFAC-sanctioned transactionsCensorship at the builder layer, not the protocol layer
GovernanceThe 2016 DAO fork reversed roughly 3.6M ETH of stateSocial consensus overrides code when enough people want it to
Read pathMetaMask's default RPC was InfuraMost "verification" is a JSON-RPC call to someone else's node

What the protocol does and does not give you

The EVM is deterministic given the same inputs and state: that part is real. What is not deterministic is which transactions reach the block and in what order; that is chosen by builders and proposers, and it is where MEV lives. Finality differs too: Bitcoin is probabilistic, with six confirmations (~60 minutes) as the convention, while Ethereum reaches finality after two epochs, about 12.8 minutes. Neither is instant, and neither helps if you never verify: running a light client or your own node is the only way to stop trusting an RPC provider.

How to answer it in the room

Pick the alternative first: "compared to a bank that can freeze my account, this removes that specific power." Then name the adversary. A state, a validator cartel, a bridge operator, a compromised key. Then say which assumptions you have actually removed and which you have merely moved. The honest one-liner: a blockchain converts one large, discretionary trust into several smaller, auditable ones, and the audit is the work.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Explain how proof-of-work and proof-of-stake chains resist sybil attacks and choose the next block, and state the fork-choice rule each uses to pick between competing chain heads.

Answer

First 90 seconds. Both designs make block production cost something an attacker cannot counterfeit, then give every node the same rule for picking one chain out of the branches it has seen. PoW prices a block in hashpower; PoS prices it in bonded capital that can be destroyed. The fork-choice rules differ in kind: PoW uses most cumulative work, PoS uses LMD GHOST weighted by attestations and bounded by Casper FFG finality.

Proof of work. A miner assembles a candidate block and hashes its 80-byte header with a varying nonce. The block is valid only if the resulting hash is below the target encoded in the header's nBits field. Expected hashes per block is 2^256 / target, and difficulty retargets every 2016 blocks (~14 days) to hold the interval near 10 minutes. Creating identities is free, anyone can run a node or point a miner at the network, but producing a block is not, so rewriting history means out-hashing the honest majority. Fork choice is the chain with the most cumulative work, not the most blocks: Bitcoin Core compares nChainWork, so a shorter branch carrying higher difficulty wins. The whitepaper's "longest chain" is shorthand that breaks in exactly that case.

Proof of stake (Ethereum). Sybil resistance is capital at risk. A validator deposits 32 ETH into the deposit contract; the active set is fixed per epoch, so identities are bought, not free, and misbehaviour is slashable. Each 12-second slot one proposer is selected pseudo-randomly, weighted by effective balance, and a committee of attesters votes on the head. Fork choice is LMD GHOST: the heaviest subtree by each validator's latest attestation, weighted by effective balance, with Casper FFG constraining it so a node never builds on a branch conflicting with a justified or finalized checkpoint. Two successive justified epochs finalize a checkpoint: 32 slots × 12 s × 2 ≈ 12.8 minutes.

PoW (Bitcoin)PoS (Ethereum)
Sybil costhashpower + energy32 ETH bonded per validator, slashable
Next blockany miner, first valid block with enough workpseudo-random proposer per slot
Fork choicemost cumulative work (nChainWork)LMD GHOST weight + FFG checkpoint constraint
Finalityprobabilistic; ~6 confirmations is conventionexplicit, ~12.8 min
Reorg costredo the work, acquire hardware≥1/3 of total stake slashed

Worked figure (illustrative). At 600 EH/s network hashrate, a 100 TH/s miner expects 600e18 / 100e12 = 6e6 s ≈ 69 days per block. Doubling that miner's share halves the interval; it does not change the rule that the heaviest chain wins.

Failure modes. PoW: a >50% miner can reorg to depth, and selfish mining lets a minority withhold blocks to waste honest work. Detect via reorg depth and stale-block rate. PoS: long-range attacks where a past key set rewrites history, mitigated by weak-subjectivity checkpoints a syncing node must obtain out of band; nothing-at-stake, mitigated by slashing; and finality reversal, which needs at least a third of total stake burned. Detect via attestation participation rate, slashing events and client diversity: one client holding >2/3 of stake is a liveness risk, not a fork-choice one.

When not to use either. If participants are known and mutually accountable, a BFT protocol (Fabric's Raft or a PBFT variant) gives deterministic finality without paying for open participation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Explain how nodes validate an execution payload.

Answer

What a strong candidate says first

Post-Merge the consensus layer (CL) owns fork choice; the execution layer (EL) owns execution validity. The CL hands a payload to the EL via engine_newPayloadV3 (V4 in Prague) with the ExecutionPayloadV3, expectedBlobVersionedHashes, and parentBeaconBlockRoot. The EL replies with PayloadStatusV1: VALID, INVALID, or SYNCING, plus latestValidHash on INVALID. The CL does not put a block into fork choice until the EL says VALID. The EL never checks the proposer signature or attestations: it only answers whether the state transition is legal.

Cheap header checks, before any execution

  • parentHash must resolve to a known block. Unknown parent → SYNCING, not INVALID.
  • blockHash must equal keccak256(rlp(header)): recompute it, never trust the field.
  • timestamp > parent.timestamp; extraData ≤ 32 bytes; gasUsed ≤ gasLimit; gasLimit within ±1/1024 of the parent's and ≥ 5000.
  • baseFeePerGas must equal the EIP-1559 value derived from the parent: parent_base_fee + parent_base_fee * (parent_gas_used - parent_gas_limit/2) / (parent_gas_limit/2) / 8.
  • EIP-4844: blobGasUsed ≤ 786432 (6 × 131072), and excessBlobGas == max(0, parent.excessBlobGas + parent.blobGasUsed - 393216).
  • EIP-4788: parentBeaconBlockRoot must match the CL's root for the parent slot. withdrawalsRoot is recomputed from the withdrawals list (EIP-4895).

Transaction-level validation, in order, before execution

  • Chain ID, nonce == sender.nonce, EIP-2 low-s, EIP-155 v.
  • EIP-3607: the sender must have no code (EIP-7702 delegations excepted).
  • Intrinsic gas: 21000 + 4 per zero calldata byte + 16 per non-zero byte; EIP-3860 adds 2 per 32-byte word of initcode, capped at 49152 bytes.
  • Fees: maxPriorityFeePerGas ≤ maxFeePerGas; balance ≥ gasLimit * maxFeePerGas + value.
  • Blob txs: versioned hashes must equal expectedBlobVersionedHashes in order, 1–6 blobs, maxFeePerBlobGas set.

Worked trace: block 20,000,000

Parent 19,999,999: gasLimit 30,000,000, gasUsed 30,000,000, baseFeePerGas 20 gwei. Derived child base fee: 20 + 20 × (30,000,000 − 15,000,000) / 15,000,000 / 8 = 22.5 gwei.

The payload claims parentHash 0x9f…c1, timestamp 1710000012 (parent + 12), gasLimit 30,000,000, gasUsed 93,000, baseFeePerGas 22.5 gwei, stateRoot 0x11…aa, receiptsRoot 0x33…dd, blockHash 0x4a…7e.

Header pass: parentHash known; recomputed keccak256(rlp(header)) = 0x4a…7e; timestamp ahead; |gasLimit − parent gasLimit| = 0 ≤ 29,296; base fee matches 22.5 gwei.

Transactions, in order:

txintrinsicexecutionstatusgasUsedrunning
tx0 transfer21,0000121,00021,000
tx1 ERC-20 transfer21,00030,000151,00072,000
tx2 call to REVERT(0,0)21,0000021,00093,000

Running total 93,000 equals the header's gasUsed. Recomputing receiptsRoot gives 0x33…dd and logsBloom 0x00…00: both match. Recomputing stateRoot gives 0x22…bb, not the header's 0x11…aa.

Response:

JSON
{"jsonrpc":"2.0","id":1,
 "result":{"status":"INVALID","latestValidHash":"0x9f...c1",
           "validationError":"<client-specific>"}}

The CL marks 20,000,000 and every descendant invalid and reorgs to 19,999,999. A reverting transaction is fine: status 0 is a legal outcome; only a validation failure invalidates the payload.

Status and consequences

  • VALID → the CL updates fork choice head.
  • SYNCING → parent unknown; the CL keeps the block pending and retries.
  • INVALID + latestValidHash → the CL marks the block and every descendant invalid and reorgs to latestValidHash. Attestations already cast for the invalid block become slashable surround votes once the chain diverges, and the proposer earns nothing for the slot.

Trade-offs

Optimistic sync lets the CL import payloads before the EL finishes validating, so a node follows the head while the EL catches up; the cost is temporarily following a chain that may be invalid, and the CL must be able to reorg on INVALID. Pre-merge clients validated before import: slower, but never followed an invalid head. With MEV-Boost the proposer signs the header before executing the payload: the EL will reject bad state, so a builder cannot make the chain accept it, but the signature is already out, so a malicious builder can waste the slot and expose the proposer to equivocation if they also sign a fallback block. Relays mitigate by simulating before revealing. A node in SYNCING is trusting the majority; only a full node re-executing can actually return INVALID.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Explain Ethereum head, justified, and finalized states to an integrator.

Answer

The 90-second answer

Assume you're integrating an app that reads Ethereum state and needs to decide when a value is safe to act on irreversibly. The consensus layer exposes three levels of commitment, and they differ in how much stake would have to be burned to reverse them.

  • Head: the tip the fork choice currently selects. It changes every slot (12s) and can be reorged by a block or two with no penalty to anyone.
  • Justified: a checkpoint (the first block of an epoch; an epoch is 32 slots = 6.4 min) that ≥2/3 of staked ETH has attested to. Reverting it needs a large fraction of validators to equivocate, which is slashable.
  • Finalized: a justified checkpoint whose next epoch is also justified. Reverting it requires ≥1/3 of all staked ETH to be slashed, roughly 11M ETH at ~34M staked, plus the social layer agreeing to ignore the violation.

So: head is for display, justified is for "very likely permanent", finalized is for "treat as irreversible".

Why two steps

Casper FFG justifies and finalizes checkpoints. A checkpoint is justified when 2/3 of validator weight votes for it as target with a justified source. Finalization is the second step: when epoch N is justified and epoch N+1 is justified with N as its source, N becomes finalized. The two-step design is what makes the slashing conditions enforceable: a validator that votes for conflicting checkpoints (double vote) or casts a vote that surrounds another (surround vote) can be proven to have equivocated from the signed messages alone, so the protocol burns its stake without trusting anyone.

Timing: minimum ~2 epochs ≈ 12.8 min from a block being proposed to finalization; in practice ~15 min because you wait for the epoch boundary.

Deciding what to act on

StateReversal costTypical use
headnone; 1–2 block reorgs commonUI balance display, mempool
justifiedslashable; needs ~1/3+ equivocationhigh-value, latency-tolerant actions
finalized≥1/3 stake slashed + social recoverywithdrawals, exchange credits, bridges

Failure modes and detection

  • Reorg past head: normal, 1–2 blocks. Detect by comparing the block hash at a fixed height across polls; never cache head as final.
  • Finality stall, if no checkpoint finalizes for more than 2 epochs, the chain is still live (head advances) but finality is delayed. Detect by polling the finality checkpoints endpoint and alerting when the finalized epoch hasn't advanced in ~4 epochs (~25 min). Cause is usually a client bug or a large validator outage, not an attack.
  • Conflicting finalized checkpoints: two finalized checkpoints at the same height with different hashes means ≥1/3 slashed. This is the catastrophic case; the runbook is to halt automated actions and follow social consensus, not to pick a chain yourself.

Getting the status

Beacon API: GET /eth/v1/beacon/states/head/finality_checkpoints returns the finalized and justified checkpoint roots and epochs. Execution JSON-RPC: eth_getBlockByNumber("finalized", false) and "safe" (safe = justified) block tags, supported by Geth, Nethermind, Besu and Erigon. Record the block hash and the finalized epoch alongside any value you act on, so you can prove later which chain you committed to.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Set a transaction finality policy for a product.

Answer

Let me clarify the product: I'll assume a custodial exchange that credits user deposits and allows withdrawals. The core recommendation is a tiered finality policy: for each chain, set confirmation thresholds by transaction value, and for high-value transactions, wait for protocol-level finality where available.

First, the mechanism. On proof-of-work chains like Bitcoin, each additional block increases the cost to reorg exponentially. If an attacker has 10% of hash rate, the probability of reversing a transaction after 6 confirmations is about 0.1^6 = 1e-6. After 3 confirmations, it's 1e-3. So depth-based confidence works because the attacker must outpace the honest chain, and the probability decays geometrically. On proof-of-stake chains like Ethereum post-Merge, there's a finality gadget. Validators attest to blocks; after two epochs (about 12.8 minutes), a block is finalized. Reverting a finalized block requires slashing at least one-third of the total stake, which is economically infeasible. So finality is deterministic, not probabilistic.

Now the policy. For Bitcoin: under $100, 1 confirmation (~10 min); $100–$10k, 3 confirmations (~30 min); over $10k, 6 confirmations (~60 min). For Ethereum post-Merge: under $100, 1 block (~12 sec); $100–$10k, 12 blocks (~2.5 min) as a probabilistic heuristic; over $10k, wait for finalized (2 epochs, ~12.8 min). For Solana: under $100, confirmed (1 slot, ~0.4 sec); over $100, finalized (32 slots, ~12.8 sec). These are starting points; adjust by risk tolerance.

ChainValue tierThresholdLatency
Bitcoin< $1001 conf~10 min
Bitcoin$100–$10k3 conf~30 min
Bitcoin> $10k6 conf~60 min
Ethereum (post-Merge)< $1001 block~12 sec
Ethereum (post-Merge)$100–$10k12 blocks~2.5 min
Ethereum (post-Merge)> $10kfinalized (2 epochs)~12.8 min
Solana< $100confirmed~0.4 sec
Solana> $100finalized~12.8 sec

Failure modes. A concrete one: you credit a user after 1 Ethereum block. A 2-block reorg happens due to a network partition. The user withdraws immediately. You lose the funds. Detection: a reconciliation job compares on-chain deposits to your internal ledger; it alerts on negative balance. Operational cost: you need to hold reserves to cover such losses, or you delay credit. Another failure: treating a single provider's receipt as settlement. If your node is on a fork, you might credit a transaction that never makes it to the canonical chain. Detection: monitor head vs finalized lag; if head is more than 10 blocks ahead of finalized, alert.

Tradeoffs. Delaying credit until finality is safe but slow: 12.8 minutes on Ethereum, 60 minutes on Bitcoin. That hurts user experience and may lose customers. Compensating by crediting early but holding withdrawals until finality is a middle ground: users see the balance but can't withdraw. Fast-loose is acceptable for low-value transactions, trusted users, or when you can reverse the credit (e.g., internal transfers). Deciding criteria: value at risk, cost of capital, user patience, and competitive pressure. So the policy should be tiered, chain-specific, and monitored.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Choose a consensus fault model for a consortium ledger.

Answer

Core answer. For a consortium ledger the fault model is a trust decision, not a performance one. If every member is a known legal entity bound by contract, running auditable software, and a lying node is detectable and punishable, crash-fault tolerance is the right model: Raft, n = 2f+1, majority quorum. If members are mutually distrusting, or a single compromised node could equivocate, sign two conflicting blocks, you need Byzantine fault tolerance: PBFT, Tendermint or HotStuff, n = 3f+1, quorum 2f+1. State the threshold out loud: with 4 organizations, Raft tolerates 1 crash; BFT with 4 nodes tolerates 1 Byzantine fault. You cannot get BFT's guarantee out of 3 nodes.

Why the numbers. BFT quorum intersection: any two quorums of 2f+1 out of 3f+1 overlap in at least f+1 nodes. At most f are faulty, so at least one honest node sits in every intersection and refuses to sign two conflicting values: that is what keeps safety when the leader equivocates. CFT's majority quorum (f+1 of 2f+1) also intersects, but the intersecting node is assumed only to crash, never to lie, so a Byzantine leader can commit conflicting entries and Raft has no mechanism to stop it.

Synchrony: Raft's safety is time-independent, but liveness needs partial synchrony. Election timeouts must eventually be long enough. Tendermint and HotStuff keep safety under asynchrony and need partial synchrony (a GST) only for liveness. A WAN consortium with variable latency should pick a protocol whose safety does not depend on clocks.

CFT (Raft)BFT (Tendermint / HotStuff)
nodes for f=134
quorumf+1 = 2 of 32f+1 = 3 of 4
toleratescrash, network partitioncrash + equivocation + forged messages
message cost per decisionO(n)O(n²) PBFT/Tendermint; O(n) HotStuff with threshold sigs
safety under asynchronyyesyes
liveness needspartial synchronypartial synchrony (GST)

Failure modes and detection. Equivocation: two conflicting signed proposals in the same view. Detect by having every node gossip signed messages and alert on a double-sign; that evidence is also the eviction proof. Partition: the minority side stops committing (no quorum). Detect via missed commit heartbeats, not via a wrong value. Unavailable quorum: more than f nodes down, liveness lost, safety intact. Alert on commit latency exceeding the block interval. Key compromise: rotate membership keys on a schedule and on any suspected leak; a stolen key is a Byzantine node.

When not to. Don't pay for BFT if the members share a legal jurisdiction and an operator can be evicted by contract: the O(n²) message cost and the extra node buy you nothing. Don't use CFT if any member is a competitor who benefits from a fork, or if the ledger settles value across trust boundaries. And check independence: 4 nodes run by 2 organizations is f=1 only if those two orgs are actually independent. Otherwise you have one vote.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Make an event indexer safe under chain reorganizations.

Answer

What I'd say first

Assume Ethereum mainnet post-merge, an indexer that reads eth_getLogs and newHeads from Geth, writes to Postgres, and publishes to Kafka for a service that credits balances. "Safe" here means three things: no double-credit, no missed event, and a deterministic replay after any reorg.

The core move is to key everything by block hash, not block number. Block numbers get reused across reorgs; hashes don't. So every row carries chain_id, block_number, block_hash, parent_hash, tx_hash, log_index, and the primary key is (chain_id, block_hash, log_index). Downstream effects are keyed by (chain_id, tx_hash, log_index): a stable operation id that survives a reorg, so re-applying is an upsert, not a duplicate credit.

Confirmation lag

Don't index the head. Index head - N. On Ethereum post-merge, reorgs are usually 1–2 blocks; the deepest mainnet reorg I've seen cited is 7 blocks. So N=12 covers every observed case with margin, at ~2.4 minutes of latency. If you need a hard guarantee, wait for finality: 2 epochs = 64 slots ≈ 12.8 minutes. That's the trade-off: 12.8 min of latency for a guarantee that only breaks under a >1/3 validator fault.

depthprotects againstadded latency
1nothing12 s
12all observed post-merge mainnet reorgs~2.4 min
64 (finalized)anything short of a 1/3 validator fault~12.8 min

Detection and rollback

On each new head, compare its parent_hash to the hash you stored at number - 1. Match → append. Mismatch → walk back with eth_getBlockByNumber until the stored hash equals the canonical hash at that height; that's the common ancestor. Delete (or mark reverted) every row above it, in reverse order, and emit a compensating revert event per operation id. Then apply the canonical branch forward.

Python
def ingest_head(block):
    prev = db.get_block(block.number - 1)
    if prev and prev.hash != block.parent_hash:
        n = block.number - 1
        while n >= 0:
            stored = db.get_block(n)
            if stored and stored.hash == rpc.get_block(n).hash:
                break
            n -= 1
        db.rollback_above(n)          # delete rows > n, emit revert events
    db.upsert_block(block)            # PK (chain_id, block_hash)
    for log in rpc.get_logs(block):
        db.upsert_log(log)            # PK (chain_id, tx_hash, log_index)

Trace: stored 100, 101, 102. New head 101' arrives with parent 100. prev = block 101, hash mismatch. n=101: stored 101 hash ≠ canonical 101' hash → n=100: stored 100 hash == canonical 100 → break. rollback_above(100) deletes 101 and 102; the next heads 101' and 102' get applied as they arrive.

Failure modes

  • Provider serves a stale head: enforce monotonic height per chain_id and reject a head whose timestamp is older than the last accepted one.
  • Duplicate delivery: the operation id makes it a no-op.
  • Restart mid-reorg: write the reorg cursor and the rollback in one transaction, so you never resume half-rolled-back.
  • Provider equivocation: reconcile against a second client (Erigon next to Geth), if their hash at height H differs, one is on a minority fork; stop and alert.

What would change the answer

If the chain is Polygon PoS, the numbers move: Bor reorgs have gone deeper, and you'd wait for a Heimdall checkpoint instead of 12 blocks. If downstream is irreversible (a fiat payout, say) you wait for finality regardless of the 12-block heuristic.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design a reliable blockchain event consumer.

Answer

Assumptions: an EVM chain (Ethereum mainnet), one writer process, a provider that delivers at-least-once and can reorg its head, and projections in Postgres. Numbers below are mainnet figures; the shape transfers to other chains with different constants.

Core answer

Treat the chain as an append-only log that occasionally rewrites its tail. Keep a durable cursor of (height, block_hash). Read blocks strictly in order, and before applying anything check that block.parentHash equals the hash you stored for height - 1. If it doesn't, you've been reorged: roll back the projections for the affected heights, move the cursor back to the last matching block, and replay forward. Make every effect idempotent on the natural key (tx_hash, log_index) so a redelivered log is a no-op. Do not let irreversible business actions fire until the block is finalized: on Ethereum that's the finalized tag, roughly two epochs, about 12.8 minutes. Everything else is bookkeeping around those four ideas.

Mechanism

Reorgs happen because the head is a fork choice, not a fact. A block you saw at height N can be replaced by a sibling with a different hash; the parent link is how you notice. So the cursor stores the hash, not just the height: height alone can't tell you the block changed.

Idempotency comes from a unique constraint, not from application logic. (tx_hash, log_index) is stable across redelivery and unique within the chain, so INSERT ... ON CONFLICT DO NOTHING on a seen_events table makes replay safe. Apply the projection and the seen_events row in one transaction so a crash between them can't double-count.

Python
def consume(provider, cursor):
    head = provider.block_number()
    while cursor.height > 0:                       # rewind past a reorg
        stored = db.get_block(cursor.height)
        if provider.block_hash(cursor.height) == stored.hash:
            break
        db.rollback_effects(cursor.height)
        cursor = Cursor(cursor.height - 1, db.get_block(cursor.height - 1).hash)
    for n in range(cursor.height + 1, head + 1):
        block = provider.get_block(n, full_tx=True)
        if block.parent_hash != cursor.hash:       # gap or fork
            raise CursorGap(n)
        for log in block.logs:
            if log.address not in CONTRACTS or log.topics[0] != TRANSFER_SIG:
                continue
            key = f"{log.tx_hash}:{log.log_index}"
            with db.tx():
                if db.seen(key):
                    continue
                db.apply_projection(log)
                db.mark_seen(key)
        db.save_block(n, block.hash)
        cursor = Cursor(n, block.hash)

Trace: cursor is (100, 0xaa). The provider reorged, so block_hash(100) now returns 0xbb. The rewind loop sees 0xaa != 0xbb, rolls back block 100's effects, sets the cursor to (99, hash(99)), and breaks because 99 still matches. The forward loop replays 100..head, and the parent_hash check catches any gap the rewind missed.

Trade-off: latency vs finality

policytime to actrisk
finalized tag~12.8 minnegligible
12 confirmations~2.4 minshallow reorgs only; post-Merge reorgs deeper than 2 blocks are rare but not impossible
head (0 conf)~0reorg likely

Pick per action, not per consumer: a balance display can read the head, a withdrawal must wait for finalized. The alternative to a self-managed cursor is a provider webhook (Alchemy Notify, QuickNode Streams): less code, but you still need the cursor and idempotency because webhooks are at-least-once and unordered.

Failure modes and detection

  • Cursor gap: provider skips a block or you crash mid-batch. Detected by the parent_hash check; halt and backfill rather than skipping.
  • Duplicate delivery: same log twice. Detected by a counter of seen hits; should be non-zero and harmless.
  • Decode error: ABI changed after a contract upgrade. Quarantine the log, alert, and do not advance the cursor past it.
  • Divergence: projection drifted from chain state. Recompute a random recent finalized block from chain and diff against the DB on a schedule.
  • Provider lag: head lag over ~30 s or finalized lag over two epochs. Alert; a silent lag looks identical to a quiet chain.

Reconcile

Periodically recompute projections for a finalized height from raw logs and compare to the stored rows. Any mismatch means a bug in apply_projection, not a chain event: that's the only way to catch a projection that was wrong from the start.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Handle concurrent Ethereum transaction submission from one account.

Answer

Core answer

Assume one EOA, one chain, an EIP-1559 chain, and that you hold the signing key. The invariant: exactly one writer owns the nonce counter for a given (chainId, sender) at a time. Everything else follows from that.

A strong first 90 seconds: "I keep a single nonce allocator per sender. It seeds from eth_getTransactionCount(sender, 'pending') (that count includes mempool transactions, not just mined ones) then hands out nonces monotonically. I persist op_id -> nonce before signing, so a crash can't lose the mapping. I broadcast with eth_sendRawTransaction, and I key idempotency on (chainId, sender, nonce), never on the tx hash, because a replacement changes the hash."

Why it behaves this way

eth_getTransactionCount(sender, 'pending') returns mined-nonce + count of that sender's txs sitting in the mempool. 'latest' returns only mined, so seeding from 'latest' under a concurrent submitter hands out a nonce that's already in flight. Geth's txpool splits these into pending (contiguous from the account nonce) and queued (gap ahead of it): a tx with nonce N+1 sits in queued and is invisible to mining until N lands.

A replacement is a new transaction: the hash is keccak over all signed fields including maxFeePerGas, so bumping the fee yields a different hash for the same nonce. Geth's txpool rejects a same-nonce replacement unless both maxFeePerGas and maxPriorityFeePerGas exceed the old values by more than the pricebump (default 10%).

Python
# Python 3.11, web3.py 6.x
class NonceAllocator:
    def __init__(self, w3, sender, chain_id, store):
        self.w3, self.sender, self.chain_id, self.store = w3, sender, chain_id, store
        self.next_nonce = None

    def allocate(self, op_id):
        if self.next_nonce is None:
            self.next_nonce = self.w3.eth.get_transaction_count(self.sender, "pending")
        n = self.next_nonce
        self.next_nonce += 1
        self.store.put(op_id, self.chain_id, self.sender, n)  # persist BEFORE signing
        return n

Trace: account has 5 mined txs and 2 in the mempool. get_transaction_count(..., "pending") returns 7. allocate returns 7, next_nonce becomes 8. Persist op -> 7, sign nonce 7, broadcast. If the broadcast fails, nonce 7 is now a gap: nothing with nonce 8 will mine until 7 is filled.

States and detection

statedetectionaction
pendingeth_getTransactionByHash non-null, receipt nullwait
droppedgetTransactionByHash null after several blocksrebroadcast the same raw tx, or re-sign the same nonce
replacedgetTransactionByHash returns a different hash for that noncetrack the new hash
includedeth_getTransactionReceipt non-nullread status
revertedreceipt.status == 0nonce consumed, business op failed
finalizedreceipt.blockNumber <= finalized headsafe to mark done

Post-Merge, finalized is ~2 epochs (~12.8 min); safe is ~1 epoch. Don't treat a receipt as final until then: a reorg can orphan it.

Trade-offs

  • Single-writer worker (one process owns the nonce): simplest, no coordination, but it's a SPOF and throughput is capped by one signer.
  • Nonce lease service (a DB row lock or Redis lease per (chain, sender)): lets several submitters share an account; adds lease-expiry bugs and coordination latency.
  • Pre-allocated window: hand out a block of nonces and keep them filled. Highest throughput, most reconciliation.

Strict serialization, wait for a receipt before the next tx, caps you at roughly one tx per block (~12 s). For a bot that needs many in-flight txs from one account, that's the wrong choice; use a window.

Failure modes

  • Nonce gap: N+1 stuck in queued. Detect via getTransactionCount(pending) not advancing. Fix: rebroadcast N, or replace it with a 0-value self-send to cancel.
  • Crash after persist, before broadcast: nonce burned. On restart, re-seed from pending; if the persisted nonce is below the pending count, check the receipt by hash to learn whether it landed.
  • Fee spike: tx underpriced and parked. Replace with a >10% bump on both fee fields.
  • Reorg: receipt seen, block orphaned. Wait for finalized.

Idempotency lives on (chainId, sender, nonce) or your own op_id, because a replacement makes the hash a moving target.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design application handling for failed blockchain transactions.

Answer

Core answer (first 90 seconds)

"Failed" is five different things and the app must not collapse them: (1) the node rejected submission, (2) it was accepted into the mempool but never included, (3) it was included and reverted, (4) it was included and executed but later reorged out, (5) it executed but is not yet final. Each has a different remedy and a different message to the user.

Assumptions: an EVM chain (Ethereum L1 or an EVM L2), we control the sending application and its database, we do not control block production. The chain is the source of truth; our DB is a cache of it.

The design is a per-transaction state machine persisted before broadcast, keyed by a client-generated idempotency key, with the signed transaction hash stored before the first eth_sendRawTransaction. Never retry by re-signing blindly: that is how you get nonce collisions and double-spends.

Mechanism

Nonce: each account has one monotonic nonce. A transaction with nonce N can only be included after N-1 is included. If nonce N is stuck (underpriced), every later transaction from that account is stuck behind it. So "retry" means either replacing nonce N with a higher fee (same nonce, both maxFeePerGas and maxPriorityFeePerGas bumped by at least 10%, Geth's default --txpool.pricebump) or cancelling it with a 0-value self-transfer at the same nonce.

Simulation divergence: eth_call executes against the state at one block, with no ordering and no fee market. It cannot see state changes between simulation and inclusion, MEV reordering, or the gas price you will actually pay. A passing simulation is necessary, not sufficient.

Trace: a reverted swap

  • App simulates router.swapExactTokensForTokens(...) via eth_call at latest block → succeeds, minOut satisfied.
  • Between simulation and inclusion, a large swap moves the pool price.
  • Tx is included at block 21,000,000, receipt status: 0x0, gasUsed 132,000, nonce consumed, no state change.
  • The receipt carries no revert reason. Replay: eth_call with the same calldata at block 21,000,000 → revert data 0x08c379a0… → INSUFFICIENT_OUTPUT_AMOUNT.
  • Cost: 132,000 × 22 gwei = 0.002904 ETH burned, no tokens moved.

State table

ObservedMeaningAction
eth_sendRawTransaction → -32000 nonce too lowAlready mined or replacedLook up by hash; do not resend
-32000 replacement transaction underpricedFee bump < 10%Bump both fee fields ≥10%
-32000 already knownSame hash already in mempoolIdempotent no-op
Hash not found after N blocksDropped from mempoolRe-broadcast the same signed tx, or replace
Receipt status: 0x0Reverted, gas spentReplay for reason; do not auto-retry
Receipt status: 0x1, block < finalizedExecuted, reorgableHold downstream effects
Block ≥ finalizedFinalCommit downstream effects

(Error strings above are Geth's; Nethermind and Besu word them differently, so match on the JSON-RPC error code and a substring, not the full string.)

Finality arithmetic

Ethereum PoS: 12 s slots, 32 slots per epoch. finalized trails head by 2 epochs = 64 slots = 768 s ≈ 12.8 min. A one-confirmation "success" can still be reorged; only eth_getBlockByNumber("finalized", false) is safe to commit against.

Trade-offs

  • Auto-replace vs manual: auto-replace keeps the queue moving but overpays during fee spikes; manual is safer for high-value transfers. Decide by value at risk against your latency SLA.
  • Public mempool vs private relay (Flashbots): private avoids front-running but adds a dependency that can fail silently.
  • Synchronous wait vs async reconciler: synchronous is simpler but ties up a request for 12.8 min; an async poller is the production choice.

Failure modes

  • Double-spend from re-signing with a fresh nonce after a timeout: detect by reconciling on-chain nonce against the DB nonce.
  • Stuck queue from one underpriced tx: alert on a nonce gap > 0 for more than 5 min.
  • Crediting a user on one confirmation, then a reorg: detect by committing only on finalized.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Make a blockchain payment workflow idempotent.

Answer

The 90-second version. The chain hands you one idempotency anchor for free: the account nonce. A nonce can be included at most once, so if I bind each payment operation to a nonce, retries and fee replacements collapse into the same operation instead of becoming new payments. Everything else is bookkeeping around that.

Concretely: the client sends an idempotency key scoped to payer, payee, chain, asset, amount, and a client request id. The server writes an intent row with a unique constraint on (payer, chain_id, nonce) before signing. Then it signs, broadcasts, and records every transaction hash that shares that nonce. Reconciliation reads finalized state, not just a receipt. Off-chain fulfillment fires once, keyed on the operation id.

Assumptions: an EVM account-model chain, one signer per payer, and we control the fulfillment side. On UTXO chains there is no account nonce, so the anchor has to be a designated UTXO or an application-level lock instead.

Why the intent must precede signing. Signing is the point of no return. A signed transaction can be broadcast by anyone holding it and can land without the server ever knowing. If you sign first and crash before persisting, you have an unrecorded payment that may still confirm: unrecoverable. Persist first and crash, and you have a dangling intent with no transaction, which is safe: you retry it or expire it. The ordering makes the crash window fail toward "no payment" rather than "payment you can't see."

SQL
CREATE TABLE payment_intent (
  op_id     UUID PRIMARY KEY,        -- client idempotency key
  payer     TEXT   NOT NULL,
  payee     TEXT   NOT NULL,
  chain_id  BIGINT NOT NULL,
  asset     TEXT   NOT NULL,
  amount    NUMERIC NOT NULL,
  nonce     BIGINT NOT NULL,
  state     TEXT   NOT NULL DEFAULT 'INTENT',
  tx_hashes TEXT[] NOT NULL DEFAULT '{}',
  UNIQUE (payer, chain_id, nonce)    -- the real guard
);

The unique constraint is what stops two intents from claiming the same nonce. A retry with the same op_id hits the primary key; a different op_id trying to reuse a nonce hits the second constraint and is rejected.

Trace of a retry plus a fee bump.

teventstate
0client POSTs op_id=abc, nonce 42INTENT
1sign tx A (nonce 42, 20 gwei), broadcast, hash 0xASIGNED, hashes {0xA}
2client times out, retries abc; server returns 0xA, no new txSIGNED
30xA stuck 90 s; fee-bump same nonce at 40 gwei, hash 0xBSIGNED, hashes {0xA,0xB}
40xB mined in block 100CONFIRMED
5reorg drops block 100; receipt for 0xB goneback to SIGNED, still watching both hashes
60xB re-mined in block 102; finalized at 102+64FINALIZED, fulfillment fires once

Step 5 is why you reconcile against finality. Post-Merge Ethereum finalizes a checkpoint two epochs out: 64 slots at 12 s, about 12.8 minutes. A receipt at one confirmation is a hint, not a fact. If fulfillment had fired at step 4, the reorg would have shipped goods against a payment that briefly didn't exist; the fix is to gate fulfillment on FINALIZED, not CONFIRMED.

Trade-offs. The intent table costs a durable write and a round trip before broadcast: single-digit milliseconds locally, but it's a state machine you now own. Key scope is the sharp edge: too coarse (payer+payee only) blocks a legitimate second payment to the same person; too fine (include a timestamp) defeats idempotency entirely. Client-side keys alone are enough when the client is the only retry source and can persist its own key; you need the server-side table once retries can come from a queue, a webhook, or a mobile app that loses local state.

Failure modes and detection.

failuredetectionrecovery
duplicate fulfillmentunique-constraint violation on the fulfillment keyreject the second write; alert
nonce gap stalls later paymentspending nonce > latest nonce for > 2 minfee-bump the stuck nonce (geth's txpool requires ≥10% price bump to replace)
reorg after fulfillmentfinalized checkpoint no longer contains the txdo not reverse fulfillment; flag for manual review
ambiguous timeoutnonce still unused on-chainresubmit the same signed tx; never mint a new payment

The last row is the whole point: an ambiguous timeout is resolved by asking the chain whether the nonce was consumed, not by creating a fresh operation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Design transaction authorization beyond signature verification.

Answer

Assumptions: EVM, secp256k1 EOA signers behind a smart account (Safe-style 3-of-5), treasury-scale operations, chainId 1. The question is the gap between "a key signed these bytes" and "this business action is authorized."

The 90-second answer

Signature verification is one gate out of six. A signature proves a key holder signed a specific byte string. It does not prove the signer understood the effect, that the effect is within policy, that the signer is still authorized, or that the bytes can't be replayed elsewhere. So: bind the signature to a domain, bind it to a decoded intent, check policy, add a delay with an exit, then verify the accepted effect.

1. Domain binding. EIP-712 domain separator is keccak256(abi.encode(typeHash, keccak256(bytes(name)), keccak256(bytes(version)), chainId, verifyingContract)). Drop chainId and a testnet signature replays on mainnet; drop verifyingContract and it replays against a second contract running the same code. EIP-155 exists because of exactly that. Also enforce low-s (s <= n/2, n/2 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) so (r, s) and (r, n-s) don't both verify: EIP-2 made that consensus-critical.

2. Intent binding. Decode the calldata and render the effect: 0xa9059cbb = transfer(address,uint256), 0x095ea7b3 = approve, 0xa22cb465 = setApprovalForAll. Show recipient, amount, and the delta to the signer's own balances. If the wallet can't render it, it is blind signing and the signature is worthless as authorization.

3. Policy. Signer role, target allowlist, per-transaction cap, rolling rate limit, and a selector allowlist that excludes delegatecall and upgrade paths unless a separate quorum approves them.

4. Delay and exit. Timelock (48h is typical for treasury) with a public cancellation path, so a compromised signer still has to survive two days of observation.

5. Verify the accepted effect. Simulate at execution time with eth_call plus state overrides, then assert post-state.

Trade-offs

on-chain policy moduleoff-chain policy service
trustnone beyond the chainadds a relayer you must trust
cost~30–60k gas per check~0 gas, one HTTP hop
change latencycontract upgrade + timelockdeploy in minutes
failurerigid; a bad rule bricks opssilent bypass when the service is down

Threshold: 3-of-5 roughly doubles signing latency and survives one lost key; 2-of-3 is faster but one phish plus one more key drains the account.

Failure modes

failurereal casedetection
blind signing / UI spoofBybit, Feb 2025 ($1.4B): signers approved a delegatecall that swapped the Safe implementation; Radiant Capital, Oct 2024 ($50M): hardware wallets signed an undecodable transferOwnershipalert on delegatecall/upgrade selectors from an account that never used them; compare the hash on the hardware screen against the one the UI shows
cross-chain replayEIP-155 was added after ETH/ETC split replaysreplay every signature on a testnet fork in CI; it must fail
EIP-1271 wallet returns 0x1626ba7e unconditionallyrecurring contract-wallet bugfuzz with random signatures; any magic-value return is a bug
nonce reusetwo signers sign different txs at nonce 42index by (account, nonce), alert on duplicates
approval phishingsetApprovalForAll drains a walletmonitor ApprovalForAll from addresses with no prior interaction

Worked trace

3-of-5 Safe, 250,000 USDC/day cap, 48h timelock. Request: transfer 400,000 USDC to 0xVendor.

  1. Decode: selector 0xa9059cbb, to 0xVendor, amount 400000e6.
  2. Domain: chainId=1, verifyingContract=Safe. Match.
  3. Signers: 3 recovered addresses are owners. Pass.
  4. Policy: 400,000 > 250,000 daily cap → not rejected, escalated: 250,000 now, 150,000 queued.
  5. Timelock: ETA = now + 48h, event emitted, anyone may cancel.
  6. At ETA: eth_call with state override; Safe's USDC balance ≥ 400,000 and nonce still 42.
  7. Execute; assert the Transfer event and post-balance.

The signature is gate one, not the answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design an oracle-dependent contract safely.

Answer

Core answer (first 90 seconds)

An oracle is a trust boundary, not a data source. The contract cannot verify an external fact: it can only choose who it trusts, how much, and how fast it reacts when they are wrong. So the design is four decisions, in order:

  1. Name the fact and its precision. "ETH/USD, 8 decimals, valid for 5 minutes", not "the price."
  2. Pick a source whose manipulation cost exceeds your contract's extractable value. If a wrong price lets someone drain $2M, a feed secured by $500k of stake is the wrong feed.
  3. Bound what a wrong value can do. Limits, circuit breakers, delayed settlement.
  4. Have a stop. Pause authority, dispute path, fallback feed.

Assume: EVM L1/L2, a lending contract that liquidates on price, you control the contract but not the feed.

Mechanism

Why aggregation secures a value. Chainlink's OCR takes a median of independent node reports on-chain. To move the answer you must corrupt more than half the reporters, not one. Nodes are staked and slashed for provable misreporting, so the attack cost is stake plus business loss. ETH/USD on Ethereum mainnet updates on a 0.5% deviation threshold or a 1-hour heartbeat: meaning the on-chain answer can legitimately lag spot by up to 0.5%.

Why a TWAP resists manipulation. A Uniswap V3 30-minute TWAP requires the attacker to hold the manipulated price for the whole window. Spot reserves can be flash-loaned in one block; a 30-minute average cannot. Cost scales with liquidity × duration.

Why a circuit breaker bounds impact. If the new price deviates >20% from the last in one block, pause liquidations. Worst case you are stale for one block instead of liquidating a solvent borrower at a bad price.

Why delayed settlement buys you a dispute window. Queue a price change and apply it after N blocks, so a bad value can be challenged before it settles.

Reading a feed safely

SOLIDITY
// Solidity ^0.8.20, Chainlink AggregatorV3Interface
uint256 constant MAX_STALENESS = 300; // 5 min, tighter than the 1h heartbeat

function getPrice() internal view returns (uint256) {
    (uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) =
        feed.latestRoundData();
    require(answer > 0, "bad price");
    require(updatedAt != 0 && block.timestamp - updatedAt <= MAX_STALENESS, "stale");
    require(answeredInRound >= roundId, "stale round");
    return uint256(answer);
}

Trade-offs

OptionCostWhen to use
Push feed (Chainlink)Gas paid by oracle, ~1h heartbeatLiquidation, needs liveness
Pull oracle (Pyth)Caller pays, price + confidence intervalLatency-sensitive, L2
TWAPLags spot, thin pools manipulableDEX-native, no external feed

Failure modes and detection

  • Stale feed: heartbeat missed. Detect: updatedAt age > MAX_STALENESS; alert on age p99.
  • Outlier: one reporter wrong. Detect: deviation vs a second independent feed.
  • Wrong domain: ETH/USD used for stETH. Detect: assert the feed address per asset in config, never derive it.
  • Key compromise: reporter key. Detect: on-chain deviation plus off-chain monitoring.
  • Market discontinuity: exchange halt. Detect: divergence between two independent feeds.

Arithmetic

Deviation threshold 0.5% + 1h heartbeat. If your liquidation threshold is 1%, a 0.5% stale deviation consumes half your buffer. Set MAX_STALENESS = 300s on the liquidation path, not 3600s: you trade occasional reverts for not liquidating on an hour-old price.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Design a ledger-backed materialized view.

Answer

Assume the ledger is an ordered chain of blocks, each with height, parent hash, and transactions with unique ids. The view is a SQL table for current balances. The goal is a queryable projection that can be rebuilt from canonical blocks and never serves data from a branch the node has abandoned.

Keep a checkpoint table in the same database as the view:

SQL
CREATE TABLE view_checkpoint (
  id int PRIMARY KEY DEFAULT 1,
  height bigint NOT NULL,
  block_hash bytea NOT NULL,
  schema_version int NOT NULL
);

CREATE TABLE applied_tx (
  tx_hash bytea PRIMARY KEY,
  height bigint NOT NULL,
  block_hash bytea NOT NULL
);

CREATE TABLE account_balance (
  account_id bytea PRIMARY KEY,
  balance numeric NOT NULL,
  last_tx_hash bytea NOT NULL,
  last_height bigint NOT NULL,
  final boolean NOT NULL DEFAULT false
);

Apply one block per database transaction. Verify block.parent_hash = checkpoint.block_hash and block.height = checkpoint.height + 1. For each transaction, INSERT INTO applied_tx ... ON CONFLICT DO NOTHING; only if the insert actually happened, apply the balance delta. Then update the checkpoint to the new height and hash. This makes replay idempotent: a retry after a crash re-reads the same block, the applied_tx conflict skips the delta, and the checkpoint advances once. Atomic checkpoint plus view update means the view and its position never disagree.

Reorg detection is a hash comparison. When a new block arrives at height H, compare its parent hash to the stored hash at H-1. If they differ, walk backward until the stored hash matches an ancestor. For example, checkpoint is height 100, hash 0xA100. A block 101 arrives with parent 0xA99. Stored block 99 is 0xA99, so the common ancestor is 99. Blocks 100 and 101 are no longer canonical.

Two ways to repair. Reverse-and-reapply keeps an undo log: for each applied transaction, store the before-value. On a reorg of depth d, reverse d blocks, then apply the new branch. Cost is O(d) writes plus undo-log storage. It is the right default for shallow reorgs, say d ≤ 6, because it avoids replaying the whole chain. Rebuild drops the view and replays from genesis or the last snapshot. Cost is O(chain length) or O(snapshot + d). It is simpler and safer for deep reorgs, schema migrations, or suspected corruption. A snapshot every 10,000 blocks bounds rebuild time. If the chain has 12-block finality, mark rows final after 12 confirmations; queries that need finality filter final = true.

Failure modes and detection:

  • Stale view: checkpoint height lags node head. Monitor node_head - checkpoint.height; alert if lag exceeds 30 blocks or 2 minutes. Symptom: users see old balances. Cost: stale reads.
  • Silent reorg: parent hash mismatch is ignored, so the new branch is applied on top of the old one and balances double-count. Detect by always checking parent hash before apply. Cost: corrupted view requiring rebuild.
  • Ledger reset: node switches network or genesis. Detect by comparing genesis hash or chain id. Refuse to apply and require an explicit rebuild.
  • Non-idempotent apply: a retried block applies a transaction twice. Detect via applied_tx unique violation or balance drift. Cost: incorrect balances.
  • Schema drift: checkpoint.schema_version differs from code. Detect at startup. Run migration or rebuild.

Expose checkpoint.height, block_hash, node_head, and lag on a health endpoint. A fast stale view is still stale; the lag metric is what stops it from being treated as authoritative.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design off-chain document anchoring with content IDs and a ledger.

Answer

I'll start by clarifying the trust model. I'll assume a permissioned ledger like Hyperledger Fabric for cost and privacy, documents are JSON or PDF, and we need integrity, timestamping, and non-repudiation. Authorized issuers anchor documents; verifiers check integrity without trusting the storage provider.

Here's the design.

First, canonicalize the document to a deterministic byte sequence. For JSON, use RFC 8785 JCS. For PDFs, use the exact bytes as produced; if normalization is needed, define a canonical PDF profile that removes metadata and linearizes. Why does this matter? Two serializers can produce different bytes for the same logical document. For example, {"b":2,"a":1} in Python default serialization is {"b": 2, "a": 1}, while JCS produces {"a":1,"b":2}. Those hash differently, so the content ID would not match. Canonicalization fixes that.

Second, hash the canonical bytes with SHA-256 to get a 32-byte digest. For content-addressed storage, wrap that in a multihash and encode as CIDv1, e.g., bafybeig... in base32. That CID is the content ID. For a document containing the bytes hello, SHA-256 is 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824.

Third, store the bytes in S3 with versioning, SSE-S3 encryption, and a bucket policy that only the anchoring service can write. Optionally pin to IPFS for content-addressed retrieval; the CID is the same.

Fourth, anchor on the ledger. Write a transaction with the CID, a monotonic version integer, the ledger timestamp, a storage pointer (S3 object key or IPFS CID), and the issuer's signature. The ledger gives ordering and immutability. For batching, compute a Merkle root of many CIDs and anchor the root in one transaction; include the Merkle proof in off-chain metadata. This binds the content ID to the ledger entry: the CID is in the transaction, and the signature ties it to the issuer.

Fifth, verify. Fetch the bytes, recompute SHA-256, compare to the CID. Fetch the ledger entry, verify the issuer signature and that the CID matches. Check the timestamp against the ledger block time.

Now the tradeoffs. I'd compare public Ethereum vs permissioned Fabric: public is transparent but costs more and has reorg risk; permissioned is private, cheap, and has instant finality. For storage, S3 gives 11 9's durability and access control; IPFS is content-addressed but requires pinning and doesn't guarantee persistence. For hashing, SHA-256 is standard and interoperable; BLAKE3 is faster but less supported. For anchoring, per-document transactions are simple but expensive; Merkle batching is cheap but adds proof complexity. The deciding criteria are privacy, cost, finality, and volume.

Failure modes I'd watch for. Canonicalization mismatch: two parties serialize JSON differently, producing different hashes. Detect by using JCS test vectors and logging canonical bytes. Storage unavailability: S3 bucket deleted or IPFS unpinned. Detect by monitoring retrieval success rate and setting up cross-region replication. Ledger reorg: on public chains, a transaction can be reorged. Detect by waiting for finality, e.g., 12 blocks on Ethereum. Key compromise: an attacker signs new versions. Detect by monitoring for unexpected ledger entries and using multi-sig or an HSM. Privacy: a hash of a low-entropy document like a boolean can be brute-forced. Detect by using a salted hash or encrypting the document before hashing.

For cost, consider storing 1 KB on Ethereum. 1 KB is 1024 bytes. Calldata gas is 16 gas per non-zero byte, so 1024 * 16 = 16,384 gas. At 20 gwei and $2000/ETH, that's 16,384 * 20e-9 * 2000 = $0.655. With Merkle batching, 1000 documents produce a 32-byte root. One transaction with 32 bytes calldata costs 32 * 16 = 512 gas, or $0.02048. Per document, that's $0.00002048. These are example figures.

If deletion is required, you can't delete the ledger entry, but you can delete the off-chain bytes and write a revocation transaction. And remember: the hash proves integrity, not source truth; the ledger timestamp proves existence at a time, not that the content was true then.

That's the design: canonicalize, hash to a CID, store off-chain, anchor the CID and metadata on a ledger, and verify by recomputing the hash and checking the ledger entry.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Define identity and versioning for a blockchain integration.

Answer

Core answer (first 90 seconds)

Assume EVM-compatible chains, we run an indexer and a signer, and the same application talks to mainnet and at least one testnet. Identity has three layers that fail differently (the chain, the contract/asset, and the message) plus versioning, because the same address can point at different code over time.

Pin chain identity with the EIP-155 chain ID and the genesis block hash. Chain ID alone is just what the RPC tells you; a misconfigured or hostile endpoint returns whatever it likes. Genesis is the anchor: mainnet is chain ID 1 with genesis 0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3; Sepolia is 11155111. Assert both at the client boundary, before application code runs.

Contract identity is the EIP-55 checksummed address plus keccak256 of the deployed bytecode. The checksum catches transcription errors; the bytecode hash catches a proxy whose implementation changed under a stable address. For proxies, read the EIP-1967 implementation slot 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc during reconciliation and alert on change.

Asset identity is (chainId, contract address), never the symbol. USDC is 6 decimals on mainnet, not 18, and two tokens can both call themselves USDC.

Message identity: an EIP-712 domain separator binds chainId and verifyingContract into every signature, so a signature for one chain cannot be replayed on another. For events, key on topic0 plus the indexed schema: ERC-20 and ERC-721 Transfer share topic0 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef but mean different things. For our own writes, an application operation ID plus (txHash, logIndex) makes retries idempotent.

TypeScript
// viem 2.x
import { createPublicClient, http } from 'viem'
import { mainnet } from 'viem/chains'

const EXPECTED_CHAIN_ID = 1
const EXPECTED_GENESIS =
  '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3'

const client = createPublicClient({ chain: mainnet, transport: http(RPC_URL) })

if ((await client.getChainId()) !== EXPECTED_CHAIN_ID)
  throw new Error('wrong chain')

const genesis = await client.getBlock({ blockNumber: 0n })
if (genesis.hash !== EXPECTED_GENESIS)
  throw new Error('genesis mismatch: RPC is lying or forked')

Trade-offs

Full verification costs two extra RPC calls per session (chainId, genesis) plus a storage read per contract per reconciliation. That is cheap for anything that moves funds. For a read-only dashboard or a low-value flow, chain ID plus a checksummed address allowlist is enough. The deciding question is whether a mismatch causes an irreversible state change: if it does, pin genesis and bytecode; if it only mislabels a chart, do not pay for it.

Failure modes and detection

  • Fork replay. Pre-EIP-155 signatures (v = 27 or 28) carry no chain ID and are valid on both sides of a split: this is what happened after the 2016 Ethereum/ETC fork. Detect by rejecting v ∈ {27,28} and requiring chainId in the EIP-712 domain.
  • Testnet/mainnet mix. CREATE2 deployers produce the same address on every chain, so an address allowlist passes on Sepolia. Detect with the chainId assertion at the RPC boundary; the symptom is a "confirmed" row the mainnet contract never saw.
  • Silent proxy upgrade. Bytecode at the address is unchanged; the implementation slot moved. Detect by diffing the EIP-1967 slot each reconciliation.
  • Reorg. Same height, different hash. Store (height, hash) and re-verify; on Ethereum PoS, wait for finality at two epochs (~12.8 minutes) before treating a write as settled.

Identity dimensions

dimensionvalue to pinwhat breaks without it
chainchainId (EIP-155) + genesis hashRPC points at testnet or fork; replay
contractEIP-55 address + keccak256(deployed bytecode)lookalike address; silent upgrade
proxyEIP-1967 implementation slotlogic swapped under a stable address
asset(chainId, address) + decimalssymbol collision; 6 vs 18 decimals
messageEIP-712 domain (chainId, verifyingContract)cross-chain signature replay
eventtopic0 + indexed schemaERC-20 vs ERC-721 Transfer confusion
operationapp op ID + (txHash, logIndex)double-processing on retry

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Evaluate storing personal data on-chain.

Answer

What I'd say first

"On-chain" needs pinning down: a public permissionless chain like Ethereum mainnet, or a permissioned ledger like Hyperledger Fabric where you control the nodes? The answer flips on that. On a public chain my default is no: don't put personal data there. Store a commitment on-chain and the record off-chain in a system you can actually delete from. On a permissioned ledger with a small, contractually bound validator set you can sometimes store data, but you've built a slow, expensive database and you still owe the data subject erasure.

Why replication is the problem

Every full node holds the full state, and archive nodes keep every historical state. Ethereum mainnet has run thousands of full nodes for years; the data sits on all of their disks. Finality means rewriting a block requires controlling a supermajority of stake: practically infeasible. So "delete" has no implementation. GDPR Article 17 gives a right to erasure; Article 5(1)(c) and (e) require minimisation and storage limitation. A ledger that cannot forget is in direct tension with all three. Fines under Article 83(5) reach €20M or 4% of global annual turnover.

The commitment pattern, and where it leaks

Store keccak256(salt || record) on-chain; keep record off-chain.

SOLIDITY
// Solidity 0.8.24
contract RecordAnchor {
    mapping(bytes32 => uint256) public anchoredAt;
    function anchor(bytes32 commitment) external {
        require(anchoredAt[commitment] == 0, "already anchored");
        anchoredAt[commitment] = block.number;
    }
}

Off-chain: commitment = keccak256(abi.encode(salt, recordBytes)). Anyone holding the record recomputes and compares.

Two leaks. First, low-entropy fields are brute-forceable: a date of birth plus postcode is maybe 10^6 combinations. An attacker enumerates the space and matches the hash. The salt must carry real entropy and stay secret, which is key management again. Second, the transaction graph leaks regardless of payload: which addresses call the contract, when, and how much. Clustering heuristics (shared funding, timing) re-identify people without ever touching the ciphertext. Hashing is pseudonymisation, not anonymisation, under GDPR Recital 26: it is still personal data.

Cost, as a sanity check

Anchoring one 32-byte commitment: 21,000 base + 32 × 16 calldata + 20,000 for a zero→non-zero SSTORE + ~2,000 overhead ≈ 44,000 gas. At 20 gwei and $3,000/ETH that's about $2.60 per record: illustrative, but it shows you pay per row forever. Storing the 1 KB record itself in storage is 32 slots × 20,000 = 640,000 gas ≈ $38, and it never goes away.

Failure modes and how you'd catch them

  • Salt/key loss: the commitment becomes unverifiable. The data is effectively gone but you can't prove what it was. Detect with a key-availability monitor and threshold escrow.
  • Cryptography aging: hash preimage resistance degrades; Grover's algorithm halves effective security. Track NIST deprecation timelines and version the commitment scheme.
  • Erasure request arrives: you delete the off-chain copy, but the commitment and the transaction remain. Detect by maintaining a data map (RoPA) listing every on-chain artefact tied to a subject, so you know what you cannot delete before you promise you can.
  • Brute-force of low-entropy commitments: catch it with an entropy audit of every field you commit to.

Alternatives

An off-chain database with periodic Merkle-root anchoring gives verifiability without replication. A zk-SNARK over a private database proves a property without publishing the data. If you genuinely need shared write access with no trusted operator, a permissioned ledger with a small validator set is the least-bad chain option, but confirm with privacy counsel before you commit, and record the residual inability to erase replicas as a known limitation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Run a blockchain-versus-database architecture decision.

Answer

Core answer, first 90 seconds

One question decides this: does more than one party need the power to reject a unilateral write? If a single operator can be the authority, even one that must be auditable, you want a database plus a signed append-only log, not a blockchain. A ledger earns its cost only when several mutually-distrusting parties share write authority and none of them may unilaterally rewrite history.

State your assumptions out loud: who the writers are, whether they are known and permissioned or open, what the dispute actually is (a wrong balance, or a deleted record), and the latency and throughput budget.

The decision, in order

  1. Writers. One accountable operator → database. Many parties who will not accept one writer → ledger.
  2. Adversary. If the threat is a lying operator, a hash-chained log with external anchoring, publish the daily root to a third party or a public chain, gives tamper-evidence at a fraction of the cost.
  3. Dispute. In a database the operator's log is the authority and the operator can edit it. In a ledger each party recomputes the state root and compares, but only if they actually run validating nodes.
SignalDatabase + signed logLedger
Writersone accountable operatormany, mutually distrusting
Disputeoperator's log is authorityeach party recomputes state root
Latencyp99 single-digit ms12 s slot, ~12.8 min finality (Ethereum)
Throughputtens of thousands TPS (Postgres, one node)~15 TPS public; ~3,500 TPS Fabric (2018 paper)
CorrectionUPDATE plus an audit rowcompensating transaction; history immutable

Why replication costs what it does

A database executes a transaction once and returns when the single writer commits. A replicated ledger executes the same transaction on every validator and waits for consensus before it is final. That is the whole cost: N× execution plus a consensus round, not the cryptography. Ethereum mainnet does roughly 15 simple transfers per second with 12-second slots and ~12.8-minute finality (two 32-slot epochs). Hyperledger Fabric, which orders and endorses rather than re-executing on every peer, reported ~3,500 TPS in its 2018 EuroSys paper. A simple transfer is 21,000 gas: about $0.32 at 5 gwei and about $126 at 2,000 gwei, at $3,000/ETH.

Failure modes and how you see them

  • Slow validator stalls the chain. Throughput is bounded by the slowest node. Detect: per-node commit latency and mempool depth.
  • Governance deadlock. An upgrade needs M-of-N signatures; a departed member or a lost key freezes the contract. Detect: age of the oldest pending proposal.
  • Non-determinism. Chaincode reading wall-clock time or a random source diverges across validators; endorsement fails or state forks. Detect: endorsement-policy failures and state-hash mismatch.
  • Cost blowup. A batch that costs $0.32 at 5 gwei costs ~$126 at 2,000 gwei. Detect: per-transaction gas dashboards.
  • Privacy and erasure. Public chain state is world-readable and immutable; PII on-chain is a GDPR problem. Detect: data-classification scan of contract state.
  • Vendor risk. AWS QLDB, a managed ledger, was announced end-of-support in 2024. Ledger-as-a-service is not a safe default.

When not to use it

If one operator is accountable and the requirement is audit, use a database plus a hash-chained audit table and periodic external anchoring. You get the tamper-evidence without replicated execution or governance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Build a blockchain integration test and observability plan.

Answer

Assume an EVM chain, one service that submits transactions, an indexer, and a UI that shows pending versus finalized. The plan is three layers, and the criterion that decides what goes in each is: does this failure lose money or double-spend? If yes, it gets a deterministic test. If no, it gets a metric and an alert.

Layer 1, deterministic, on every PR: a local node where you control mining. Layer 2, fork or staging, nightly: two real clients (Geth and Nethermind) behind a proxy you can make lag or lie. Layer 3, public testnet, before release: real fees, real reorgs, rate limits.

Why reorgs break projections: the mechanism. Your indexer writes a row when it sees a transaction in a block. If that row is keyed by transaction hash, a reorg cannot find it to undo. Key by (block hash, tx hash) and store the parent-hash chain, so on a parent-hash mismatch you roll back every row at or above the fork point and re-apply. Trace: tx T lands in block 100. Indexer writes (T, 100, included). At 102 the chain reorgs 100–101 away; the node's head is 102' with a different parent. The indexer compares the stored parent hash of 100 against the node's 100' parent, sees the mismatch, deletes rows with block >= 100, and replays 100'–102'. Had you keyed on tx hash alone, T stays "included" forever and the UI lies.

testprovesmetricthreshold
duplicate intent, two workers, same idempotency keyexactly one on-chain effecton-chain txs per intent== 1
nonce race, two workers, same noncereplacement handledreplacement count, pending agepending p99 < 3 blocks
fee too lowstuck tx detectedpending agealert > 2 min on a 12s chain
reorg depth 2 vs 12rollback correctnessindexer head minus node finalizedalert > 2 pre-finality
RPC equivocationprovider disagreement caughthead hash mismatch across >= 2 providersany mismatch

Arithmetic for the UI: Ethereum slot is 12s, an epoch is 32 slots = 6.4 min, finality is about two epochs, roughly 12.8 min. So "finalized" is a ~13-minute promise, not one confirmation. A UI that says finalized at one block is wrong on every reorg.

Trade-offs. Deterministic tests are fast and never flaky, but a scripted local reorg proves your rollback code, not your reorg detection. Fork tests catch client-specific behaviour, Geth and Nethermind differ in mempool handling, but they are slow and flaky, so run them nightly, not per-PR. Testnet is the only place you see real fee markets and MEV-driven reorgs, but it is non-deterministic and rate-limited; use it as a release gate, not a debugger. Do not run fork tests per-PR; the flake cost exceeds the signal.

Failure modes and detection. Nonce collision shows as a replacement event and a pending age that stops advancing; alert on replacement count > 0 per intent. Insufficient fee shows as pending age p99 climbing past three blocks; alert at 2 min. RPC equivocation shows as two providers returning different head hashes for the same height; poll both every block and alert on mismatch. Indexer divergence shows as indexer head lagging node finalized by more than two blocks; alert and page. Key rotation shows as signature failures with a distinct error code; alert on any occurrence.

Curated: · Written: · Reviewed:

Difficulty: Hard