Skip to content
Tech Interview Prep
Technical interview guide

Consensus Mechanisms

How a distributed network of untrusted nodes agrees on a single canonical transaction history: Proof of Work, Proof of Stake, and BFT-style consensus.

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

Scope: NISTIR 8202; Bitcoin white paper; Ethereum proof-of-stake documentation reviewed 2026-09-04; CometBFT main specification reviewed 2026-09-04; PBFT, HotStuff, and Raft papers.

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

Define safety and liveness for a blockchain protocol.

Answer

I'd pin the model first: n validators, up to f Byzantine, partially synchronous network, quorum 2f+1 (or 2/3 stake). Safety: no two honest nodes finalize conflicting blocks. Liveness: a valid transaction eventually finalizes when the network is synchronous and a quorum is online. Those are the two properties; the tension is that under partition you can't always have both.

Mechanism: quorum intersection. Any two 2f+1 quorums in n=3f+1 overlap in at least f+1 nodes, so at least one honest node is in both. If that honest node locks or votes once, conflicting finality would require it to double-vote or >f Byzantine. That's why safety holds even if the network splits. Liveness needs 2/3 online and messages delivered within timeout; if not, the protocol stalls rather than risk conflicting finality. If you try to keep liveness during a partition by lowering quorum, you break safety: two sides could each finalize.

Concrete trace: Tendermint with n=4, f=1, quorum=3. Partition {A,B} vs {C,D}. Neither side has 3 votes, so no block commits. Safety holds; liveness lost. If the split is {A,B,C} vs {D}, the 3-validator side commits, D cannot. When healed, D must sync to the finalized chain. If D signed a conflicting block, that's a double-vote, slashable.

ProtocolFinalityQuorumPartition behavior
Tendermintabsolute at commit2f+1 of 3f+1halts if no quorum
Casper FFGabsolute after 2 epochs (~12.8 min)2/3 stakefinality stalls; fork choice may reorg before finality
Bitcoinprobabilistic, 6 confirmationslongest chainkeeps producing, reorg risk

Ethereum's Casper FFG finalizes after two epochs, each 6.4 min (32 slots * 12s), so ~12.8 min. Before that, LMD GHOST fork choice can reorg. Bitcoin is probabilistic: 6 confirmations, reorg probability drops with depth. So absolute vs probabilistic finality is the design choice.

Failure modes: double-vote, surround vote (Casper), long-range attack. Detection: slashing proofs from signed votes; finality stall >2 epochs. Cost: slashing loses stake; stall halts withdrawals and exchange deposits.

Trade-off: absolute finality (Tendermint, Casper FFG) halts on partition, good for settlement. Probabilistic (Bitcoin) keeps liveness, good for high-throughput but reorg risk. Choose based on whether you need irreversible settlement or continuous progress.

Recovery: authenticated by signed quorum certificates. A light client verifies a finality proof signed by 2/3; a rejoining validator uses a weak subjectivity checkpoint. That's the answer.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-11

Compare proof of work and proof of stake.

Answer

What I'd say first

Both mechanisms make block production expensive, but they price different resources. PoW prices external work: you burn electricity and hardware, and the chain with the most accumulated work wins. PoS prices bonded capital: you lock ETH, and the chain that two-thirds of the stake attests to finalizes. The practical consequence is that PoW gives you probabilistic settlement with no finality, while PoS gives you explicit finality but requires a fresh node to trust a recent checkpoint.

The numbers

Bitcoin, 2025: 10-minute block target, network hashrate in the 700-900 EH/s range, energy draw estimated at 150-180 TWh/yr by CBECI. Six confirmations is about 60 minutes, and reorg probability falls off sharply with depth.

Ethereum: 32 ETH per validator, roughly a million validators, 12-second slots, 32-slot epochs. A checkpoint is justified after one epoch and finalized after two: about 12.8 minutes: once two-thirds of stake attests. Reverting a finalized checkpoint requires at least a third of stake to be slashable, which is the whole reason slashing exists.

Slashing, concretely

An attestation violation costs 1/32 ETH minimum. A surround vote or a double proposal costs the full 32 ETH, plus a correlated penalty that scales with how many other validators were slashed in the same window: a mass event can drain entire stakes. You watch for it on the beaconcha.in slashing feed and in client logs; one slashing is noise, a correlated one is an incident.

Where each fails

PoW: a 51% attacker rents hashrate and double-spends. Ethereum Classic took three such reorgs in 2020, one a few thousand blocks deep, with rented hashrate costing on the order of thousands of dollars per hour. Detection is reorg-depth monitoring plus exchange deposit delays.

PoS: long-range attacks. An attacker holding old validator keys builds an alternative history from a past checkpoint, and nothing in the protocol stops it, so nodes rely on a weak subjectivity checkpoint: roughly a two-week window at current validator counts. Detection is a node refusing to sync past its checkpoint.

PoS liveness: if more than a third of stake goes offline, finality halts. Blocks keep coming, but nothing finalizes. The inactivity leak then drains the offline validators' balances until the online two-thirds regains a supermajority. Detection is finality lag.

Client diversity: a consensus bug in a supermajority client can finalize an invalid chain. Geth was over 80% of execution clients in 2022 and sits around 50-60% now; Bitcoin Core is near 99% of nodes.

Concentration and governance

PoW: the top two or three pools routinely exceed 50% of hashrate (Foundry USA, AntPool), and ASIC supply is concentrated in a handful of fabs. PoS: Lido holds roughly a quarter to a third of staked ETH, with Coinbase and Binance behind it. PoS concentration is visible on-chain and re-delegable in a day; PoW pool concentration can be switched by miners, but the hardware pipeline cannot.

Governance differs too: Bitcoin BIPs and rough consensus, Ethereum EIPs through AllCoreDevs with the social layer deciding the hard cases. The DAO fork and the Merge.

When to prefer which

Pick PoW when you want a new node to validate from genesis without trusting a checkpoint, and you can tolerate probabilistic settlement. Pick PoS when you need fast, explicit finality and cheap participation, and you accept weak subjectivity plus a social layer that can, in extremis, choose a chain.

Neither removes software bugs, network delay, or an exchange's confirmation policy.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Explain Bitcoin-style probabilistic settlement.

Answer

Core answer (first 90 seconds)

"Probabilistic settlement" means a Bitcoin payment is never final the way a bank ledger entry is. It becomes economically irreversible as work accumulates on top of it. The fork-choice rule is: among valid candidate histories, follow the one with the greatest total accumulated proof of work. A payment is settled when the cost of rewriting it exceeds the value at stake: a policy decision made by the receiver, not a protocol event.

So "when is it final?" has no absolute answer. At k confirmations the reversal probability is roughly (q/p)^k for an attacker holding fraction q of hash power, where p = 1 − q. That number, not a promise of finality, is what you defend in an interview.

Mechanism

Each block commits to its parent by hash, so rewriting block N means re-mining N and every block after it while out-pacing the honest chain. Work is the cost function; depth is the security parameter. At the 10-minute target, 6 confirmations is about 60 minutes.

The simplified gambler's-ruin bound (q/p)^k, assuming the attacker mines in private and the honest chain advances at its expected rate:

attacker share qk=1k=3k=6
10%0.111.4e-31.9e-6
30%0.437.9e-26.2e-3
40%0.670.308.8e-2

Read the 30% row: a miner with nearly a third of hash power still needs six blocks to reach a ~0.6% chance of overtaking. That is why exchanges commonly require 3–6 confirmations for BTC deposits and why the depth is a policy knob, not a constant.

Failure modes

  • Natural reorgs. Two miners find blocks within propagation delay; depth-1 and depth-2 reorgs happen most days. Detection: getchaintips in Bitcoin Core lists every known chain tip and its branch length.
  • Consensus-divergence reorg. In March 2013, v0.8 and v0.7 nodes disagreed on a block and the network reorged 24 blocks deep. Not a hashrate attack: a software bug. Detection: version telemetry, and Bitcoin Core's -alertnotify hook, which runs a shell command when it raises a warning such as a longer-than-expected fork.
  • Selfish mining. Eyal and Sirer (2014) showed withholding blocks can be profitable above roughly a quarter of hash power under their model. Detection: per-pool stale/orphan rate.
  • Eclipse. An attacker surrounds a node with fake peers and feeds it a false chain. Detection: peer diversity and outbound connection count.

Trade-offs and when not to use it

Probabilistic settlement is cheap and needs no known validator set, but it is the wrong tool when you need sub-minute finality, or when the counterparty can rent hash power: a 51% rental on a small chain costs far less than on Bitcoin, so "6 confirmations" is not portable across chains. For high-value cross-chain transfers, BFT finality (Tendermint-style, one block, 2/3 honest validators) or a federated bridge is the alternative, at the cost of trusting a named validator set.

What changes the decision

The value at risk, the attacker's plausible hashrate (rental markets make this a market price, not a constant), and whether you can tolerate a reorg at all. If you cannot, you need a different settlement layer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

Contrast deterministic and probabilistic finality.

Answer

The 90-second version. Both models answer one question: what evidence do I accept that a block will not be reverted, and what does reverting it cost? Probabilistic finality says "the deeper it is, the more work an attacker must redo." Deterministic finality says "a quorum signed a certificate, and reverting means provably breaking the fault assumption." Assume an adversary with bounded resources and a stated fault threshold: that is the only frame in which either claim means anything.

Probabilistic (Nakamoto / PoW). The chain with the most accumulated work wins. A reorg of depth z requires the attacker to out-mine the honest chain from z blocks behind; with attacker hashrate fraction q and honest p = 1−q, that probability falls roughly as (q/p)^z. Satoshi's own table: at q = 0.1, 6 blocks behind gives 0.00024 (0.024%), 10 behind gives 1.2e-6. Bitcoin's 10-minute target makes 6 confirmations ≈ 60 minutes. "6 confirmations" is exchange policy, not a consensus constant: Bitcoin Core has no such rule. Confidence is a curve, not a step.

Failure modes here are not only 51% attacks. Bitcoin's 24-block reorg on 2013-03-11 came from a consensus bug between v0.7 and v0.8 (BDB vs LevelDB), not an attacker. Ethereum Classic in August 2020 took three rented-hashrate 51% attacks that reorged thousands of blocks and double-spent. Detection is reorg-depth monitoring plus per-counterparty confirmation thresholds; the operational cost is latency: 60 minutes of settlement delay per deposit.

Deterministic (BFT / PoS). A quorum signs a block and that block is final. PBFT needs 2f+1 of 3f+1 replicas; Tendermint needs >2/3 of voting power to precommit; Ethereum's Gasper (Casper FFG + LMD GHOST) justifies and then finalizes a checkpoint with 2/3 of total staked ETH. Safety holds while Byzantine weight stays under 1/3. Reverting a finalized checkpoint requires at least 1/3 of stake to have equivocated, and that equivocation is provable: the attacker is slashed. That is the concrete cost: on Ethereum, reverting finality burns at least a third of all staked ETH.

Latency: Tendermint finalizes in one block, roughly 1–6 s on Cosmos chains. Ethereum finalizes in two epochs: 32 slots × 12 s = 6.4 min per epoch, so about 12.8 min.

The trade is liveness. Below 2/3 participation, Tendermint halts: no new blocks until validators return. Ethereum stops finalizing but keeps producing blocks: in May 2023 the beacon chain missed finality for roughly an hour. No conflicting checkpoint was finalized; the chain simply stopped finalizing. Detection is a non-finality alert on checkpoint distance; the cost is that nothing new settles.

ProbabilisticDeterministic
Evidencedepth × accumulated workquorum certificate
Revert costredo the work (hashrate)≥1/3 stake slashed, equivocation proof
Time to finality~60 min at 6 conf (Bitcoin)1 block (Tendermint) to ~12.8 min (Ethereum)
Fails when>50% hashrate, consensus bug≥1/3 Byzantine, or <2/3 online (liveness)
Detectionreorg depthslashing evidence, non-finality alert

Choosing. High-value, low-frequency settlement (exchange deposits, bridges, large transfers) wants deterministic finality or a very deep confirmation count, because the revert cost is explicit and the wait is bounded. High-throughput, low-value payments tolerate probabilistic finality, because 60 minutes of latency is worse than a 0.024% reorg risk on a $20 payment. The two are not exclusive: Ethereum ran PoW with probabilistic finality, layered Casper FFG on top to get checkpoints, then moved to PoS. If you need both properties, that is the pattern: a probabilistic chain with a deterministic finality gadget.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Explain why BFT quorum intersection prevents conflicting commits.

Answer

Core answer

Assume n = 3f+1 replicas, at most f Byzantine, quorum size 2f+1, signed messages, and honest replicas that vote at most once per view and lock before voting in a later view. Under those assumptions two conflicting values cannot both commit. Any two quorums of 2f+1 out of 3f+1 overlap in at least f+1 replicas; at most f are Byzantine, so at least one overlapping replica is honest. An honest replica's single vote cannot certify both values, and its lock stops it voting for a conflicting value later without a certificate that the earlier one did not commit. Certificates are themselves quorums, so the same counting argument applies recursively.

Worked trace

n = 4, f = 1, quorum size 3. R3 is Byzantine; R0, R1, R2 are honest.

  • Q1 = {R0, R1, R2} commits X.
  • Q2 = {R1, R2, R3} commits Y ≠ X.
  • Q1 ∩ Q2 = {R1, R2}, size 2 = f+1. At most one of them is Byzantine, so at least one, say R1, is honest.
  • Committing X required a signed vote for X from R1; committing Y required a signed vote for Y from R1. R1 is honest, so it did not sign both. Contradiction.

The counting generalises: the intersection is f+1, the Byzantine budget is f, so an honest replica is always in the overlap.

Failure modes

More than f Byzantine. With f+1 faulty replicas, two quorums can intersect in f replicas, all Byzantine, and no honest vote is shared. Detection: two signed, conflicting messages from the same replica for the same view are non-repudiable. Any node can prove equivocation by comparing signatures. Cost: safety is already gone; recovery is manual, and on a chain it means a fork resolved by social consensus rather than by the protocol.

Reconfiguration without quorum overlap. If the validator set changes so old and new quorums can be disjoint, two commits can happen across the boundary. Detection: audit the reconfiguration certificate for the required overlap between old and new sets. Cost: a hard fork or a chain halt.

Non-deterministic execution. Quorum intersection orders the requests; it says nothing about the resulting state. Map iteration order, floating-point, wall-clock reads or unseeded randomness make replicas commit the same log and diverge in state. Detection: compare state roots / app hashes across replicas after each block. Cost: the divergent node resyncs from a snapshot; if it is a chain, it halts until the divergence is found.

Unsigned messages. Without authentication a Byzantine replica forges votes and the intersection argument has nothing to bite on. Detection: signature verification on every message. Cost: none if you verify; total loss of safety if you do not.

Trade-offs

CFT (Raft, Paxos) uses majority quorums and the same intersection arithmetic, but tolerates only crash faults: one Byzantine replica can violate safety. It is cheaper: n = 2f+1 instead of 3f+1, and one round trip instead of PBFT's three phases. Choose CFT when every replica is under one operator's control; choose BFT when any replica may be adversarial.

Nakamoto consensus gives probabilistic finality with no fixed quorum and open membership, tolerating up to 1/2 of hashrate. Choose it when membership is unknown and sybil resistance must come from work; choose BFT when the validator set is known and you want deterministic finality.

Weighted BFT (Tendermint, HotStuff) applies the same argument to voting power: the quorum is 2/3 of stake, and the assumption becomes stake distribution. A single entity above 1/3 can stall liveness; above 2/3 it can violate safety. Detection: monitor stake concentration. Cost: nothing until it happens, then it is a governance crisis, not a code fix.

The guarantee also does not hold under weak synchrony for liveness: BFT safety is asynchronous, but liveness needs eventual synchrony (FLP). And it never covers application-level determinism, which is why state-root checks belong in the protocol rather than being an afterthought.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain locks and safe unlocking across consensus rounds.

Answer

Assumptions. BFT consensus, n = 3f+1 validators, quorum = 2f+1. Terminology is Tendermint/CometBFT; HotStuff's unlock rule differs and I contrast it below.

The rule. A validator that precommits block B at round r sets lockedValue = B, lockedRound = r. At any later round r' > r it prevotes a conflicting B' only if it has seen a polka, 2f+1 prevotes, for B' at some round r'' with r ≤ r'' < r'. Otherwise it prevotes nil. The lock is set at precommit time, which happens when the validator sees a polka for the proposed block.

Why it's safe. Suppose B commits at round r: 2f+1 validators precommitted B and locked on it. For a conflicting B' to commit at r' > r, 2f+1 must precommit B', so by quorum intersection at least f+1 of B's lockers must precommit B'. A locked validator precommits B' only after prevoting it, which needs a polka for B' at round ≥ r. That polka needs 2f+1 prevotes for B', so again ≥ f+1 of B's lockers must prevote B'. At round r they won't, no polka for B' at round ≥ r exists yet, and by induction none forms at any round ≥ r. So B' can't commit. The lock is the induction step.

Trace (n=4, f=1, quorum=3). Round 0: A, B, C prevote B0 → polka; A, B, C precommit B0 and lock at round 0. B0 committed. Round 1: the proposer offers B1. A, B, C are locked on B0 and have seen no polka for B1 at round ≥ 0, so they prevote nil. Only D prevotes B1: one vote, no polka, B1 can't be precommitted. Safety holds. Progress resumes when a proposer re-proposes B0 (or a descendant): A, B, C prevote it, polka, commit.

Legitimate unlock. Round 0: A, B, C prevote B0 → polka; only A precommits and locks on B0; B0 is not committed (one precommit < three). Round 1: B, C, D prevote B1 → polka at round 1. Round 2: the proposer offers B1 with validRound=1. A checks validRound 1 ≥ lockedRound 0, prevotes B1; B, C, D prevote B1 → polka → B1 commits. No safety violation, because B0 was never committed.

Trade-offs. Tendermint's unlock is polka-based: a fresh 2f+1 prevotes for the conflicting block. HotStuff's is view-based: safeNode(node, QC) = node extends lockedQC.node OR QC.round > lockedQC.round. One higher QC unlocks, so a replica can vote for a non-descendant without waiting for a polka on it. HotStuff's condition is cheaper to satisfy (one QC vs 2f+1 votes), which is why it pipelines; Tendermint's is stricter, and that costs liveness: a locked set stalls until the proposer re-proposes the locked value, so you need a round timeout to rotate the proposer. PBFT's prepared certificate plays the same role across view changes.

Failure modes.

  • Lock lost on restart: a validator that precommits B0, crashes, and restarts without its lock will prevote B1 at a later round, breaking the induction and enabling a conflicting commit. Detect via equivocation evidence: two signed prevotes at the same height and round for different blocks (CometBFT's DuplicateVoteEvidence). Cost: slashing (Cosmos Hub's default double-sign penalty is 5% of stake) and a possible halt.
  • Stale lock never released: if the locked block is unavailable, locked validators prevote nil indefinitely and the height stalls. Detect via repeated round timeouts; recover by rotating the proposer and re-proposing the locked value.
  • Unlock too loose: unlocking on any higher-round proposal instead of a polka lets two rounds commit conflicting blocks. The exact bug the lock prevents.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Handle a faulty leader in a BFT protocol.

Answer

Core answer

Assume n = 3f+1 replicas, at most f Byzantine, authenticated channels, and partial synchrony (messages eventually arrive within an unknown bound). The leader is faulty. You don't try to make it behave: you make its misbehaviour detectable and replaceable without letting it break safety. Safety comes from quorum intersection; liveness comes from a timeout-driven view change.

Concretely: a replica accepts a value only with a quorum certificate. 2f+1 matching signed votes. If the leader equivocates, withholds, or proposes garbage, correct replicas time out and broadcast a view-change message carrying their highest certificate. The next leader must adopt the highest certificate it sees and cannot propose anything that conflicts with an already-certified value. That is the whole mechanism.

Why the certificate is enough

Two quorums of 2f+1 out of 3f+1 intersect in at least f+1 replicas, and at most f are Byzantine, so at least one correct replica sits in both. If a value was certified in view v, that correct replica holds the certificate and reports it during the view change, so no later leader can ignore it. Discarding the old leader's value is safe only because the certificate is carried forward: the certificate, not the leader, is the source of truth.

Trace (PBFT-style, f = 1, n = 4)

  • View v, primary P0 proposes X. R1, R2, R3 each send PREPARE(X); P0 collects 3 = 2f+1 prepares → a prepared certificate for X.
  • P0 goes silent (omission fault).
  • R1's timer fires. PBFT backs off exponentially; Tendermint uses seconds-scale timeouts (timeoutPropose ≈ 3 s, prevote/precommit ≈ 1 s, growing per round). R1 broadcasts VIEW-CHANGE(v+1) carrying the certificate for X.
  • R2 and R3 do the same. New primary P1 collects 2f+1 = 3 VIEW-CHANGE messages, picks the highest certificate (X), and sends NEW-VIEW(v+1) containing X.
  • Replicas re-propose X under P1. Liveness restored, X preserved.

If P0 had equivocated, signed X to R1 and Y to R2, R1 and R2 exchange the two signed proposals. That is non-repudiable evidence, so the view change fires immediately rather than after a timeout, and the pair is slashable.

Trade-offs

  • Rotate vs wait. If the leader is merely slow, rotating wastes a view and can trigger view-change storms; if it is Byzantine, waiting is unbounded. Decide on evidence: conflicting signed messages → rotate now and slash; silence → rotate after a timeout with exponential backoff.
  • View-change cost. PBFT gossips every replica's certificate to the new primary, O(n²) messages. HotStuff makes it linear by aggregating votes into one threshold signature and driving views with a pacemaker. Tendermint locks validators on a polka (2f+1 prevotes), so a new proposer must supply proof of a newer polka to unlock them.
protocolquorumview-change costwhat carries safety forward
PBFT2f+1 of 3f+1O(n²)prepared certificates gossiped to the new primary
Tendermint2f+1 of 3f+1O(n²) per round, rounds are cheapvalidator lock + polka proof
HotStuff2f+1 of 3f+1O(n)threshold-signature QC in the new leader's proposal

FLP says no deterministic protocol guarantees liveness under asynchrony with even one faulty process, so every BFT protocol assumes partial synchrony for liveness. Safety never depends on the timeout.

Failure modes and detection

  • Equivocation: two conflicting signed proposals at the same height → non-repudiable evidence, slash.
  • Omission/withholding: no proposal within the timeout → view change.
  • Invalid proposal: replicas reject at validation, cast no votes, time out.
  • Targeted delivery: leader sends to a subset; excluded replicas time out and drive the view change.
  • View-change storm: backoff, plus a pacemaker that advances only on a quorum of timeout messages.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Tune and operate consensus timeouts under partial synchrony.

Answer

Assumptions I state up front: a quorum-based protocol (Raft, Multi-Paxos, HotStuff), a network that is eventually timely but whose delay I cannot bound in advance, and clocks I do not trust for safety. Under those, timeouts are a liveness mechanism only: they decide when to stop waiting for a leader, never what value is chosen.

Core answer (first 60–120 seconds). Set the timeout from the measured tail of a full round, not from a guess, and keep it strictly above that tail. Raft's own rule is broadcastTime << electionTimeout << MTBF, with electionTimeout in the 10–500 ms band and heartbeat roughly 10× smaller; the paper's 150–300 ms range assumes a LAN. etcd ships 1000 ms election / 100 ms heartbeat. Because partial synchrony gives me no bound on when the network becomes timely, the timeout has to be a moving estimate, not a constant. Then I make it back off when rounds fail and reset it when progress resumes.

SystemKnobDefaultNote
etcd / Raft--election-timeout1000 msheartbeat 100 ms
Raft paperelectionTimeout150–300 msLAN, ~10× broadcast
ZooKeepertickTime2000 msinitLimit 10, syncLimit 5 ticks
SpannerPaxos leader lease10 sTrueTime commit-wait ≈ 2ε, ε < 7 ms

Mechanism. Viewstamped Replication's pacemaker is the clean model: it keeps a moving average of round-trip time and starts a view change when a round exceeds that estimate. HotStuff's pacemaker doubles the timeout on each view that fails to decide and resets on a decided block. Exponential rather than linear backoff matters because under a real partition no finite timeout is long enough: linear growth just burns rounds, while doubling bounds wasted work logarithmically and still recovers fast once the network heals.

Safety survives round changes because the lock lives in the quorum, not in the clock. In Raft a candidate must have an up-to-date log, and a leader cannot commit an entry from an earlier term until it commits one of its own (Figure 8). In Paxos, acceptors promise not to accept lower-numbered proposals, so a new leader must re-propose the highest already-accepted value. The timeout only decides when to try; the quorum decides what is chosen.

Trade-off. Short timeout: recovery in about one timeout, but under tail latency you get spurious view changes, and each one costs a full round trip and stalls commits for at least one timeout. Long timeout: fewer spurious changes, longer unavailability. The rule I use is timeout ≈ 10× p99 round trip, and I only lengthen it when the leader-change rate is high while the network is measurably healthy: otherwise I am hiding a real fault.

Failure modes. A timeout storm is all followers timing out together, split votes, repeated elections, throughput at zero. Detect it with the leader-change counter (etcd exposes etcd_server_leader_changes_seen_total) and the view-change rate; the cost is a commit stall of at least one election timeout per change. Distinguishing a slow leader from a Byzantine one: a timeout is evidence of missing progress, not of misbehavior. A crashed leader sends nothing; a Byzantine leader sends well-formed messages that never commit. You separate them with evidence (quorum certificates, equivocation proofs) never with the timeout itself.

Worked check (illustrative numbers). Five Raft nodes across three AZs, p99 RTT 8 ms, p99 fsync 12 ms, so a round is ≈ 20 ms at p99. Election timeout = 10× = 200 ms, heartbeat 20 ms. Now load pushes p99 RTT to 60 ms: round p99 ≈ 72 ms, and 200 ms still holds. A 100 ms timeout would sit inside the tail distribution and fire on ordinary jitter: that is the election storm, and it is a tuning bug, not a faulty leader. Batching raises the processing term, and geography sets the RTT floor, so both belong in the measurement before you pick the multiplier.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Evaluate a HotStuff-style protocol for production.

Answer

Core answer (first 90 seconds). Before I trust a HotStuff deployment I pin three things, then measure them. First, which variant: original chained HotStuff commits on a three-chain, Jolteon/DiemBFT on a two-chain. That is a full round trip of latency. Second, the safety core: quorum size and the locking rule. Third, the liveness core: the pacemaker and what happens when the leader is slow or Byzantine. Only then do I look at throughput, because a protocol that is safe but never commits under a flaky leader is not production-ready.

Safety: quorum intersection and locking. With n = 3f+1 replicas a quorum is 2f+1. Any two quorums intersect in at least f+1 replicas, so at least one honest replica sits in both: that is what makes conflicting commits impossible. The locking rule enforces it: a replica votes for a block only if it extends the highest QC it has seen (its locked block). A leader pushing a conflicting branch cannot collect 2f+1 votes, because honest replicas are locked elsewhere. In code review these are the two lines that carry safety: the lock update and the vote predicate.

Liveness: pacemaker and commit rule. Progress needs an honest, timely leader after GST. The pacemaker advances the view on a timeout; production systems back off exponentially (double the timeout after each consecutive view change) so a stalled leader does not cause a timeout storm. In chained HotStuff a block commits when it, its child, and its grandchild each carry a QC: a three-chain, three round trips after GST. Jolteon's two-chain cuts that to two. Responsiveness means commit latency after GST tracks the actual network delay, not the worst-case bound Δ: it does not remove the quorum, timeout, DoS, or reconfiguration requirements.

Trade-offs. Chained HotStuff costs O(n) messages per view (leader broadcasts the proposal, n−1 votes return, leader broadcasts the QC) against PBFT's O(n²): that is why it scales. The price is latency: pipelining trades commit time for throughput. Two-chain variants (Jolteon, DiemBFT) buy back a round trip but need a slightly stronger vote rule. Leader rotation is cheap in message count and expensive in wall-clock: every view change costs a timeout plus a fresh proposal.

VariantCommit ruleRound trips after GSTMessages per view
Chained HotStuff3-chain3O(n)
Jolteon / DiemBFT2-chain2O(n)
PBFTdirect3 phasesO(n²)

Quorum arithmetic: f = 1 → n = 4, quorum 3; f = 3 → n = 10, quorum 7. Two size-7 quorums in a 10-replica set intersect in at least 4 replicas; at most 3 are faulty, so at least one honest replica is in both.

Failure modes and detection.

  • Locked replicas plus a bad leader → no commits. Detect: view-change rate climbing while committed block height stays flat.
  • Timeout too tight → constant view changes, throughput collapse. Detect: pacemaker-timeout histogram against measured RTT.
  • Timeout too loose → slow recovery from a crashed leader. Detect: time-to-first-commit after a leader kill.
  • No reconfiguration path → membership change stalls consensus. Detect: epoch/configuration-change latency.

Measure steady-state and failed-leader communication, block propagation, persistence and execution, and report the view-change rate next to the commit latency: the pair is what tells you whether the pacemaker is tuned or hiding a problem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Choose between crash-fault and Byzantine-fault consensus.

Answer

The 90-second answer

The deciding question isn't "how bad is a wrong answer": it's "can a replica lie?" If every replica runs code you control on hardware you control, and the only way one goes wrong is stopping or dropping messages, use Raft. It tolerates f crashes with 2f+1 replicas, and a majority quorum is enough because any two majorities share a replica that holds the committed entry. If a replica can be taken over by an adversary who controls its network and its clock, or if two operators can be coerced into signing conflicting statements, you need Byzantine fault tolerance: 3f+1 replicas to tolerate f liars, and signed messages so a liar can be caught.

Concretely, f=1 is 3 replicas with Raft and 4 with PBFT; f=2 is 5 versus 7. The extra replica is the cheap part. The expensive part is that every message is signed and verified, and PBFT's prepare and commit phases are all-to-all.

Why 3f+1 and not 2f+1

Raft's safety argument is quorum intersection. With 2f+1 replicas a quorum is f+1, and two f+1 sets drawn from 2f+1 always overlap in at least one replica: that replica's log is the witness the entry was committed.

Under Byzantine faults the overlap has to contain a correct replica, not just any replica. With n = 3f+1 and quorum 2f+1, two quorums intersect in at least (2f+1) + (2f+1) − (3f+1) = f+1 replicas. At most f are faulty, so at least one is correct. With n = 2f+1 and quorum f+1, the intersection can be as small as one, and that one can be the liar, which is exactly how two conflicting values get committed.

How equivocation is caught

A Byzantine primary sends pre-prepare(seq=7, v=A) to half the replicas and pre-prepare(seq=7, v=B) to the other half. In PBFT each backup broadcasts a signed prepare to all the others, so a replica that receives two different pre-prepares for the same (view, seq) holds two signed messages from the same primary and can prove the fault to everyone. Tendermint does the same with signed prevote and precommit votes: two conflicting votes at the same height and round are a self-authenticating proof. Raft has no equivalent: a leader sending conflicting AppendEntries just produces divergent logs, and nothing in the protocol notices.

Costs

RaftPBFT / Tendermint
replicas for f faults2f+13f+1
messages per decisionO(n)O(n²) for PBFT and Tendermint gossip; O(n) per view for HotStuff with threshold signatures
cryptonone requiredsignature or MAC on every message
LAN latencylow single-digit mslow tens of ms
throughputtens of thousands of small writes/sone to two orders of magnitude lower

Those are typical orders of magnitude, not benchmarks: measure your own workload before committing.

When BFT is not worth it

If all replicas sit in one cloud account, one region, one cluster, under one operator's credentials, a compromise takes all of them at once and 3f+1 buys nothing. Same if the failure you actually fear is a correlated bug or a bad deploy. BFT pays only when the adversary's reach is bounded: separate administrative domains, separate HSMs, or a consortium where no single member can coerce the others.

Failure modes worth naming. A Raft cluster spanning trust boundaries, where a compromised follower silently drops or reorders entries: detected only by comparing logs out of band, long after the fact. A BFT cluster whose replicas share one HSM or signing service, so the signature check passes and the fault model is fiction. And a BFT cluster under a malicious primary that forces repeated view changes; PBFT's exponential backoff (2^v) bounds the churn, but liveness still degrades while it lasts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Evaluate a proof-of-work network's security budget.

Answer

Core answer

Assume a longest-chain PoW network with no checkpoints, an attacker who is profit-motivated rather than spiteful, and an application that settles some dollar value per confirmation window. The security budget is the recurring cost an attacker must outspend to rewrite history, and you evaluate it by putting two numbers side by side: the cost to rent or acquire majority hash power for the time it takes to build a competing chain, and the value the application settles in that same window. If attack cost per hour is below value-at-risk per hour, the budget is inadequate regardless of how large the raw hash rate looks.

Mechanism

Hash rate buys Sybil resistance and rewrite cost. It does not buy confidentiality, input truth, or liveness. The budget that funds hash rate is (block subsidy + fees) × blocks per day. Miners will spend up to that on electricity and hardware, so it is the recurring security spend. An attacker does not need to own hardware: rental markets (NiceHash and similar) let them buy hash by the hour, so the relevant figure is the rental price, not the hardware price.

To reorg n blocks deep, the attacker must build n+1 blocks faster than the honest chain extends. Cost ≈ (hash needed to exceed honest rate) × (rental price) × (time to build those blocks).

Worked example (hypothetical figures)

Chain with 100 EH/s honest hash, rental at $0.06 per TH/day.

  • 100 EH/s = 10^8 TH/s. Majority ≈ 5.1 × 10^7 TH/s.
  • Rental cost ≈ 5.1 × 10^7 × $0.06 ≈ $3.1M/day ≈ $128k/hour.
  • If the app settles $50M/hour in transfers, a single double-spend window is worth ~390× the hourly attack cost. Budget inadequate.
  • If it settles $50k/hour, attack cost exceeds value at risk by ~2.5×. Adequate for that window.

For reference, Bitcoin's subsidy is 3.125 BTC/block (post-April-2024 halving), ~144 blocks/day = 450 BTC/day; at $60k/BTC that is ~$27M/day of recurring budget.

Confirmation depth vs cost

DepthTime (10-min blocks)Attacker workWhen it is enough
1~10 min~1 block of majority hashLow-value, reversible actions
3~30 min~3 blocksSmall retail settlement
6~60 min~6 blocksStandard exchange deposit
100~16 h~100 blocksLarge irreversible settlement

Depth is a proxy for cost only if hash rate is high and stable. On a small chain, 6 confirmations may be minutes of rentable hash.

Trade-offs

  • Fees vs subsidy: as subsidy halves, the budget must migrate to fees or security falls. Watch the fee share of the budget.
  • Checkpointing / merged mining / PoS: each trades different trust assumptions for cheaper finality. Checkpointing centralizes; merged mining borrows another chain's budget; PoS replaces work with capital cost.
  • Confirmation depth vs latency: deeper is safer and slower; pick depth from value-at-risk, not habit.

Failure modes and detection

  • Rentable-hash attack: attacker rents, owns nothing. Detect via sudden hash-rate spikes and rental-market depth.
  • Pool collusion: two pools above 50% can coordinate. Detect via pool-share monitoring.
  • Selfish mining: withheld blocks orphan honest work. Detect via orphan rate above the expected baseline.
  • Deep reorg: confirmed deposits reversed. Detect via reorg-depth monitoring and alerting on depth > policy.

Evaluate the budget by the ratio of attack cost to value settled, not by raw hash rate.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How does Proof-of-Stake handle the nothing-at-stake problem and long-range attacks, and what role does weak subjectivity play?

Answer

In Proof-of-Work, extending multiple competing branches divides an entity's finite physical hashrate, imposing an immediate opportunity cost. In naive Proof-of-Stake, creating a signature costs negligible compute or energy. If a fork occurs, a rational or malicious validator maximizes expected yield by signing blocks on all competing tips at height $h$. Because there is no marginal computational cost to vote on every branch, this is the nothing-at-stake problem.

PoS protocols counter short-range nothing-at-stake attacks using explicit slashing conditions. Consensus rules require validators to deposit collateral (such as 32 ETH in Ethereum). A validator's cryptographic signature commits them to a specific target and height/epoch. If an observer detects two contradictory signatures for the same height or spanning target epochs (e.g., Casper FFG double voting or surround voting), that evidence is included on-chain. The protocol slashes the offender's deposit, burning a portion and ejecting them from the active validator set.

However, slashing alone cannot secure the protocol against long-range attacks. Once a validator unbonds and withdraws their stake, that capital is no longer locked on-chain. The private keys that controlled a majority of stake 12 months ago can now be used (or sold to an attacker) to sign an alternative, valid-looking history starting from an ancient block where those keys were active. Because this alternative chain is fully signed by what was a valid 2/3 supermajority at that historical block height, an offline node rejoining or bootstrapping from genesis cannot distinguish the real history from the attacker's fabricated chain purely by applying local cryptographic verification and chain-scoring rules.

Canonical Chain:  [Block 0] --- ... --- [Block N (Keys unbonded)] --- ... --- [Current Tip A]
                                      \
Long-Range Fork:                       +--- [Alternative Block N+1] --- ... --- [Attacker Tip B]
                                            (Signed by historically valid keys with zero slashed collateral)

Proof-of-Stake resolves long-range attacks by abandoning strict full subjectivity (where a node can verify canonical truth from genesis using only static protocol rules and code) in favor of weak subjectivity.

Under weak subjectivity, nodes require a trusted, recent state checkpoint (a "weak subjectivity checkpoint") that is younger than the protocol's unbonding period (the unbonding / withdrawal delay, such as Ethereum's withdrawal queue period or CometBFT's trusting period).

Parameter / MechanismShort-Range / Nothing-at-StakeLong-Range Attack
Threat WindowImmediate active slots / epochsBeyond the validator unbonding duration
Attacker CostLost bonded collateral (protocol slashing)Zero protocol penalty (keys already unbonded)
Defense MechanismDouble-vote slashing + inactivity leakWeak subjectivity checkpointing within unbonding bounds
Trust ModelPurely algorithmic / objective over gossipOut-of-band social consensus / trusted recent block hash

If a node syncs within the unbonding window, any historical double-signing violates protocol safety while the stake is still locked, guaranteeing attributable financial destruction. If a node is offline longer than the unbonding window, it must inject an out-of-band verified block hash from an honest external source (block explorers, trusted peers, social consensus) within the weak subjectivity period to safely discard malicious historical forks.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Threat-model the economics of a consensus attack.

Answer

Core answer

First I'd pin down three things: which chain and finality gadget, what the attacker already holds, and what value is settled before finality. The economics of a consensus attack are not the nominal cost of acquiring 51% of stake or hashrate: that is usually the most expensive route and the one nobody uses. The real cost floor is the minimum of three routes: acquire, rent, or bribe. Revenue is usually external: a short position, a derivatives book, or value the attacker can double-spend before the chain finalizes.

So the threat model reduces to: can the attacker make bribe cost < external payoff + value at risk before finality? If yes, deterrence fails no matter how much stake is nominally locked.

Three cost routes

routemechanismwhen it is chosen
Acquirebuy 51% of stake/hashrate on marketmoves price against you; on Ethereum ~34M ETH staked, 51% is ~17M ETH
Rentrent hashrate (NiceHash) or borrow stakeonly viable on small chains; Bitcoin's hashrate (hundreds of EH/s) is not rentable
Bribepay validators/miners directlycheapest: no asset to custody, pay only the marginal coalition

Bribery beats renting because you never hold the asset and never eat price impact, and you pay only the validators you need. The counter is the slashing correlation penalty.

Worked threshold (hypothetical, ETH at $3,000)

1M validators, 32M ETH staked. Blocking finality needs >1/3, ~10.7M ETH. The base slashing penalty is 1/32 of the 32 ETH effective balance: 1 ETH. But the correlation penalty is effective_balance × min(3 × slashed_stake, total_stake) / total_stake; at 1/3 slashed that term is 1, so each slashed validator loses its full 32 ETH. The bribe must beat that: 333k validators × 32 ETH ≈ 10.7M ETH. The same as buying the stake outright. The correlation penalty is what removes bribery's cost advantage at the threshold that matters.

Where revenue comes from

  • Reorg / double-spend: value settled before finality. Ethereum finalizes in two epochs, ~12.8 minutes; an exchange crediting deposits after 1–2 confirmations is exposed for that window.
  • Derivatives: short the token on a perp venue before the attack, or buy puts. A credible reorg or censorship event that crashes price pays the position even if the attack itself is unprofitable.
  • MEV / time-bandit: reorg to capture MEV already in past blocks. If a block's MEV exceeds the cost of reorging it, the reorg is rational.
  • Censorship: force liquidations or extract fees by excluding transactions.

Failure modes and detection

  • Correlated custodians: if Lido plus a couple of CEX staking products exceed 1/3 of stake, one subpoena, key compromise, or cloud outage can cross the finality threshold. Detection is staking-pool and client concentration, not validator count.
  • Client monoculture: a single client with >2/3 share can cause a mass slashing event from one bug. A correlated failure that looks like an attack.
  • Governance response: social slashing or a hard fork to burn the attacker's stake is the recovery value, but it takes days and only works if the community coordinates. It is a deterrent, not a guarantee.

When it pays, when it doesn't

It pays when the attacker holds no slashable stake (they bribe others), the external position is large, and settled value at risk exceeds the bribe. It doesn't pay when the correlation penalty makes the coalition convex, finality is fast enough that little value is at risk, and the token is hard to borrow for a short.

Economic deterrence supplements protocol safety. It is not evidence that every rational actor follows nominal rewards.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

How does Ethereum's Gasper combine Casper FFG and LMD GHOST to achieve safety and liveness?

Answer

What a strong candidate says first

Gasper is Ethereum's beacon-chain consensus protocol (phase0 spec, live on mainnet since the Merge in September 2022). It runs two protocols over one stream of validator messages: LMD GHOST picks the head every slot, giving liveness; Casper FFG finalizes checkpoints every epoch, giving safety. They are not sequential layers. Every attestation carries both an LMD GHOST vote and an FFG vote, and the fork choice is rooted at the latest justified checkpoint. That coupling is the design.

Time and the two votes

  • Slot = 12 s. One proposer per slot; a committee attests to the head.
  • Epoch = 32 slots = 6.4 min. Each active validator attests exactly once per epoch, in its assigned slot, with:
    1. beacon_block_root: its LMD GHOST vote for the current head.
    2. source → target checkpoints: its FFG vote.

Justification and finalization

A checkpoint B is justified when ≥ 2/3 of total active stake (not of participating stake) votes a link A→B from an already-justified A. B is finalized when its direct descendant C is justified by B→C. Two epochs, deterministic.

Worked numbers: with 1,000,000 validators at 32 ETH each, total stake is 32,000,000 ETH and the supermajority threshold is 21,333,334 ETH. Epoch 100: A justified. Epoch 101: 22.1M ETH attests A→B, so B is justified. Epoch 102: 21.8M ETH attests B→C, so C is justified and B is finalized. Reverting B now requires slashing ≥ 1/3 of stake (≥ 10.67M ETH).

LMD GHOST in one trace

Fork choice starts at the latest justified checkpoint and prunes any block not descending from it. At each fork it takes the child subtree with the greatest weight of latest messages.

Slot 3210: blocks X and Y at the same height. Latest attestations: 19M ETH on X, 13M ETH on Y → head is X. A validator that voted Y at slot 3209 attests X at slot 3211; its 32 ETH now counts for X and no longer for Y. Only the newest message per validator counts: that is the "latest message driven" part, and it is what makes the fork choice responsive rather than cumulative.

Slashing conditions

Two slashable offenses keep conflicting checkpoints from both reaching 2/3:

  • Double vote: two distinct targets at the same epoch height.
  • Surround vote: signing s1→t1 that surrounds s2→t2, i.e. h(s1) < h(s2) < h(t2) < h(t1).

If two conflicting checkpoints were both finalized, ≥ 1/3 of stake must have signed a slashable pair, so safety is economic: the attacker burns ≥ 1/3 of the stake.

Failure modes

  • Partition / < 2/3 participation: FFG cannot justify or finalize, but LMD GHOST keeps producing blocks on each side. Liveness survives, finality stalls. This is the intended split.
  • Inactivity leak: after 4 epochs without finality (MIN_EPOCHS_TO_INACTIVITY_PENALTY = 4), non-attesting validators are penalized proportionally to epochs-since-finality, so the per-epoch penalty grows linearly and cumulative loss is quadratic. Their effective balances fall until the online set is > 2/3 of remaining stake and finality resumes.
  • Known caveat: the original Gasper liveness proof (Buterin et al., 2020) was shown by Neu, Tas and Tse (2021) to have a gap. A < 1/3 adversary can delay finality with a balancing attack. Safety is unaffected.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

How do PoS consensus protocols manage the trade-off between liveness and safety during prolonged network partitions or validator inactivity?

Answer

Under the CAP/FLP implications for partial synchrony, a distributed consensus protocol cannot guarantee both safety and liveness during an arbitrary network partition. Proof-of-Stake protocols navigate this trade-off by adopting one of two architectural strategies: strict safety-priority (halting until connectivity recovers) or availability-priority with economic self-healing (continuing execution and burning inactive stake until a quorum restores).

1. Classical BFT Protocols (Safety Prioritized)

Systems derived from classical PBFT (e.g., CometBFT, Tendermint, HotStuff) prioritize safety unconditionally across any partition:

  • Quorum Requirement: Progress requires two rounds of pre-votes and pre-commits from strictly $> 2/3$ of the active bonded stake.
  • Partition Behavior: If a network partition splits the validator set into $50% / 50%$, or if $> 1/3$ of stake goes offline, neither partition can assemble the $> 2/3$ quorum. Progress halts entirely. State machine replication ceases until network synchrony is restored and nodes reconnect.
  • Trade-off: Zero risk of conflicting finalized forks (safety is mathematically guaranteed by the intersection of any two $> 2/3$ quorums sharing $> 1/3$ honest stake), but absolute loss of liveness for applications.

2. Hybrid Liveness Protocols with Inactivity Leaks (e.g., Ethereum Gasper)

Gasper decouples short-term optimistic block production (LMD GHOST) from deterministic finality (Casper FFG) to maintain partial availability during partitions while engineering an eventual return to safety:

Normal (Synchronous):   [Slot N] ---> [Slot N+1]  (Casper FFG finalizes epochs every 32 slots)

Partition (> 1/3 offline):
  LMD GHOST fork-choice: Continues appending blocks locally (Liveness preserved)
  Casper FFG:            Finality stops (Cannot reach 2/3 supermajority)
  Inactivity Leak:       Triggered after 4 unfinalized epochs (~25.6 minutes)
                         Iteratively burns offline validators' effective balances
                         until online partition controls > 2/3 of total remaining stake.

The Inactivity Leak Mechanism

If the chain fails to finalize for 4 consecutive epochs:

  1. Attestation Penalties: Validators failing to submit target attestations do not receive base rewards and incur an escalating penalty proportional to epochs_since_finality.
  2. Deflation of Inactive Stake: The offline partition's effective balance decays quadratically over time. The stake denominator shrinks until the online partition, even if originally representing only 55% of physical stake, now controls $> 66.7%$ of the remaining active validator balance.
  3. Restored Finality: The active partition regains the supermajority required by Casper FFG and resumes finalizing blocks.

Comparison of Partition Behaviors

Protocol ClassBehavior Under $> 1/3$ Validator DropoutResolution MechanismInherent Partition Risk
Strict BFT (CometBFT / HotStuff)Hard Halt: Block production freezes; no transactions processed.Manual operational recovery or network healing.Prolonged denial of service; zero risk of state divergence.
Hybrid / Dynamic (Ethereum Gasper)Progress Without Finality: LMD GHOST builds blocks; Casper FFG halts finality.Automated inactivity leak drains absent stake to force a new quorum.Catastrophic Fork: If a symmetrical partition (e.g., 50/50 split) stays partitioned through an inactivity leak, both sides leak the other and finalize divergent histories. Reconnecting requires manual social consensus.

In high-value financial settlements, strict-safety halts are often preferred over risking conflicting finalizations, whereas consumer networks may accept split-brain remediation risks to avoid global downtime.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Specify a safe consensus vote envelope.

Answer

Assumptions. A BFT chain with a validator set known per height, ed25519 signatures, and a gossip layer that can deliver two votes from the same validator. The envelope is the message a validator signs; safety means no two distinct decisions can share a valid signature.

Core answer. The envelope must carry every field that distinguishes one consensus decision from another, encoded canonically, and the signature must be durable before the vote is broadcast. Concretely: chain ID, height, round (or view), vote type, and block ID. Validator identity travels on the wire but need not be signed: verification resolves the pubkey from the validator set for that height, so a signed address is redundant and a relayer could rewrite it anyway.

Why each field. Chain ID is domain separation: without it, a precommit signed on a testnet with an overlapping validator set is a valid precommit on mainnet. Height and round are the monotonic coordinates; a vote is meaningful at exactly one (height, round), so replaying it elsewhere is rejected by the receiver's state machine. Vote type separates prevote from precommit: same coordinates, different meaning. Block ID binds the vote to a specific proposal, and two votes at the same coordinates with different block IDs are precisely the equivocation you want to make provable.

Canonical encoding. Tendermint v0.34 signs a protobuf CanonicalVote prefixed with a length-delimited chain ID:

Go
type CanonicalVote struct {
    Type      byte      // 1 = prevote, 2 = precommit
    Height    int64
    Round     int32
    BlockID   BlockID   // Hash [32]byte + PartSetHeader{Total uint32, Hash [32]byte}
    Timestamp time.Time
    ChainID   string
}
// signBytes = uvarint(len(chainID)) || chainID || protobuf(CanonicalVote)

The length prefix matters: without it, chain ID "ab" plus a vote could collide with "a" plus a vote whose first byte is b. Protobuf field order is fixed by the schema, so two encoders produce identical bytes.

Trace: equivocation. Validator V holds 10% of stake. At height 100, round 0, V signs a precommit for block A (hash 0xAA…) and a precommit for block B (hash 0xBB…). Same chain ID, type, height, round; different BlockID, so different sign bytes and two valid signatures. A node that receives both holds a duplicate-vote evidence pair. Tendermint's default slash_fraction_double_sign is 0.05, so V loses 5% of its stake and is jailed; evidence must be retained at least through the unbonding period (21 days default) or the validator can unbond before being punished.

Persist before send. Write the signed vote to the consensus WAL and fsync before broadcasting. On restart, replay the WAL, see a signature already exists at (100, 0), and refuse to sign a different block. Cost: one fsync per vote. Roughly 0.1–1 ms on NVMe, 5–20 ms on network-attached storage. At 1 s block times that is noise; at 100 ms block times it sits on the critical path, and the alternative (send then persist) buys latency by accepting a double-sign window on crash.

Failure modes and detection.

  • Missing chain ID → cross-chain replay. Detect by running the same validator key against two chains and checking whether one chain's vote verifies on the other.
  • Non-canonical encoding (map iteration order, varint vs fixed width) → two encodings of one vote, so signer and verifier disagree. Detect with differential fuzzing of encoder against decoder.
  • Persist-after-send → crash between broadcast and write, restart signs a conflicting vote. Detect by WAL replay mismatch at startup.
  • Envelope too small: dropping round lets a vote replay across rounds at the same height.

What changes the decision. A single static validator set with no light clients can drop chain ID and timestamp. A threshold-signature protocol (HotStuff-style QC) replaces n individual votes with one aggregate per view, so the per-vote envelope shrinks but the view number becomes the only replay guard.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Design safe validator signing and slashing protection.

Answer

Assuming Ethereum proof-of-stake and a validator that signs attestations and beacon blocks, the core design is: keys live in a constrained signer (HSM or remote signer like Web3Signer), every signing request is checked against a slashing protection database that enforces the consensus spec's slashing conditions, the intent to sign is persisted before the signature is released, and the signing state is never restored backward. The signer must enforce its own slashing protection; it cannot trust the validator client.

Why persist-before-sign? The crash window: if you sign, then crash before updating the database, on restart you might sign a conflicting message. By writing the intent (the exact message to be signed) to durable storage first, a crash after the write but before the signature means on restart you see an intent without a signature. You can either sign it (if it's still valid) or discard it, but you never sign a conflicting message. This is a two-phase commit: persist intent, sign, persist completion.

The slashing conditions are specific. For attestations: double vote (two attestations with the same target epoch but different data) and surround vote (one attestation's source and target epochs surround another's). For blocks: two different beacon blocks for the same slot. The database must track the minimum source epoch, maximum target epoch, and the roots of the last signed messages. EIP-3076 defines the interchange format so you can move this state between clients.

Trade-offs: a single HSM-backed signer is simpler and lower latency (sub-millisecond signing), but if it fails, the validator goes offline and misses attestations (availability penalty, not slashing). A remote signer cluster (e.g., multiple Web3Signer instances behind a load balancer) adds a network round trip (typically 1-5 ms on a local network) and operational complexity, but survives a signer node failure. For a single validator, a single HSM is often enough. For an operator with thousands of validators, the cluster is worth it because the cost of downtime across many validators outweighs the latency. The deciding criterion is: how many validators, and what is the cost of a missed attestation versus the cost of a slashing event? A slashing event costs at least 1 ETH for a 32 ETH validator plus correlation penalty and ejects the validator, so safety always wins.

Failure modes and detection:

  • Slashing protection database corruption or loss. Detection: monitor database integrity and backups. If lost, do not start the validator until you can reconstruct the last signed messages or wait out the slashing protection period. Operational cost: downtime, and you may need to use doppelganger detection.
  • Doppelganger: another instance running with the same key. Detection: doppelganger detection at startup, which checks if the validator is already active on the network. It adds a delay of 2 epochs (12.8 minutes) before signing. Operational cost: missed attestations for that period.
  • Clock skew: signer signs for the wrong slot. Detection: monitor NTP offset; if > 500 ms, alert. Operational cost: missed attestations or, worst case, a slashable message if the skew causes a slot mismatch.
  • Network partition between validator client and remote signer. Detection: monitor signing request latency and error rates. Operational cost: missed attestations (availability penalty).

Artefacts: a table of slashing conditions, and a sequence diagram of the signing flow.

MessageSlashing condition
AttestationDouble vote: same target epoch, different data
AttestationSurround vote: source/target epochs surround another
Beacon blockDouble proposal: two different blocks for same slot

Signing flow:

  1. Validator client receives duty.
  2. Checks local slashing protection DB.
  3. Sends signing request to remote signer over mTLS.
  4. Signer checks its own DB.
  5. Signer writes intent to DB.
  6. Signer signs.
  7. Signer writes completion.
  8. Returns signature.
  9. Validator client updates its DB.

If the signer crashes between 5 and 6, on restart it sees intent without completion; it can sign or discard, but never sign a conflicting message.

That's the core. I'd also mention that you should never restore signing state backward, and you should test failover by killing the signer and ensuring the validator misses attestations but does not double sign.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Design crash-safe high availability for a validator signer.

Answer

First, I'd clarify the consensus protocol and the cost of equivocation versus downtime. I'll assume a BFT protocol like Tendermint, where equivocation leads to slashing, and downtime of a few minutes is acceptable. The core requirement: never sign two different messages for the same height, round, and vote type. So the signer must have a durable, atomic anti-equivocation state machine.

My design: a single active signer with a hot standby. Before signing any message, the signer writes the consensus coordinates (height, round, step) and the message hash to a write-ahead log (WAL) on stable storage, then fsyncs. Only after the fsync returns does it release the signature. On restart, it loads the WAL and refuses to sign any message that conflicts with a recorded entry. For failover, the standby shares the same WAL via a replicated log like etcd, which provides linearizable writes and leases. The active signer holds a lease; the standby can only take over after the lease expires. This fencing prevents two active signers.

Why this works: the WAL makes the signing decision atomic with respect to crashes. If you crash after fsync but before signing, you recover and know you haven't signed yet, so you can sign the same message. If you crash after signing, the WAL entry is already there, so you won't sign a conflicting message. The replicated log ensures the standby sees the same state. The lease ensures only one instance can write to the log at a time.

Trade-offs: A cold standby with manual failover is simpler. No distributed lock, no etcd. It's fine if you can tolerate 10-30 minutes of downtime. A hot standby with shared storage (e.g., a SAN) requires a distributed lock or fencing, which adds complexity. A replicated log like etcd adds a dependency on an etcd cluster, but gives automatic failover and strong consistency. For Ethereum 2.0, Web3Signer uses a slashing protection database that records the last signed slot and block root; it can be backed by PostgreSQL or a local file. That's a concrete example.

Failure modes: Disk corruption. Use checksums and backups. Network partition: the lease expiry and fencing token prevent split-brain. Clock skew: use consensus coordinates, not wall clock. Stale instance: the fencing token is checked on every write. Disk snapshots: never restore an older WAL; use a monotonic counter and reject any state that goes backward. The WAL entries should be authenticated (e.g., signed) to prevent tampering.

Worked trace:

  1. Signer receives vote V1 for (height=100, round=0, type=prevote).
  2. It writes WAL entry: (100,0,prevote, hash(V1)) and fsyncs.
  3. It signs V1 and sends it.
  4. Crash.
  5. Restart, load WAL. See entry for (100,0,prevote, hash(V1)).
  6. Receive vote V2 for (100,0,prevote) with different hash. Refuse to sign.
  7. Receive V1 again. Can return cached signature or re-sign.

This trace shows the state machine survives a crash at the critical boundary.

Table comparing designs:

DesignFailover timeComplexityDouble-sign riskWhen to use
Cold standbyManual, 10-30 minLowLow if manual process is strictDowntime acceptable
Hot standby + shared storageSecondsMediumMedium (needs fencing)Need fast failover, can afford SAN
Replicated log (etcd)SecondsHighLow (linearizable, leases)Need automatic failover, can run etcd

In summary, the key is to persist before signing, use a single authoritative state machine, and fence stale instances. The simplest design that meets your availability requirement is usually best.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design safe validator-set reconfiguration.

Answer

Assumptions first: partially synchronous network, authenticated links, under 1/3 of stake Byzantine, finality is a commit certificate carrying more than 2/3 of the voting power of the set active at that height, and validator keys are bonded so a leaving validator stays slashable through an unbonding window.

The rule I would defend: the validator set is consensus state, never local configuration. Block H's header commits to ValidatorsHash(H), the set that had to sign H, and NextValidatorsHash(H+1), the set that must sign H+1. The change is authenticated by the set it replaces. Two nodes replaying block H derive the same next set; if they disagree, their block hashes diverge at H+1 and the fork surfaces at the first post-change height, not at the next epoch boundary. Nothing on the path depends on an operator restarting a node with a different config file or agreeing on a cut-over time.

// runs deterministically on every node once block H commits
onCommit(H):
    updates = staking.powerUpdates()   // part of committed state, not a memo field
    next    = apply(state.set, updates)  // pure function of committed state
    state.nextSet = next
// block H header: ValidatorsHash      = hash(state.set)
//                 NextValidatorsHash  = hash(state.nextSet)
// commit at H+1 verifies against NextValidatorsHash taken from H

Because the H+1 certificate is only valid against the set that H's commit authenticated, the quorum chain is linked through signed state; it does not need the old and new sets to overlap by themselves. That is the safety argument, and it is what most broken implementations skip.

Churn larger than 1/3 is where it breaks. Take a five-member set and remove two members at once. A majority of the old set is any three members; a majority of the new three-member set is any two. Old quorum {C,D,E} and new quorum {A,B} share nobody, and both are legitimate majorities. If the change is applied by configuration rather than by signed state, two valid-looking histories exist with no shared validator.

Repair, when the change cannot live inside signed state: joint consensus. Commit C_old,new first, where every decision needs a majority of the old and a majority of the new; any two C_old,new commits intersect, because both must contain a majority of the new set and two majorities of one set must overlap. Then commit C_new, and any C_new commit intersects any C_old,new commit for the same reason. Order is load-bearing: once C_old,new commits a leader may not fall back to C_old, and no decision in C_new may be taken before the C_new entry itself commits. Raft (section 6) allows a single-server change without this machinery precisely because a one-member difference can never yield disjoint majorities; removing two at once is why the joint step exists.

Votes, keys, activation:

  • A vote is meaningful only against the set for its height: the commit at H verifies against ValidatorsHash(H). Do not let one signature be valid in two sets, or the height (hence the set) must be part of the rule that verifies it.
  • Key rotation needs proof of possession: the new key signs over the rotation, the old key authorises it, and the change lives in state so a gossip message cannot forge it.
  • Removal needs a delay. An unbonding window (21 days on the Cosmos Hub) keeps a departed validator slashable, and IBC clients are conventionally given a trusting period below it, commonly two-thirds of it (14 days against that 21-day window).

Light clients. Ethereum rotates a 512-validator sync committee every 256 epochs, about 27.3 hours, and a client offline longer must re-anchor at a weak-subjectivity checkpoint; finality there is 2 epochs, 12.8 minutes. If your reconfiguration cadence is faster than the light client's refresh period, it has nothing it can verify. Choose the two numbers together.

FailureHow it shows up
Set applied from local config, not stateNextValidatorsHash mismatch at the same height between two nodes, then a block-hash fork at H+1
More than 1/3 churn without a joint quorumTwo commit certificates at one height whose signer sets do not intersect. It is a transition bug, and no single validator can be slashed for it because each signed once
Key removed while still signingSignature verifies against the old set, not the new one; attribution needs the height and set version
Light client syncing past its trust periodCompare against a checkpoint; a past coalition holding more than 2/3 can serve a forged chain to anyone who arrives late

Emergency. If more than 1/3 of stake is compromised, no in-protocol rule helps: that coalition can finalise any transition, including one that hands it the set. The remedy is out of band, halt, agree on a checkpoint, distribute a new config, require evidence before re-admission. Every light client re-anchors, which is why the trust period is a recovery budget rather than a tuning knob.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Bootstrap and update a proof-of-stake light client safely.

Answer

A proof-of-stake light client can't replay the chain from genesis: it has no validator set and no way to check signatures from the start. So it bootstraps from a finalized checkpoint it trusts, then follows sync committee signatures from there. Two things decide whether it is safe: the bootstrap must be a genuine finalized block, and the trust anchor must be replaced before the weak subjectivity period runs out.

Bootstrap. Fetch a LightClientBootstrap for a recent finalized block from a source you trust: your own consensus node, or a checkpoint-sync provider. It carries the block header, the current_sync_committee, and a Merkle branch. Verify:

  1. hash_tree_root(header) == trusted_block_root: the header is the checkpoint you chose.
  2. is_valid_merkle_branch(hash_tree_root(current_sync_committee), current_sync_committee_branch, floorlog2(CURRENT_SYNC_COMMITTEE_GINDEX), get_subtree_index(CURRENT_SYNC_COMMITTEE_GINDEX), header.state_root): the committee really is in that block's state.

Note what is not checked: the client cannot verify the checkpoint's signature, because it has no validator set yet. The checkpoint is the trust assumption; that is why it must be recent.

Update. A LightClientUpdate carries attested_header, sync_aggregate (512-bit participation bitmap plus a BLS aggregate signature), signature_slot, next_sync_committee with its branch, and optionally finalized_header with a finality_branch. The spec's validate_light_client_update requires:

  • participation ≥ MIN_SYNC_COMMITTEE_PARTICIPANTS (1);
  • the update's sync committee period is the store's period or the next one: no skipping;
  • attested_header.slot > store.finalized_header.slot: rollback protection;
  • the aggregate signature verifies against the store's current sync committee, with the domain derived from attested_header's fork version and the genesis validators root;
  • if finalized_header is present, finality_branch proves it against attested_header.state_root, and its slot beats the store's finalized slot;
  • next_sync_committee is proven against attested_header.state_root; when the period rolls over, the store adopts it.

The store keeps the best update seen (highest finalized slot, then most participation) and only advances the finalized header on a strictly better one.

Refresh. Before the weak subjectivity period elapses, fetch a fresh checkpoint and re-bootstrap. Cross-check independent sources; on disagreement, halt.

Why weak subjectivity. A client offline longer than the period cannot distinguish the real chain from a long-range attack rebuilt from old validator keys. The period bounds how long a checkpoint is safe to trust.

Arithmetic. Sync committee period = 256 epochs × 6.4 min = 27.3 h; committee = 512 validators. Churn limit = max(4, N // 65536) validators per epoch (Electra replaced this with a balance-based limit, get_balance_churn_limit); at 1M active validators that is 15 per epoch, so 1/3 of the set turns over in (1,000,000 / 3) / 15 ≈ 22,222 epochs ≈ 99 days. The spec's compute_weak_subjectivity_period(state) is the authoritative value: read it from the state, don't hardcode it.

Failure modes.

  • Long-range attack: a valid-looking chain from an old checkpoint. Detect by rejecting checkpoints older than the weak subjectivity period and cross-checking sources.
  • Expired anchor: the client keeps using a stale checkpoint. Monitor checkpoint age; refresh before expiry.
  • Sync committee compromise: ≥2/3 of a committee signs a false update. Detect by cross-checking another client or a full node; for high-value use, run a full node.
  • Rollback: an old update replayed. Rejected by the attested_header.slot > finalized slot check.
  • No updates: the client cannot reach a full node. Use multiple endpoints.

Trade-off. A public checkpoint provider is convenient but adds a trust assumption; your own consensus node removes it at the cost of running one. Refresh more often than the protocol maximum if the value at stake justifies it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How do you test and verify safety invariants in a distributed consensus implementation using deterministic simulation and formal verification?

Answer

Clarify and scope. I'll assume a crash-fault model (no Byzantine), a Raft- or Paxos-style replicated log, and the invariants that actually matter: state-machine safety (no two servers commit different entries at the same index), log matching (same index and term implies identical prefix), and validity (committed entries were proposed by some client). Liveness is a separate problem: DST is a safety harness, and liveness needs fairness assumptions in the spec.

The answer is two layers plus a bridge: model-check the abstract protocol, deterministically simulate the production binary, and tie them together with trace validation. Neither layer alone is sufficient.

Layer 1: model checking the protocol. Write the consensus core as a TLA+ state machine: variables currentTerm, votedFor, log (a function from index to entry), commitIndex. Actions RequestVote, AppendEntries, Timeout transition them. Then assert the invariants as state predicates. The one that matters most:

TLA
StateMachineSafety ==
    \A i, j \in Server :
        \A ix \in (1 .. commitIndex[i]) \cap (1 .. commitIndex[j]) :
            log[i][ix] = log[j][ix]

TLC explores every interleaving within the constants you fix:

CONSTANT Server    = {s1, s2, s3}
CONSTANT Value     = {v1, v2}
CONSTANT MaxTerm   = 3
CONSTANT MaxLogLen = 3
INVARIANT StateMachineSafety

Illustrative: those bounds give roughly 10^6–10^7 reachable states and TLC finishes in under a minute on a laptop; going to 5 servers pushes it past 10^9 and you switch to Apalache's SMT-backed symbolic checking or symmetry reduction. When it fails, TLC prints the minimal counterexample trace: e.g. a leader-lease bug where A (term 3, partitioned) and B (term 4) both commit index 7 with different entries. That trace is the bug report.

What this layer cannot see: the spec is not the binary. Storage races, torn writes, and thread-synchronization bugs live only in the implementation.

Layer 2: deterministic simulation of the implementation. Compile the production code against a deterministic runtime: a single-threaded event loop, a seeded PRNG, and virtual implementations of every source of nondeterminism.

SourceVirtual replacement
wall clock, timersvirtual clock advanced by the event loop
networkvirtual net: reorder, delay, drop, duplicate, partition
diskvirtual disk: partial fsync, torn writes, crash-restart
faultsseeded injection points (FoundationDB's BUGGIFY)

FoundationDB's simulator is the reference design; TigerBeetle's VOPR and madsim/turmoil in Rust are the same idea. The invariant watcher runs after every event: compare committed prefixes across all live nodes, and check that any two nodes at the same commit index produce the same state root. A linearizability checker (Porcupine, Elle) validates the client-visible history.

The payoff is reproducibility: a failing seed replays the exact interleaving. The cost is that you only cover the schedules you sample, and one unabstracted time.Now() or rand.Read silently breaks determinism. Detect that by running the same seed twice and diffing the event log.

The bridge. Trace validation replays a DST event log against the TLA+ spec to confirm the implementation refines the model. Without it you can have a verified spec and a buggy binary, or a passing simulator and a spec that never modelled the case you hit.

When not to. If you build on etcd/raft or CometBFT, don't re-prove Raft; DST your state machine and linearizability-check the client history. Reach for the full stack when the consensus core is yours and a safety violation is unrecoverable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do you verify that a consensus implementation refines its specification, and that liveness, not just safety, holds under partial synchrony?

Answer

Refinement means every behaviour the implementation can produce is a behaviour the spec allows, under a refinement mapping from implementation state to spec state. Safety is an invariant; liveness is temporal, so deterministic simulation can falsify it but never establish it. I'd verify in three layers, and state up front: the spec is the TLA+ or pseudocode model, the implementation is the artifact under test, and partial synchrony means a GST exists but its arrival time is unknown.

Layer 1: model-check liveness with fairness. Write the property as a temporal formula and let TLC search for a violating behaviour. Fairness and GST encoding are what make or break it:

tla VARIABLES gst, height, round, lockedRound, lockedValue, msgs

GST == gst' \in BOOLEAN /\ (gst => gst') * once true, stays true

Fairness == /\ \A v \in Values: WF_vars(Propose(v)) /\ WF_vars(Timeout) /\ SF_vars(Commit)

Spec == Init /\ [][Next]_vars /\ Fairness

* After GST, every proposed value is eventually decided. Liveness == Spec => (gst ~> \A v \in Values: decided[v])

TLC needs a finite state space. With 4 validators, 2 heights and 3 values it finishes in minutes; with 7 validators and message loss it does not finish: symmetry sets and a VIEW that collapses message buffers are what keep it tractable. Those figures are illustrative, not a benchmark.

propertyformchecked bytypical false positive
no two commits at one height`[](\A h:commits[h]<= 1)`
eventual decision after GSTgst ~> <>decidedTLC with WF/SFmissing fairness → stuttering counterexample
no infinite view changes[](round advances => <>height advances)TLC, or liveness monitor on tracestight timeout in impl, not spec
refinementImpl => Spec under mappingtrace validationincomplete refinement mapping

Layer 2: trace validation. Nodes emit structured logs: {node, height, round, step, msg, ts}. A trace spec consumes the log as a sequence of TraceEvent actions, with TraceNext allowing only the logged action, and you check TraceSpec => Spec. A violation means the implementation took a step the spec forbids: a commit at height h without a quorum certificate, or two votes in one round. The check is only meaningful if it can fail: mutate a log to inject a double vote and confirm the checker rejects it. A trace spec permissive enough to accept anything passes vacuously.

Layer 3: differential and fuzz testing against a reference model. Implement the spec's Next relation as an executable oracle, hand-written or extracted, then drive both it and the implementation with the same deterministic scheduler so failures replay. Fuzz partitions, clock skew, duplicate/reordered/dropped messages, crash-restart and equivocating votes; compare committed sequences. Divergence is either an implementation bug or a spec gap: both are findings. Measure distinct interleavings covered, not wall-clock hours.

Failure modes I'd name: a liveness counterexample that is really a fairness bug in the model (re-run with fairness and inspect the stuttering suffix); a liveness proof that silently assumes GST arrives within N rounds (state the bound and argue GST separately); and a differential harness that only explores schedulers the fuzzer happens to generate. If the protocol is a thin wrapper over a well-specified library, a liveness monitor plus deterministic simulation is enough; full TLA+ liveness is not free.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Make a consensus application deterministic.

Answer

Core answer (first 90 seconds).

Determinism means: given the same block of transactions and the same starting state, every replica computes the same state root. You get there by making execution a closed function of (state, block, code version): no input that varies between machines, and no operation whose result depends on the machine.

Three things break that, and they are what an interviewer will probe:

  1. Iteration order. Go's map randomizes iteration order per run; Rust's HashMap seeds RandomState per process. Sum balances by ranging over a map and two replicas get different totals. Fix: iterate sorted keys, or use BTreeMap / an ordered slice.

  2. Floating point. IEEE 754 addition is not associative: (0.1 + 0.2) + 0.3 = 0.6000000000000001, but 0.1 + (0.2 + 0.3) = 0.6. Compilers may contract a*b+c into an FMA, 32-bit x87 keeps 80-bit intermediates, and sin/exp come from libm, which differs between glibc versions. Fix: no floats in consensus-critical code; use fixed-point integers with an explicit scale. Cosmos SDK's LegacyDec is a 256-bit integer with 18 decimal places.

  3. Ambient inputs. time.Now(), crypto/rand, os.Getenv, HTTP, DNS. Fix: block time comes from the proposer and is validated within a drift bound (Tendermint BFT time is the median of validator precommit timestamps, monotonic and bounded); randomness comes from a consensus-governed seed (commit-reveal, or a VRF over the previous block hash); oracle data enters as a transaction.

Then versioning: even a correct binary diverges from an older one. Put an app version in the block header and upgrade at an explicit height, so every replica switches at the same block.

SourceFixDetected by
Map/HashMap iterationSorted keys, BTreeMapApp-hash mismatch, often only with >1 key
Float arithmetic, libmFixed-point integers, pinned scaleDivergence on a rounding boundary
Wall clock, crypto/randProposer time + drift bound; consensus seedReplay from genesis
HTTP/DNS in executionOracle data as a transactionNon-reproducible block
Binary version skewApp version in header, upgrade at heightHalt at the upgrade height

Trade-offs.

  • Ban floats vs software-emulate them. Banning floats is fast and simple, but forces you to rewrite AMM curves, interest math and reward splits in fixed point, where rounding direction becomes a consensus rule you must specify. Emulating IEEE 754 (softfloat) keeps bit-exact float semantics but runs 10–100× slower and still needs a pinned libm for transcendentals. Most chains ban floats.
  • Snapshot-and-migrate vs dual-run replay. Snapshot-and-migrate restores state at height H and runs the new binary from there: fast, but it only proves the new binary is self-consistent, not that it matches the old one at H. Dual-run replay runs both binaries over the full history and compares the app hash at every height: slower, but it localizes divergence to the exact block.

Failure modes and detection.

The signal is a state-commitment mismatch: Cosmos puts the app hash in the block header, Ethereum puts the state root there. Two replicas disagree, the chain halts at that height. Operationally: find the divergent block, replay from the last snapshot, patch, coordinate a restart. Hours of downtime, and if the divergence sits in a light client's verification path it can fork the network.

The subtle ones: a map iteration that only diverges once the map has more than one key; a float that only diverges on a value hitting a rounding boundary; a libm bump in a base image that changes exp in the last bit. None of these show up in unit tests on one machine.

What would change the decision. If the workload is dominated by transcendental math (a pricing oracle, say) fixed-point emulation of exp/ln with a pinned polynomial is the alternative to banning floats outright: you keep determinism and pay in precision.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design transaction status for a consensus-backed product.

Answer

First 60–120 seconds

Clarify three things before designing anything: which chain, how much value is at risk per transaction, and whether we hold the sender key. Assume an EVM chain: Ethereum mainnet post-Merge, 12-second slots, finality at roughly two epochs (~12.8 minutes): that we hold the key, and that the product moves money.

The answer is that status is two independent axes, not one ladder. Propagation is whether nodes have seen the transaction. Consensus is whether it sits in a block that cannot be reverted. Collapsing them is the bug: "broadcast" tells you nothing about whether the transaction will ever execute.

So the states are: created → signed → broadcast → seen (accepted by at least one mempool) → included (in a canonical block, depth 0) → safe (its block is an ancestor of a justified checkpoint) → finalized. Terminal states are dropped, replaced, reorged-out, and reverted. "Confirmed" is not a state at all: it is a depth threshold you choose per value.

Mechanism

A receipt is keyed to (blockHash, txIndex). When that block is orphaned the receipt stops existing on the canonical chain, so a stored receipt is not evidence: you must re-query by transaction hash and compare the returned blockHash against the canonical block at that height. That is why reorgs invalidate receipts rather than merely delaying them.

Nonce gaps are the second mechanism. A transaction with nonce 8 broadcast while nonce 7 is unconfirmed sits in the pool's queue, not its pending set. If 7 is replaced by 7′ with a higher fee, 8 still executes after 7′. If 7 is dropped, 8 never executes and its status stays "broadcast" forever.

stateevidencecan revert?
broadcast≥1 peer acceptedyes, may never land
seeneth_getTransactionByHash non-null on 2 providersyes
includedreceipt with blockHash, status 1yes, on reorg
safeblock is ancestor of justified checkpointrarely
finalizedancestor of finalized checkpointno, without slashing

Depth arithmetic: 12 s × 64 slots (two epochs) ≈ 12.8 min to finality. Exchanges conventionally wait 12–64 confirmations. For a $10k transfer, waiting for finalized is cheap; for a $5 payment, one confirmation is the right call. That is the trade-off: depth buys reorg safety and costs latency, and the deciding criterion is value at risk.

Failure modes and detection

  • Eviction: the pool is full and the cheapest transactions are dropped (geth's default global slot count is 5120). Detect by getTransactionByHash returning null while the nonce is still unmined after k blocks; rebroadcast the same nonce.
  • Replacement: same nonce, new hash, typically a ~10% fee bump (geth's default). Track every hash per nonce: only one can land.
  • Censorship: a valid transaction with no inclusion across many slots. Detect via an inclusion-latency SLO breach; resubmit through a private relay.
  • Reorg: stored blockHash no longer matches the canonical block. Detect by comparing against eth_getBlockByNumber.
  • Receipt failure: status 0 means revert. Read the status; do not retry blindly.

Query at least two independent RPC providers and freeze state on disagreement. Reconcile only from finalized state, and never trigger irreversible work from a single mempool sighting.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Choose a consensus architecture for a new product.

Answer

Assumptions. New product: a settlement ledger for a consortium of 7 member firms, each a separate legal entity, none willing to let another hold the only pen. Peak 200 writes/s, sub-second finality wanted, records must be provably unaltered for 7 years, transaction contents are commercially sensitive, members can leave and new ones join.

Answer: permissioned BFT, 7 validators, one per member. With n=7 the Byzantine bound is f = ⌊(n−1)/3⌋ = 2, so quorum is 2f+1 = 5 signatures. That is the whole point of the choice: safety holds with 2 members actively lying, liveness holds with 2 members down. CometBFT is the boring engine here: its default timeout_commit is 1s, so finality is one block, roughly 1–2s end to end across a WAN, and a few thousand small transactions per second. Each validator runs comfortably on 4 vCPU / 16 GB.

Why not the alternatives:

OptionFaults tolerated (n=7)FinalityWho can rewrite historyFits?
Postgres primary + hash-chained audit table0 (crash failover only)~5 ms commitThe operator, silentlyNo: one member owns the pen
Raft (etcd defaults: 100 ms heartbeat, 1000 ms election)3 crash, 0 Byzantine~10–50 msAny single compromised nodeNo. One bribed node rewrites the log
Signed audit log, no consensus0no agreement at allWhoever holds the signing keyOnly as a complement
Permissioned BFT (CometBFT)2 Byzantine, 2 down1 block, ~1–2 sNeeds 5 of 7 to colludeYes
Permissionless chain1/3 of stake~12.8 min (2 epochs × 6.4 min)1/3 of stakeNo: public data, gas, latency

Failure modes.

  1. Equivocation. A validator signs two different blocks at the same height. Detected when a later block carries both signatures as evidence; the node is slashed and ejected. Cost: the fork is real until evidence lands, so the unbonding window must exceed your incident-response time.
  2. Liveness stall. 3 of 7 validators unreachable means no quorum and the height stops. Detected by height stagnation beyond 2× block time: alert on consensus_height not advancing. Cost: writes queue in the mempool, nothing is lost, but the product is down.
  3. Partition. A 4/3 split lets the 4-side keep finalizing while the 3-side stalls. Detected by peer-count drop and height divergence in your own monitoring. Cost: any client that read from the minority side saw uncommitted state. Never serve reads from a node outside the current quorum.
  4. Censorship. 5 colluding validators can exclude one member's transactions indefinitely while still finalizing. Detected by mempool age for that member's txs. The fix is governance, not code: eject and replace the validators.

Trace of the partition.

t=0     all 7 at height 100, quorum 5 signing
t=1s    network splits 4 / 3
t=2s    side A (4 nodes) commits 101, 102, 103 ...
        side B (3 nodes) proposes, never reaches 5, height stays 100
t=30s   partition heals
        side B sees A's 101-103, discards its own uncommitted proposals
        all 7 at height 103

When to pick differently. If one member is contractually accountable and the rest can verify against an independent notary, a Postgres primary plus a hash-chained audit table plus periodic notarization is an order of magnitude cheaper and far faster. Go permissionless only if open participation matters more than privacy and you can live with ~13-minute finality.

Curated: · Written: · Reviewed:

Difficulty: Hard