Skip to content
Tech Interview Prep
Technical interview guide

Cryptographic Primitives for Blockchain

The hashing, digital signature, and Merkle tree building blocks every blockchain is constructed from.

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

Scope: NIST FIPS 180-4 (revision planned), FIPS 186-5 with published errata status reviewed 2026-09-04, SP 800-57 Part 1 Rev. 5, SP 800-186, RFC 6979, Bitcoin and Ethereum protocol documentation reviewed 2026-09-04.

Interview Q&A

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

Curated: · Written: · Reviewed:

25 questions

Q&A-2

Contrast preimage, second-preimage, and collision resistance.

Answer

The 90-second answer

Three properties, three different attacker goals against the same function:

  • Preimage resistance: given a digest h, find any message m with H(m) = h. Generic cost ~2^n.
  • Second-preimage resistance: given a specific message m1, find m2 ≠ m1 with H(m2) = H(m1). Generic cost ~2^n for a fixed target.
  • Collision resistance: find any two distinct messages with equal digests. Generic cost ~2^(n/2), by the birthday bound.

Collision resistance implies second-preimage resistance (a second preimage is a collision), but not the reverse, and neither implies preimage resistance. Collision resistance is the strongest property and the first to fall as n shrinks.

propertyattacker starts withattacker wantsgeneric cost, n-bit digest
preimagea digestany message with that digest~2^n
second preimagea digest + one messagea different message with that digest~2^n (fixed target)
collisionnothingany two messages, same digest~2^(n/2)

Birthday arithmetic: 50% collision probability at k ≈ 1.177·2^(n/2). SHA-1 (n=160) → 2^80. SHA-256 → 2^128. Preimage hits 50% at ~0.69·2^n.

Which property your protocol actually needs

  • Password storage: preimage resistance is the property; collisions are irrelevant. Use Argon2/bcrypt/scrypt for cost, not a bare SHA-256.
  • Digital signatures: collision resistance, because the signature covers the digest, not the message. A collision lets an attacker get a signature on a benign document and transplant it onto a hostile one.
  • MACs: preimage/second-preimage. HMAC-SHA-256 is fine even though SHA-256 is Merkle–Damgård.
  • Content addressing (git, IPFS): collision resistance, because the digest is the identity.

Failure modes in practice

  1. MD5 (128-bit). Collisions published in 2004 (Wang et al.); chosen-prefix collisions in 2009 (Stevens et al.), which produced the rogue CA certificate using a cluster of a couple hundred PlayStation 3s. A plain MD5 collision is now a laptop-scale computation. Anything still verifying MD5 signatures is broken, not weak.

  2. SHA-1 (160-bit). Birthday bound is 2^80. SHAttered (2017) produced two colliding PDFs for ~2^63.1 SHA-1 compressions: roughly 6,500 CPU-years plus 100 GPU-years. Leurent and Peyrin (2020) then built a chosen-prefix SHA-1 collision (~2^63.4 compression calls) and used it to forge a PGP key signature. Chosen-prefix is the variant that matters: the attacker controls both messages, so "sign this innocuous file" becomes "sign this malware."

  3. Second preimage is cheaper than 2^n on long messages. Kelsey and Schneier (2005): for a Merkle–Damgård hash and a message of 2^k blocks, a second preimage costs about 2^(n−k). A 1 GB message is 2^24 blocks, so SHA-256 second-preimage on it is ~2^232, not 2^256. Still infeasible, but it shows why "second preimage = 2^n" is a short-message statement. Collision resistance is unaffected.

  4. Length extension. MD5, SHA-1 and SHA-256 are Merkle–Damgård, so H(secret ‖ message) is forgeable without knowing the secret. Not a collision, but it is the failure people actually hit when they hand-roll a MAC. Use HMAC, or SHA-3 / SHA-512/256, which are not vulnerable.

Detection and migration cost

You cannot detect a collision by looking at a digest: two colliding files look like two random 256-bit strings. Detection is inventory and policy: know which algorithms appear in your certificates, signatures and content addresses, and track the deprecation calendar. NIST disallowed SHA-1 for digital signature generation in 2013 (SP 800-131A); browsers stopped accepting SHA-1 certificates in 2017.

The real bill is migration. Git adopted SHA-1 collision detection (sha1dc) in 2017 and has supported SHA-256 repositories since 2.29, but the default is still SHA-1 because every object ID, packfile and third-party tool assumes 20 bytes. Certificate chains, HSMs, firmware signing keys and long-lived signed documents all have to be re-issued. Budget the migration when you pick the algorithm, not when the collision lands.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Explain what a block hash proves and what it does not prove.

Answer

What a strong candidate says first

A block hash is a commitment to a fixed sequence of bytes. Recomputing it over those bytes and getting the same 32-byte digest proves the bytes are unaltered relative to whatever trusted copy of the digest you started from. In a proof-of-work chain it also proves work was spent: the digest is below the target encoded in the header. That is the whole claim. It says nothing about whether the transactions inside are valid, whether the block is on the chain everyone else follows, whether the data is retrievable, or who produced it.

Mechanism

In Bitcoin the block hash is SHA-256 applied twice (SHA-256d) to the 80-byte header:

fieldbytes
version4
prev_block32
merkle_root32
timestamp4
nBits (target)4
nonce4

The Merkle root is what binds the transactions. Each txid is SHA-256d of the serialized transaction; the root is SHA-256d over pairs of txids up the tree. Flip one byte in one transaction and its txid changes, which changes every node on the path to the root, which changes the header, which changes the block hash, and the proof of work no longer satisfies the target, so the block has to be re-mined. That cascade is the integrity guarantee.

Python
import hashlib

def sha256d(b: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(b).digest()).digest()

header = bytes(80)           # 80 zero bytes, one per header field
print(len(sha256d(header)))  # 32
print(sha256d(header).hex()) # 64 hex chars

Trace: the inner sha256 consumes the 80 bytes and returns 32; the outer sha256 consumes those 32 and returns 32. The printed digest is 64 hex characters. Change any one of the 80 input bytes and roughly half the output bits flip: that avalanche is why a single-byte edit is detectable.

What it does not prove, and how you find out

  • Validity. The hash covers bytes, not semantics. A block whose transactions have bad signatures or double-spend inputs still hashes correctly. Detection is consensus validation: script execution and UTXO checks. A light client that only checks headers inherits this gap.
  • Canonicality. Two valid blocks at the same height both hash correctly. The chain is chosen by cumulative work, not by any single hash. You detect a competing chain by seeing a header chain with greater total work.
  • Finality. A reorg of depth d requires an attacker to outpace honest hashrate. Nakamoto's table gives about 0.024% success for an attacker with 10% of hashrate at 6 confirmations; that is why 6 is the convention, not a rule. The cost is that a reorg invalidates every confirmation you counted, which is why exchanges wait.
  • Availability. The hash commits to bytes you may not have. A node that cannot fetch the block body cannot verify a transaction; a light client needs the Merkle path from a peer, and a lying peer is caught only because the path must hash to the root in the header.
  • Confidentiality and identity. Everything is public, and the hash authenticates bytes, not a person. Use a signature (ECDSA over secp256k1, or Ed25519) when you need to bind a key.

When a block hash is the wrong tool

If you need to hide the committed value, use a salted commitment (hash of value concatenated with a nonce): a bare block hash is not hiding. If you need to prove a computation ran correctly, use a zk or fraud proof; a hash only proves the input bytes. If you need availability guarantees, use erasure coding or data-availability sampling.

Arithmetic worth knowing

A block with 2,000 transactions has a Merkle tree of depth ceil(log2 2000) = 11, so a proof is 11 x 32 = 352 bytes against a block body on the order of 1 MB: about a 3,000x reduction, which is why light clients work. A header chain of 900,000 blocks is 900,000 x 80 = 72 MB, small enough to sync on a phone.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

Compare membership and non-membership proofs.

Answer

Assume a Merkle-based authenticated structure (a Merkle tree, a Merkle Patricia Trie, or a sparse Merkle tree) and a trusted root hash. Both proof types are checked the same way: recompute the root from the supplied nodes and compare. What differs is what the proof must contain.

Membership. Supply the leaf holding the key's value plus the sibling hashes on the path to the root. The verifier hashes upward and compares to the trusted root. Cost is one hash per level: 256 hashes (8 KB) in a depth-256 sparse Merkle tree, ~20 hashes (640 B) in a balanced tree with 1M leaves, ~5 nodes in an Ethereum MPT with 1M keys.

Non-membership. You cannot prove absence by withholding a proof: a missing response is indistinguishable from a censored one. The structure must encode absence. Three common encodings:

  • Sparse Merkle tree. Fixed depth (256 bits); every position holds either a value or a canonical empty hash. Non-membership is the path to the key's position, showing the leaf there is the empty hash. Same size as membership: 256 siblings, 8 KB.
  • Ordered Merkle tree. Keys sorted. Non-membership is two adjacent leaves L_i < key < L_{i+1}, each with an inclusion proof, plus evidence the two are adjacent. About 2× a membership proof.
  • Merkle Patricia Trie. Non-membership is the path to where the key diverges from existing keys; the terminal node has no child for the key's next nibble. Same node count as membership.
ConstructionProof size (1M leaves)Verify costStructural requirement
Sparse Merkle tree256 × 32 B = 8 KB256 hashes ≈ 250 µsFixed depth 256, canonical empty hash
Ordered Merkle tree2 × 20 × 32 B ≈ 1.3 KB40 hashes ≈ 40 µsSorted keys, adjacency provable
MPT~5 nodes, ~1–2 KB5 keccak256 ≈ 5 µs16-ary trie, RLP nodes

(≈1 µs per 32-byte hash on a modern x86 core.) Note the MPT row: the proof carries full RLP node encodings, not just hashes, so its byte size is larger than the node count suggests.

Failure modes.

  • Ordered tree, adjacency unchecked. If the verifier only checks L_i < key < L_{i+1} and not that the two leaves are adjacent in the tree, a prover can pick two far-apart leaves and "prove" non-membership for a key that is present. Detection: require leaf indices and check they are consecutive, or use an append-only tree with a consistency proof.
  • SMT, non-canonical empty. If the tree admits more than one representation of "empty", the verifier cannot tell an empty leaf from a value that happens to equal the empty hash. Detection: fix one default empty hash and reject any leaf that is not exactly it.
  • MPT, terminal node unchecked. If the prover stops at a branch node that does have a child for the next nibble, the verifier must check that the nibble is absent; otherwise it accepts a false non-membership.
  • Wrong root or key derivation. Ethereum's state and storage tries use the same MPT node encoding, so a proof is only meaningful against the right root and the right key (keccak of the address vs. keccak of the slot). The verifier must be told which, and must check the root against a trusted source such as a block header.

Toy trace. Depth-2 SMT, 4 leaves, keys 00/01/10/11, values V00=10, V11=20, others empty (E=0). H(a,b) = (31a + 17b + 7) mod 100.

  • Node0 = H(10,0) = 17; Node1 = H(0,20) = 47; Root = H(17,47) = 33.
  • Membership for 00: leaf 10, siblings [0, 47]. Node0' = H(10,0) = 17; Root' = H(17,47) = 33. ✓
  • Non-membership for 01: leaf 0, siblings [10, 47]. Node0' = H(10,0) = 17; Root' = H(17,47) = 33. ✓

Both recompute the same root; the only difference is that the membership proof's subject leaf is non-empty and the non-membership proof's is the canonical empty value. The verifier must know E=0 is the default.

Choosing. Need compact non-membership and can keep keys sorted → ordered Merkle tree, ~2× membership size. Want simplicity and can afford 8 KB → sparse Merkle tree, non-membership costs the same as membership. Already in Ethereum → MPT, non-membership ≈ membership size. In every case, non-membership needs an authenticated representation of absence, never a missing response.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Verify a Merkle membership proof defensively.

Answer

Core answer

Pin down three things before writing any verification code, because the code depends on all of them: the tree construction (hash function, leaf-vs-node domain separation, whether pairs are sorted or index-ordered), the tree size, and where the root came from. If the root came from the same service that handed you the proof, you have verified nothing: that service can fabricate both. Bind the root to a block header you validated yourself, or to a finalized checkpoint.

Then, in order: canonicalize the leaf exactly as the tree builder did; check the index is in range and the proof length matches the tree height; walk the proof consuming one orientation bit per level; compare the recomputed root to the trusted root.

Code: RFC 6962 style, SHA-256, domain-separated:

Python
import hashlib

def leaf_hash(data: bytes) -> bytes:
    return hashlib.sha256(b"\x00" + data).digest()

def node_hash(left: bytes, right: bytes) -> bytes:
    return hashlib.sha256(b"\x01" + left + right).digest()

def verify(leaf: bytes, index: int, size: int, proof: list[bytes], root: bytes) -> bool:
    if index >= size:
        return False
    h = leaf_hash(leaf)
    fn, sn = index, size - 1
    for p in proof:
        if sn == 0:
            return False              # proof taller than the tree
        if (fn & 1) or (fn == sn):
            h = node_hash(p, h)
            while (fn & 1) == 0 and fn != 0:
                fn >>= 1
                sn >>= 1
        else:
            h = node_hash(h, p)
        fn >>= 1
        sn >>= 1
    return sn == 0 and h == root

Trace: 4 leaves a,b,c,d; prove index 2 (leaf c); proof = [H_d, H_ab].

  • fn=2, sn=3. p=H_d: sn≠0, fn even and fn≠sn → h = node_hash(H_c, H_d) = H_cd. Shift: fn=1, sn=1.
  • p=H_ab: sn≠0, fn odd → h = node_hash(H_ab, H_cd) = H_abcd. Inner loop doesn't run (fn&1==1). Shift: fn=0, sn=0.
  • Loop ends, sn==0, compare H_abcd to root.

Index bits are consumed LSB-first: bit 0 = 0 meant "current node is a left child", bit 1 = 1 meant "right child".

Why each check matters

  • Domain separation (0x00 leaf, 0x01 node): without it a 64-byte leaf can be reinterpreted as an internal node, so an attacker presents a leaf that hashes to an existing internal node and forges inclusion. RFC 6962 §2.1 specifies the prefixes.
  • Index bits encode left/right. Always hashing (h, p) verifies a different tree. Sorted-pair schemes (OpenZeppelin's MerkleProof.verify) drop the bits by sorting each pair before hashing: cheaper to call, but you lose the index and size binding, so you must add the size back yourself if duplicate leaves are possible.
  • The sn == 0 check rejects a proof with extra trailing nodes; without it the loop just keeps hashing and you can't tell.
  • Leaf canonicalization: in Ethereum's MPT, go-ethereum's trie.VerifyProof(root, key, proof) hex-encodes the key to nibbles and RLP-encodes the value. Hashing the raw key gives a different leaf hash and the proof fails.

Trade-offs

Index-based (RFC 6962, Bitcoin's merkleblock) vs sorted-pair (OpenZeppelin): index-based needs the index and tree size in the proof; sorted-pair doesn't, but loses the size binding. On-chain root vs trusted API: an on-chain root costs an RPC round trip and a finality wait (Ethereum finalizes ~12.8 minutes behind head. 2 epochs of 32 slots at 12 s); a trusted-API root is instant and worthless against an adversarial proof. Skip the ceremony when you built the tree and the proof in the same process from data you already trust: there is no adversary to defend against.

Failure modes

  • Stale root: proof generated at block N, root read at block N+1. Detect by pinning the root to a specific block number and re-fetching on mismatch.
  • Orientation flip: a proof for the right sibling verified as if left. Detect by asserting the recomputed root equals the trusted root, not just that the walk completes.
  • Duplicate leaves: Bitcoin's CVE-2012-2459. A block whose transaction list contained a duplicated pair produced the same merkle root as the valid block. Fixed by rejecting duplicate hashes at the same tree level; if you build trees, reject duplicates at insert time.
  • Constant-time comparison: not needed here. Merkle roots are public, so timing leaks nothing. Constant-time comparison is for MACs and password hashes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How do Merkle trees, Verkle trees, and polynomial commitment accumulators (like KZG) compare for blockchain state commitments and proof sizes?

Answer

These three bind a key-value state to one short root and prove membership, but they sit at different points on a proof-size / prover-cost / trust curve. They are not drop-in replacements.

The 90-second answer. Merkle (Ethereum's Merkle Patricia Trie) is hash-based: a proof is O(log_k N) sibling hashes, an update is O(log N) hashes, and it is post-quantum secure, but a block witness is megabytes. Verkle replaces the hash at each node with a vector commitment over the node's children, so the tree gets wide (256-ary) and shallow, and proofs for many keys aggregate into one short proof; witnesses drop roughly an order of magnitude, at the cost of MSM prover work and a non-post-quantum assumption. A direct KZG accumulator over the entire state gives a 48-byte proof, but its SRS is O(N) and a single write is O(N): for 10^9 keys that is a ~48 GB SRS and a full re-interpolation per write. That infeasibility is exactly why Verkle trees exist: they keep the polynomial degree equal to the branching factor (256), not N.

Merkle Patricia Trie. Hexary (k=16), Keccak-256, 32-byte hashes. For N = 10^9 accounts, average depth = ceil(log16 10^9) = 8 (hard-bounded at 64 nibbles). A branch node contributes up to 15 sibling hashes × 32 B = 480 B per level, so the worst-case single-key proof is 8 × 480 ≈ 3.8 KB; real proofs are smaller because sparse branch nodes encode fewer children, typically 1–2 KB. A block touching ~1,000–2,000 slots, with shared paths deduplicated, produces a 1–4 MB witness. Verification is O(log N) hash calls: microseconds.

Verkle tree. 256-ary over 32-byte keys; Ethereum groups keys by a 31-byte stem so the last byte indexes a 256-value leaf vector. For 10^9 keys the average path is ≈ 4 levels (log256 10^9), versus ≈ 8 for the hexary MPT. Each node commits to its 256 children with a vector commitment. Ethereum's design uses Pedersen commitments plus an inner-product argument (IPA) on the Bandersnatch curve: deliberately not KZG, to avoid a trusted setup; other designs do use KZG. A single-key proof is a few hundred bytes; because the commitments are algebraic, openings for many keys aggregate into one proof plus per-key values, so a block witness is estimated at roughly 100–200 KB. Update cost is the catch: recomputing a node commitment is an MSM over 256 points, so a write touches ~4 nodes ≈ 1,024 scalar multiplications. Milliseconds, but far more than a hash. Verification is an MSM plus IPA check, ~1 ms.

Direct KZG accumulator. Interpolate one polynomial P with P(key_i) = value_i, degree N−1, commit C = [P(τ)]_1 (48 B on BLS12-381). A membership proof is one G1 element, 48 B, independent of N. Two things kill it for global state:

  • SRS size is O(N): N powers of τ. At 48 B per compressed G1 point, N = 10^9 → ~48 GB. A Verkle tree needs degree 256 → 256 × 48 B ≈ 12 KB.
  • Update is O(N): changing one value re-interpolates P over all N points (O(N) field ops, or O(N log N) with an FFT). Per block that is seconds to minutes.

Verification is two pairings, ~1–2 ms. Trust is q-SDH plus a powers-of-tau ceremony (Ethereum's had >140,000 contributors). RSA accumulators avoid pairings and give a ~256 B proof for a 2048-bit modulus, but need an unknown-order group and have O(N) witness updates.

MechanismMembership proofUpdate costVerifyTrust assumption
Merkle Patricia TrieO(log_k N) hashes, ~1–2 KBO(log N) hashesO(log N) hashes, µsHash collision resistance
Verkle (IPA)O(1) group elements + per-key values, ~100–200 KB/block~4 MSMs of 256 points, msMSM + IPA, ~1 msDiscrete log (no setup)
Verkle (KZG)same shape, ~48 B per openingsamepairings, ~1–2 msq-SDH + trusted setup
Direct KZG accumulator48 B, O(1)O(N) re-interpolation2 pairings, ~1–2 msq-SDH + trusted setup

Failure modes.

  • Prover CPU saturation: Verkle block building is MSM-bound. Under sustained transaction bursts, block latency degrades without hardware acceleration; profile MSM time per block to detect it.
  • Toxic waste: if the KZG ceremony's τ leaks, an attacker forges arbitrary state roots. IPA-based Verkle removes this failure entirely.
  • Post-quantum: Merkle survives Shor; Verkle and KZG do not. A quantum adversary breaks discrete log and can forge proofs.
  • Sparse-state waste: fixed 256-ary nodes waste space for sparse state; Ethereum's stem grouping is the mitigation, since leaves sharing a stem share one node.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Explain why data availability is separate from Merkle validity.

Answer

The 90-second answer. A Merkle or KZG proof is a statement about a commitment, not about the world. It says "this leaf is in the tree the root commits to," or "this value is the evaluation of the committed polynomial at point z." Both are true whether the data sits on ten thousand disks or on one disk that just went offline. Availability is the separate claim that the data behind the commitment is retrievable by whoever needs it: fraud-proof challengers, light clients, users computing an exit proof. Validity is "the state transition is correct given the data." You can have either without the other, so they are two questions with two verification procedures.

Why the split exists. Fraud proofs need the data. An optimistic rollup's model is: post a state root, publish the batch data, and if the root is wrong anyone can recompute the transition from the data and submit a fraud proof inside the challenge window (7 days on Optimism). If the sequencer posts the root and a commitment but withholds the data, no one can build that proof, and the invalid state finalizes. No amount of Merkle verification touches that case. The mirror case (data published, root wrong) is exactly what the fraud proof is for.

How sampling addresses it. Full danksharding arranges a slot's blobs into a matrix, Reed-Solomon extends it 2x in each dimension, and light clients do data availability sampling: each sample is a share plus a Merkle proof against the block's data root. The original data is reconstructible from any 75% of the extended matrix, so an adversary must withhold more than 25% to make it unrecoverable. A client taking 75 samples, each missing a withheld share with probability at most 3/4 under that attack, misses unavailability with probability (3/4)^75 ≈ 2^-31. That is a strong probabilistic guarantee, not a proof. Celestia runs the same 2D RS + DAS design with its own share size and sampling parameters. EIP-4844 is the stepping stone: blobs are downloaded by full nodes, not sampled. DAS arrives with full danksharding.

The trade-off. The deciding criterion is who you trust and what you pay:

optionavailability guaranteecost
on-chain calldataevery full node has it~16 gas/non-zero byte; 100 KB ≈ 1.6M gas
EIP-4844 blobsKZG commitment, 128 KiB/blob, target 3 / max 6 per blockcheap, but pruned after ~18 days (4096 epochs)
erasure-coded samplingprobabilistic, needs enough honest samplers onlinecheap for light clients
DA committee (validium)honest-minority assumption on the committeecheapest

Failure modes and detection.

  • Valid-but-withheld: commitment on-chain, data never propagated. Detect via DAS sampling failures, or a challenger timing out while fetching the batch. Cost: the rollup freezes; users cannot compute their exit Merkle proof without the state, so funds are stuck until the data reappears.
  • Invalid-but-available: data published, root wrong. Detect via fraud proof inside the window, or a ZK validity proof failing verification immediately.
  • Attacker-selected root: a light client accepts a root that did not come from consensus. Every proof verifies against it and proves only self-consistency. Detect by requiring the root to be finalized by the consensus layer before trusting any proof against it.

One line: a proof tells you the data is consistent with a commitment; it never tells you the data exists. Different claims, different machinery, and a system that conflates them is only as safe as the weaker one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Establish trust in a root used by a light client.

Answer

Assumptions: Ethereum mainnet, post-Altair light client protocol. The client holds no chain data; the "root" is a beacon block root or an execution state root it wants to verify a proof against.

The 90-second answer. A light client cannot verify a root from the inside: that is the whole point of being light. So you bootstrap trust exactly once, out of band, and then authenticate every later root by consensus signatures that chain back to that one anchor. Concretely: pin a weak subjectivity checkpoint (block root + state root) from a source you chose, prove the sync committee for that period is committed in that state, then accept only beacon headers signed by ≥2/3 of that committee, and only advance on finalized updates. Everything after the first checkpoint is verified, not trusted.

Mechanism.

  1. Bootstrap. The checkpoint is the only unverified input. You trust it because you chose the source: your own full node, a checkpoint-sync provider, a peer. Bind it to chain identity (chain ID, genesis validators root, fork digest) so a testnet root cannot be substituted.
  2. Committee. The beacon state at that checkpoint commits to the current sync committee's 512 validator pubkeys. Verify them against the state root with an SSZ proof (the beacon state root is a depth-5 SSZ tree; the committee sits at a known generalized index). You now hold a trusted pubkey set.
  3. Headers. Each light client update carries a beacon block header plus a sync committee aggregate BLS signature over its signing root. Verify the signature against the committee and require ≥2/3 participation: 342 of 512. The fork digest is inside the signature domain, so a mainnet committee signature will not verify under a testnet domain.
  4. Finality. A finality update carries a finalized header and a proof that it is an ancestor of the signed header. Accept the root as canonical only when the finalized checkpoint matches.
  5. Rotation. The committee rotates every 256 epochs (~27.3 h). The new committee is committed in a state you already authenticated, so rotation is verified, not trusted.

Worked trace. Anchor: checkpoint at slot 8,000,000, block root R0, state root S0, from your own node. (1) SSZ proof of next_sync_committee against S0 → pubkeys P[0..511]. (2) Update at slot 8,000,064 carries header H1 and signature σ; verify σ against P, participation bits = 400 → 400/512 > 342 → pass. (3) Finality update: finalized slot 8,000,000 (2 epochs = 12.8 min behind), finalized root Rf; the finality proof shows Rf is an ancestor of H1 → accept Rf. (4) H1's body contains the execution payload header with state root Se; verify an account proof against Se with a Merkle Patricia trie proof (≤64 nibbles). Se is now trusted because H1 was signed by the committee.

Alternatives.

anchortrust assumptioncostwhen to use
Weak subjectivity checkpointone out-of-band root, < ~2 weeks oldlowdefault for light clients
Sync committee alonenone, but you cannot get the committee without a rootlownot viable on its own
Full node bootstrapyour own nodedisk + bandwidthneed historical state, or no external trust
Trusted RPC providerthe provider, every querylowprototyping only; the provider can lie

Failure modes.

  • Stale checkpoint. Older than the weak subjectivity period (~2 weeks at current mainnet validator counts). Detect by comparing checkpoint slot to wall-clock slot; reject and re-bootstrap.
  • Long-range attack. An alternative chain built from an old checkpoint. Only possible if you accept a checkpoint past the weak subjectivity period; the finalized-checkpoint monotonicity check catches forks that diverge after your anchor.
  • Rollback. An update claims a finalized root conflicting with one you already finalized. Keep the highest finalized slot; reject any update whose finalized root at slot ≤ that differs. This is slashable evidence.
  • Insufficient participation. <2/3 signature. Count the aggregate participation bits; reject.

What changes the decision. If you need historical state or cannot accept a single out-of-band root, run a full node and skip all of this. If you can tolerate a trusted provider, you do not need a light client at all.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Explain the evidence and limitations of a blockchain signature.

Answer

Core answer. A blockchain signature is evidence of exactly one thing: the holder of a specific private key authorized a specific byte string. It is not evidence of who that person is, whether they understood what they signed, whether they still control the key, or whether the transaction was included, succeeded, or finalized. Say that in the first minute, then separate the cryptographic claim from the operational ones.

Mechanism. The signer hashes canonical bytes to a 32-byte digest, then signs the digest. On secp256k1 (Bitcoin, Ethereum) that is ECDSA: a 32-byte private key, a 33-byte compressed public key, and a 64-byte (r, s) signature. 65 bytes with a recovery id. Ed25519 (Solana, NEAR, Cardano) uses a 32-byte public key and a 64-byte signature with a deterministic nonce. Verification recomputes the digest and checks the curve equation against the public key. The binding is key→signature. The binding key→account is an enrollment fact held in a registry, not a cryptographic one.

Canonicalization is where most real bugs live. Ethereum signs keccak256 of EIP-191 prefixed bytes or an EIP-712 typed hash; Bitcoin signs double-SHA256 of the serialized transaction. Change one byte of serialization (key order, whitespace, a field the signer didn't see) and verification fails. That is integrity working, and an interop footgun.

What it does not prove, grouped.

QuestionCovered by signature?
Was this byte string authorized by the key holder?Yes
Is the key holder a named person or a business?No: enrollment/registry
Did the signer understand the effect?No: blind signing
Is the key still under the owner's control?No: custody
Was it included, did it succeed, is it final?No: chain state

Failure modes, with detection and cost.

  • Replay across chains. A signature valid on one chain is valid on a fork. Detect by requiring the chain id in v (EIP-155) or a domain separator. Cost of missing it: post-2016, ETH transactions replayed on ETC.
  • Malleability. ECDSA (r, s) and (r, n−s) both verify, so the txid changes. Detect by enforcing low-S (BIP-146 in Bitcoin, EIP-2 in Ethereum). Cost: pre-fix, systems keyed on txid broke.
  • Key compromise. A valid signature from a stolen key is indistinguishable cryptographically. Detect only off-chain: monitoring, hardware-wallet attestation, spend limits. Cost: no cryptographic recovery.
  • Blind signing. The user signs a hash they cannot decode. Detect by decoding and displaying intent before signing. Cost: wallet-drainer losses.

Trade-offs. Signature-based authorization is sufficient when the key is the authority and freshness is enforced by a nonce or chain id: a hot wallet spending its own funds, a validator attestation. It is not sufficient when the action has off-chain legal effect, when custody is shared or custodial, or when the signer's intent must be provable later. In those cases you add authorization policy, freshness checks, and chain-state confirmation on top; the signature stays necessary but stops being the whole answer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Compare Schnorr and ECDSA signatures for blockchain use: how each handles key and signature aggregation, linearity, and multisig construction, and what that changes for on-chain verification cost, transaction identity, and Taproot key aggregation?

Answer

Ask which chain and curve first: the answer is chain-specific. Bitcoin and Ethereum both use secp256k1 ECDSA; Bitcoin has also had BIP 340 Schnorr since Taproot. Everything else follows from one structural fact: ECDSA verification is non-linear in the key, Schnorr is linear.

ECDSA verifies (r, s) by computing u1 = z·s⁻¹, u2 = r·s⁻¹, R = u1·G + u2·Q, and accepting when R.x mod n = r. The s⁻¹ is what kills linearity: two ECDSA signatures cannot be added into a valid signature under the sum of the keys. Schnorr signs s = k + e·a with e = H(R.x ‖ P ‖ m) and verifies s·G = R + e·P. Key and signature both appear to the first power, so they add: (s1+s2)·G = (R1+R2) + e·(P1+P2) when both signers share the challenge. That is the whole difference; the rest is consequences.

ECDSA secp256k1BIP 340 Schnorr
signatureDER ~71–72 B (Bitcoin); 65 B with recovery id (Ethereum)64 B fixed
public key33 B compressed32 B x-only
verifyu1·G + u2·Q, needs s⁻¹s·G = R + e·P
linear in keynoyes
aggregationnone nativekeys and signatures add
malleability(r,s) and (r,n−s) both validnone
batch verifyno standard form~2× for large batches

On-chain cost. A 2-of-3 bare Bitcoin multisig spend carries three 33-byte pubkeys and two ~72-byte DER signatures, about 243 bytes of witness. The same policy as a MuSig2 key-path Taproot spend is one 32-byte x-only output key plus one 64-byte signature, about 96 bytes, and it is indistinguishable from a single-key wallet: a 100-of-100 policy costs the same 64 bytes. Ethereum has no protocol-level Schnorr: ecrecover is a 3000-gas precompile, while a Schnorr verifier in Solidity costs tens of thousands of gas, so aggregation there lives in contracts or an L2 precompile, not in the scheme.

Transaction identity. ECDSA's (r,s)/(r,n−s) ambiguity is why Bitcoin needed low-S rules and segwit's separate witness commitment to stop a third party changing txids. Schnorr has no such ambiguity, BIP 340 fixes 64 bytes and s < n, so the signature is canonical and txid stability is free.

Taproot key aggregation. The output key is Q = P + t·G, P the internal key, t = H(P ‖ script) committing to the script path. If P is a MuSig2 aggregate of n signers, the key-path spend is one signature revealing nothing about n. The price is interactivity and rogue-key defence: MuSig2 needs two nonces per signer and two rounds, and aggregation needs either a proof of possession or the MuSig coefficient a_i = H(L, P_i) over the key list L. Without it the last signer sets P_n = P′ − ΣP_i and controls the aggregate alone.

Failure modes. Schnorr nonce reuse is as fatal as ECDSA's: k known gives a = s − e·k, and a MuSig2 nonce reused across sessions leaks the key. ECDSA's nonce risk is normally handled with RFC 6979 deterministic k; Schnorr's with per-session nonces and MuSig2's two-nonce scheme. Batch verification accepts or rejects a set, so one bad signature fails the batch and you need a fallback to find it. And any protocol where an attacker chooses its key inside an aggregate needs proof of possession.

When not to use it: a chain with no Schnorr verifier (Ethereum L1 today), or when an auditor must see who approved. An aggregated signature hides the signer set, which is right for a 2-of-2 treasury and wrong for a compliance trail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Protect ECDSA nonce generation in a signing service.

Answer

Use RFC 6979 deterministic nonces, or a CSPRNG you trust. Never use timestamps, counters, or a weak RNG. The reason is that ECDSA's security collapses if k repeats or is biased.

I'm assuming you control the signing service and can pick the library. The attacker sees your public key and signatures.

ECDSA signs with s = k⁻¹(h(m) + r·d) mod n. If two signatures share the same k, they share the same r. Subtract the two equations: s1 - s2 = k⁻¹(h1 - h2) mod n. Solve for k: k = (h1 - h2)/(s1 - s2) mod n. Then d = (s1·k - h1)/r mod n. Two signatures, one private key.

Toy example with n=17, d=5, k=3, r=10. Message hashes h1=7, h2=11. k⁻¹ mod 17 = 6. s1 = 6*(7 + 105) = 657 = 342 ≡ 2 mod 17. s2 = 6*(11 + 105) = 661 = 366 ≡ 9 mod 17. Attacker sees (r=10, s1=2, h1=7) and (r=10, s2=9, h2=11). Compute k = (7-11)/(2-9) = (-4)/(-7) = 4/7 mod 17. 7⁻¹ mod 17 = 5 (since 75=35≡1). So k = 45 = 20 ≡ 3 mod 17. Then d = (2*3 - 7)/10 = (6-7)/10 = -1/10 ≡ 16 * 12 = 192 ≡ 5 mod 17. Recovered.

Deterministic RFC 6979 uses HMAC_DRBG with the private key and message hash to derive k. It removes the RNG from the equation. Random nonces need a CSPRNG seeded with enough entropy; a hardware RNG is ideal. Deterministic is safer against RNG failures, but you must ensure the implementation is constant-time. Random can be fine if you have a good entropy source.

Deterministic (RFC 6979)Random (CSPRNG)
Nonce sourceHMAC_DRBG(private key, message hash)CSPRNG
Failure modePrivate key leak compromises all noncesRNG failure or reuse
Implementation riskSide channels, fault injectionEntropy starvation, reuse
Best forConstrained devices, no RNGSystems with hardware RNG

Nonce reuse is detected by seeing the same r in two signatures. Bias, e.g., k from a small range, enables lattice attacks. Side channels: timing or power analysis can leak k. Fault injection: glitching to skip the nonce check. Monitor for duplicate r values, run known-answer tests, use constant-time code. Pin the curve and hash algorithm; don't let the caller choose weak ones. Keep the library patched.

If you're on a constrained device without a good RNG, deterministic is the only safe choice. If your compliance regime mandates a specific RNG, follow that. If you suspect reuse, rotate the key immediately; historical signatures are already compromised.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Design strict public-key validation for a multi-chain verifier.

Answer

Core answer (first 90 seconds)

Assume the verifier takes public keys from untrusted peers and must map each key to exactly one chain. The design rule: derive the expected curve and encoding from authenticated configuration keyed by chain ID, never from the key bytes. Then run a fixed pipeline (canonical encoding, range, on-curve, subgroup, chain binding) and reject on the first failure. The pipeline is cheap: one field inversion, plus one scalar multiplication only on cofactor > 1 curves. It is the only place attacker bytes touch curve arithmetic, so it is also the only place you need negative test vectors.

Why each check exists

Canonical encoding. A point has one valid encoding per scheme. secp256k1 SEC1 compressed is 33 bytes: a 0x02/0x03 prefix plus big-endian x; uncompressed is 65 bytes starting 0x04. Ed25519 is 32 bytes: little-endian y with the sign of x in the top bit of byte 31. Non-canonical forms (y ≥ p = 2^255 − 19, or x = 0 with the sign bit set) decode to a point that already has a canonical encoding. Accepting both is signature malleability; Bitcoin's low-S rule (BIP-62) exists because two encodings of one signature produced two transaction IDs.

Reject infinity and out-of-range. SEC1 encodes infinity as the single byte 0x00. Coordinates must satisfy x, y < p. Skip the range check and a value ≥ p aliases to a different field element after reduction.

On-curve. secp256k1: y² = x³ + 7 over F_p, p = 2^256 − 2^32 − 977. P-256: y² = x³ − 3x + b. Ed25519: −x² + y² = 1 − (121665/121666)x²y². Skipping this enables the invalid-curve attack (Biehl–Meyer–Müller): the attacker supplies a point on a different curve with a small factor, the verifier does scalar multiplication there, and the result leaks bits of the private scalar. It bites ECDH hardest; for signature verification it still admits a key no honest signer could have produced.

Subgroup. This is the check people skip, and it is only needed when the cofactor h > 1. secp256k1 and P-256 have h = 1, so on-curve implies in the prime-order subgroup: no extra work. Ed25519 has h = 8: eight points of order dividing 8 exist, and a small-order public key makes a signature verify for many messages or lets a key-exchange peer pin the shared secret. BLS12-381 G1 has h = 0x396c8c005555e1568c00aaab0000aaab, so a subgroup check is mandatory before any pairing. The check is [h]P == identity, or [L]P == identity for the prime order L.

Chain binding. A secp256k1 key is valid on Bitcoin and Ethereum at once. Curve validation alone does not say which chain it belongs to; address derivation differs (HASH160 for P2PKH, Keccak-256 of the uncompressed key for Ethereum). Bind the validated key to the chain ID from config and reject a key whose derived address does not match the claimed network.

curvechainscofactor hsubgroup checkencoding
secp256k1Bitcoin, Ethereum1not neededSEC1 33/65 B
P-256NIST, passkeys, some L2s1not neededSEC1 33/65 B
Ed25519Solana, Cardano, NEAR8required32 B LE, sign bit in bit 255
BLS12-381 G1Ethereum consensus, Chia0x396c8c005555e1568c00aaab0000aaabrequired48 B compressed
BLS12-381 G2Ethereum consensuslarger than G1required96 B compressed

Libraries that already implement the pipeline: libsecp256k1 secp256k1_ec_pubkey_parse (rejects infinity, off-curve, x ≥ p); Go crypto/ecdh P256().NewPublicKey; filippo.io/edwards25519 Point.SetBytes (rejects non-canonical and off-curve, but not small order. Call IsSmallOrder or multiply by 8); Rust curve25519-dalek 4.x CompressedEdwardsY::decompress plus is_small_order; blst blst_p1_uncompress plus blst_p1_affine_in_g1.

Trade-offs

Strict validation costs one field inversion plus, on cofactor > 1 curves, one scalar multiplication: sub-millisecond, and it is per-key, not per-signature, so cache the result. Lighter validation is defensible when the key is already authenticated elsewhere: a key read from verified on-chain contract state, or pinned in config at deploy time, has been through the chain's own consensus validation. The deciding criterion is provenance. Bytes from an untrusted peer get the full pipeline; bytes from a source you already trust to have validated them can skip the subgroup check but not the encoding check, because re-encoding is where malleability lives.

What would change the decision

If the verifier only ever sees keys a full node already validated, reading through a light client with proof verification, the on-curve and subgroup checks are redundant and you can drop to encoding plus chain binding. Add a curve with h > 1 to the supported set and the subgroup check becomes mandatory, with negative vectors for the eight small-order Ed25519 points and the non-canonical encodings.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Handle signature malleability and transaction identity safely.

Answer

Assumptions I'd state first: Bitcoin with segwit v0 inputs, Ethereum mainnet post-Homestead, and a service that credits deposits or dedupes withdrawals. If your chain is neither, the mechanism is the same but the constants differ.

Core answer. Signature malleability means one message has more than one valid signature encoding. So a signature is not an identity. Never key idempotency, dedupe, or a business record on submitted signature bytes. Key on protocol identity where the protocol guarantees it: Ethereum (sender, nonce) or the post-EIP-2 transaction hash; Bitcoin txid for confirmed spends and wtxid when witness data matters, and carry a client-generated operation id in the payload for anything that must survive re-signing or a bridge.

Why it happens. ECDSA verifies (r, s) and (r, n − s) against the same message and key, where n is the curve order. For secp256k1:

Python
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
HALF_N = N // 2   # 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0

def canonical_s(s):
    return s if s <= HALF_N else N - s

s_high = N - 1
print(hex(canonical_s(s_high)))  # 0x1
print(s_high <= HALF_N)          # False

s_high and 1 both verify. Separately, DER encoding has slack: leading zero padding, non-minimal lengths, negative integers. Bitcoin closed both holes: BIP-66 strict DER became consensus at block 363725 (July 2015), and low-S is standardness since Bitcoin Core 0.11.2 and consensus for segwit v0 witness signatures per BIP-143. Note the gap: low-S is not consensus for legacy inputs, so a miner can still include a high-S legacy signature. Ethereum's EIP-2 (Homestead, block 1,150,000) rejects s > n/2 at the transaction level, and EIP-155 binds v to a chain id. But the ecrecover precompile at 0x01 still accepts high-S, so a contract that stores used[keccak(sig)] is replayable by flipping s.

Identity, and what it costs.

identity sourcesurvives re-signingsurvives cross-chaincost
Bitcoin txid / wtxidnonofree
Ethereum (sender, nonce)nonofree
app op id in calldata/memoyesyesbytes + client change

Deciding criterion: if exactly-once must hold per on-chain transfer, protocol identity is sufficient and cheapest. If the same logical payment can be re-signed, replaced (RBF), or bridged, protocol identity is not stable and you need the application id. The alternative to rejecting non-canonical input is normalizing on read: accept both s and n − s, canonicalize before hashing. That is required only when you must verify historical pre-BIP-66 signatures; for new traffic, reject at ingress and match consensus.

Failure modes and detection.

  1. Idempotency keyed on signature bytes. Attacker takes a pending deposit, flips s to n − s, resubmits; two distinct txids, two credits. Detect by indexing on the input outpoint set plus outputs, not the txid, and alerting on two txids sharing an identical outpoint set.
  2. Bitcoin legacy third-party mutation. A relayer rewrites scriptSig, the txid changes, and a child spending the unconfirmed output is invalidated. Detect with a mempool watcher that groups by outpoint set; this is exactly what segwit's txid/wtxid split fixes.
  3. Contract-level replay. ecrecover without a low-S check accepts the flipped signature. Detect by indexing on (recovered signer, message hash) rather than signature bytes.
  4. Nonce reuse. Two signatures sharing r leak the private key. Detect by asserting r uniqueness per signing key in your signer service.

What I'd test. Network vectors for alternate valid encodings, rejected non-canonical DER, and a library upgrade that changes canonicalization: run the same vectors before and after, and diff the resulting txids.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Specify canonical bytes for a signed blockchain request.

Answer

Canonical encoding means a bijection: one logical request maps to exactly one byte string, and every implementation produces it. Signatures are over bytes, so a second encoding of the same request is a second valid signature over the same intent (malleability), and an encoding that omits chain identity is replayable on a fork.

State assumptions before choosing rules: signature scheme (secp256k1 ECDSA with low-S, Ed25519, or BLS), whether the chain already defines a typed-data standard, and whether you control both signer and verifier. If a standard exists (EIP-712 on EVM, SSZ on Ethereum consensus, Borsh on Solana) adopt it. Hand-roll only when no standard covers your fields.

Rules that buy the bijection:

  • Version byte first. 0x01 at offset 0. Unknown version → reject, never guess.
  • Fixed field order, fixed widths, explicit endianness. No maps, no implicit defaults. Integers big-endian at a declared width, no leading zeros beyond it.
  • Length-prefix every variable field. A 4-byte big-endian length before each bytes/string. Delimiters are ambiguous; lengths are not.
  • Bind chain and domain. chain ID, application ID, message type and a purpose separator inside the signed payload.
  • Normalize strings. UTF-8, NFC, reject invalid sequences. Addresses as raw 20 bytes, not mixed-case hex.
  • Reject non-canonical input at the verifier. Duplicate fields, non-minimal integers, unknown versions, alternate encodings.

Byte layout for a transfer:

offset  bytes  field
0       1      version  = 0x01
1       1      msg_type = 0x02 (transfer)
2       4      chain_id = 0x00000001 (BE)
6       8      nonce    = 0x000000000000002A (BE)
14      8      amount   = 0x0000000000000005 (BE)
22      4      to_len   = 0x00000014
26      20     to       = <20 raw bytes>
46      4      data_len = 0x00000000
50      0      data

50 bytes total. Sign the payload directly (Ed25519) or its 32-byte hash (ECDSA).

approachcanonical by constructioncost
hand-rolledonly if you enforce ityou own test vectors, cross-language parity, and every future field addition
EIP-712yes, via type hashesEVM-only; nested structs need careful encodeType; domain separator must include chainId and verifyingContract
SSZyesconsensus-layer tooling; 4-byte offsets for variable fields add complexity; not on every chain

EIP-712's digest is keccak256("\x19\x01" || domainSeparator || hashStruct(message)), where the domain separator hashes the type string EIP712Domain(string name,string version,uint256 chainId,address verifyingContract) plus each field. That prefix is what stops a signed message from being reinterpreted as a transaction.

Failure modes and how to catch them:

  1. Cross-chain replay. Omit chain ID and a testnet signature verifies on mainnet. Detection: replay a mainnet-signed request against a fork in CI; it must fail. EIP-155 added chain ID to Ethereum's signing hash for exactly this.
  2. Two encodings, one signature. JSON {"to":"A","to":"B"}: some parsers take the first key, some the last. Detection: fuzz the parser with duplicate keys and assert rejection.
  3. ECDSA malleability. (r, s) and (r, n−s) both verify. Enforce low-S (s ≤ n/2), as BIP-62 does. Detection: assert the high-S variant is rejected.
  4. Non-minimal integers. 0x00 0x2A and 0x2A decode to the same value. Detection: property test that re-encoding a decoded message is byte-identical.

Operational cost: every new field is a version bump. Keep byte-level test vectors in the repo and run a cross-language conformance suite (Go, Rust, TypeScript) in CI before signatures are accepted in production.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Prevent cross-chain and cross-protocol signature replay.

Answer

First 90 seconds

Sign an EIP-712 typed struct, never an opaque hash. The digest the key signs is:

keccak256(0x1901 || domainSeparator || structHash)

domainSeparator = keccak256(abi.encode(keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), block.chainid, address(this)))

structHash = keccak256(abi.encode(keccak256("Order(address maker,address taker,uint256 amount,uint256 nonce,uint256 deadline)"), maker, taker, amount, nonce, deadline))

chainId and verifyingContract are bytes inside the preimage, so the same order signed on chain 1 or for contract A gives a different digest on chain 137 or contract B; ecrecover over that digest returns an address that is not the signer, and verification fails. The primary type string sits inside structHash too, so the same chain and contract cannot reinterpret a Permit as a TransferWithAuthorization. The distinct 0x19 namespaces (0x1901 for EIP-712, 0x19 followed by "Ethereum Signed Message:\n" for personal_sign) stop a personal_sign signature being replayed as typed data. Then: a nonce consumed atomically, a deadline, and authorization re-checked after verification, because a signature proves intent at signing time, not authority now. Assumes EVM, secp256k1 ECDSA, EIP-712, EIP-155 chain ids.

The check, Solidity 0.8.24

SOLIDITY
bytes32 constant ORDER_TYPEHASH = keccak256(
    "Order(address maker,address taker,uint256 amount,uint256 nonce,uint256 deadline)"
);
bytes32 immutable DOMAIN_SEPARATOR;              // built in the constructor
mapping(address => mapping(uint256 => bool)) usedNonce;

function fill(address maker, address taker, uint256 amount,
              uint256 nonce, uint256 deadline, bytes calldata sig) external {
    require(block.timestamp <= deadline, "expired");
    bytes32 structHash = keccak256(abi.encode(ORDER_TYPEHASH, maker, taker, amount, nonce, deadline));
    bytes32 digest = keccak256(abi.encodePacked(hex"1901", DOMAIN_SEPARATOR, structHash));
    require(ECDSA.recover(digest, sig) == maker, "bad sig");  // s <= n/2, v in {27,28}
    require(!usedNonce[maker][nonce], "nonce used");
    usedNonce[maker][nonce] = true;              // rolled back with the tx if anything later reverts
    // authorization last: is maker still the owner, with allowance?
}

Two transactions with the same nonce: the second reverts on require and the write above it unwinds with it, all inside one single-threaded EVM frame, so check-and-set needs no lock. The trap is that immutable separator. Deploy at the same address on two chains with the same chain id, or fork a chain and the cached value goes stale, and signatures made for the old id verify again. OpenZeppelin's EIP712 rebuilds the separator whenever block.chainid or address(this) differs from the cached pair; a hand-rolled deploy-time constant does not.

Failure modes, and how you see them

VectorBlocked byDetection
Replay in the intended domainone-time nonce: EIP-2612 increments nonces[owner], EIP-3009 consumes a random bytes32 from a mappingsecond fill reverts "nonce used"
Same address on many chains, domain omits chainIdchainId in the domainidentical calldata in both chains, same nonce filled twice
Cached separator after a chain-id changerecompute on chainid/address mismatchorders verify on the old chain id only
Malleabilityreject s > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, v outside {27,28}two different signatures over one digest both recover the signer
Safe / contract walletsEIP-1271 isValidSignature returning 0x1626ba7e, plus signer.code.length > 0ecrecover returns a non-owner for every order
No expirydeadline, or validAfter/validBeforea fill lands months after signing
Contract exposing verify(bytes32)always recompute the digest from fieldsattacker presents a signature over a digest they picked

Alternatives and when to pick one

  • Sequential nonce (EIP-2612, one SSTORE) when a single relayer submits in order. A stuck relayer blocks every later permit, which is why USDC permits cannot be batched.
  • Bitmap nonce (Permit2: 2^248 words of 256 bits, nonce = wordPos << 8 | bitPos) when out-of-order or batched submission matters, at one SSTORE per word touched.
  • Random bytes32 nonce from a mapping (EIP-3009) for any-order single-use without batching.
  • Off-chain relayer: unique index on (signer, nonce); a duplicate-key insert or failed Redis SET NX is the replay signal. Any TTL on that key must outlive the signature deadline or the same signature works again afterwards.
  • Per-token domain plus permit (USDC implements EIP-2612; USDT does not, so those flows need approve then transferFrom) versus one Permit2-style escrow at 0x000000000022D473030F116dDEE9F6B43aC78BA3 deployed at the same address across chains: one signature covers many tokens, paid for with a standing max allowance.
  • Implement EIP-5267 eip712Domain() so wallets re-derive the domain from the contract instead of guessing and showing the user an unknown domain.

Outside the EVM the same split holds. Cosmos sign docs carry chain_id, account_number and sequence, so sequence bounds replay. Solana messages carry no chain id; freshness comes from a recent blockhash that expires within about a minute, which blocks indefinite replay but gives no domain separation, so a program needing it puts its own domain string in the signed payload.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How do threshold ECDSA schemes and on-chain multisignatures compare in on-chain footprint and round interactivity?

Answer

Say this first. Pin three things before comparing: which chain (ECDSA-only, or Schnorr-capable), the quorum (t-of-n), and whether signers can be online in the same window. Then: threshold ECDSA gives O(1) on-chain footprint and hides the policy, but needs a stateful multi-round off-chain protocol. On-chain multisig needs zero coordination but publishes m keys and m signatures. On a Schnorr chain (Taproot, BIP-341) MuSig2 collapses both (2 rounds, one 64-byte signature, indistinguishable from single-sig) so the trade-off only bites on ECDSA-only chains.

On-chain footprint.

Threshold ECDSA outputs an ordinary (r,s) pair under one aggregated public key Q = xG. The verifier runs stock ECDSA (ecrecover (precompile 0x01, 3000 gas) on Ethereum, one OP_CHECKSIG on Bitcoin) so cost is flat in n and t.

SOLIDITY
// threshold: one signature, one recovery
function verifyThreshold(bytes32 d, uint8 v, bytes32 r, bytes32 s, address Q)
    internal pure returns (bool)
{
    address signer = ecrecover(d, v, r, s);       // 3000 gas
    return signer != address(0) && signer == Q;   // reject the zero-address failure
}

// m-of-n on-chain: m recoveries, m calldata loads
function verifyMultisig(bytes32 d, bytes[] calldata sigs, address[] calldata owners)
    internal pure returns (bool)
{
    for (uint256 i; i < sigs.length; ++i) {
        (uint8 v, bytes32 r, bytes32 s) = split(sigs[i]);
        address signer = ecrecover(d, v, r, s);   // 3000 gas each
        if (signer == address(0) || signer != owners[i]) return false;
    }
    return true;
}

Ethereum arithmetic: one 65-byte signature (r 32 + s 32 + v 1) is 65 × 16 = 1040 gas of calldata plus 3000 gas for ecrecover ≈ 4.0k gas. A 5-owner Safe-style check is 5 × 3000 = 15,000 gas of ecrecover plus 5 × 1040 = 5200 gas calldata ≈ 20.2k gas, before Safe's own nonce, event and execution overhead. Roughly 5×, and it scales with m.

Bitcoin arithmetic: a P2WPKH input is 68 vbytes (41 non-witness bytes + 108 WU witness) whether it is one signer or a threshold quorum. A 2-of-3 P2SH multisig input is ≈290 vbytes: outpoint 36 + scriptSig length 1 + scriptSig 248–250 (OP_0 1 + two 72–73-byte pushes + 103-byte redeem-script push) + sequence 4. A 3-of-5 is larger again. Threshold ECDSA on Bitcoin is the 68-vbyte case.

The privacy consequence is the flip side: threshold ECDSA is indistinguishable from a single-signer wallet, so there is no on-chain record of who approved. Multisig exposes keys and quorum, which is what you want if the policy must be auditable on-chain.

Round interactivity.

Threshold ECDSAOn-chain multisig
On-chain sizeO(1): 65 B (Ethereum) / 68 vB (P2WPKH)O(m): m sigs + m keys
Verifierstock ECDSA (ecrecover / OP_CHECKSIG)script or contract loop over m
Online signing roundsGG18: 6; GG20: 1 online + preprocessing; Lindell17 (2-party): 40 coordination
Schnorr equivalentn/a: FROST/MuSig2 are Schnorr, not ECDSAMuSig2: 2 rounds, O(1)
Signer livenessall t online in one sessionasync, any time
Policy privacyhiddenpublic
Abort handlingGG18 unattributable; GG20 identifiabledropouts just delay

Round counts are for the online signing phase; preprocessing (Paillier modulus generation, MtA) adds more. The digest each signer commits to is chain-defined (BIP-143 sighash on Bitcoin, EIP-712 typed data on Safe) while RFC 6979 governs each signer's deterministic nonce, not the digest.

Failure modes.

Threshold ECDSA: nonce reuse is fatal. If any party reuses its nonce share k_i across two different messages, the shared secret is recoverable from the two signatures: the same algebra that breaks single-signer ECDSA. Sessions need unique IDs, nonce commitments, and no reuse of aborted state. Aborts are the second hazard: a party that drops mid-protocol stalls the signature; GG18 has no identifiable abort, so a malicious party can DoS without being named, while GG20 adds identifiable abort at the cost of heavier preprocessing. Signers must be online together, and losing t shares loses the key permanently: there is no on-chain recovery path.

On-chain multisig: signers are independent, so dropouts just mean fewer signatures collected and the transaction waits. The real hazards are signature malleability (enforce low-s, s ≤ n/2, per EIP-2: the ecrecover precompile does not), replay across chains (bind a chain ID or EIP-712 domain separator), and ecrecover returning address(0) on malformed input, which must be rejected explicitly.

Picking. ECDSA-only chain and you want privacy or flat fees → threshold ECDSA, and budget for the round count plus a session manager. Need on-chain auditability, async signers, or recovery modules → on-chain multisig. Schnorr chain → MuSig2/FROST, the only option that gets both.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Use hierarchical deterministic wallets without expanding compromise impact.

Answer

Core answer (first 60–120 seconds)

Start from the threat model, because it decides the design. Three things leak independently: an extended public key (xpub), a single child private key, or the seed. One rule governs everything else. Under BIP32 non-hardened derivation, a parent xpub plus any one non-hardened child private key reconstructs the parent private key. Hardened derivation breaks that link. So you put hardened boundaries at the levels you want to act as blast-radius walls, and you only ever hand out the xpub of a hardened boundary: never the master.

In BIP44/49/84/86 the account level is hardened: m/44'/0'/0'. That account xpub is the natural watch-only unit. Leaking it plus one address key compromises that account and nothing above it, because the account is a hardened child of the master. That containment is the whole point.

Why it works

Non-hardened child: I = HMAC-SHA512(chain_code, serP(K_par) || index), IL = I[0:32], child_priv = (IL + parent_priv) mod n. The same IL is computable from the parent public key alone: that is why an xpub can generate child public keys and addresses. It also means: given child_priv and IL, parent_priv = (child_priv − IL) mod n.

Hardened child: I = HMAC-SHA512(chain_code, 0x00 || parent_priv || index). Computing IL now needs the parent private key, so an xpub cannot derive hardened children, and a leaked hardened child key gives no path upward.

Toy arithmetic (labelled, not real curve values): pretend n = 1000, parent_priv = 500, IL = 137, so child_priv = 637. The attacker holds the parent xpub, recomputes IL = 137, and recovers parent_priv = 637 − 137 = 500. Real n is the secp256k1 order, about 1.16 × 10^77; the subtraction is identical.

Paths

BIPPathAddress
BIP44m/44'/0'/0'/0/01…
BIP49m/49'/0'/0'/0/03…
BIP84m/84'/0'/0'/0/0bc1q…
BIP86m/86'/0'/0'/0/0bc1p…

purpose', coin_type', account' are hardened; change and address_index are not. Ethereum uses m/44'/60'/0'/0/0.

Failure modes

  • Master xpub exported: it is the root of the non-hardened tree. In a strict BIP44 layout the hardened purpose/coin/account levels mean it derives nothing on its own, but any non-hardened child of the master, some wallets and custom schemes have them, plus the master xpub recovers the master key. Do not export it.
  • Account xpub plus one address key: the account is compromised. Detect by auditing which services hold xpubs and whether any store a non-hardened private key alongside one.
  • Gap limit: BIP44's default is 20 consecutive unused addresses. Generate out of order and funds look missing.
  • Sharing an xpub with a watch-only service leaks every address and balance and links them together.

Trade-offs

Hardening everything kills watch-only. So harden at the account boundary, accept the account xpub as the exposure unit, and use separate accounts, each hardened, per tenant or purpose when you need finer isolation. For cold storage, a separate seed beats a deeper path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design a production blockchain signing service.

Answer

Clarify first. Which chains and curves? Ethereum and Bitcoin use secp256k1 ECDSA; Solana and Cardano use ed25519. What throughput: a treasury signing a few transactions a day, or a hot wallet signing thousands? Who calls it? I'll assume multi-chain, secp256k1 + ed25519, internal callers, tens of signatures per second at peak, and a hard rule that key material never reaches an application process.

Core answer. Split into three planes that fail independently:

  • Custody: keys live in an HSM or an MPC cluster; the private key is never in process memory.
  • Policy: a stateless engine that decides whether a signing intent is allowed.
  • Signing: workers that call custody and return only a signature.

The API takes an intent, not a blob: {chain_id, from, to, value, data, nonce, fee_cap, request_id}. The service builds the transaction, hashes it, and asks custody to sign the digest. It returns {signature, tx_hash}. The caller broadcasts. Keeping broadcast out of the signer means a compromised caller cannot make the signer talk to the network.

Custody choice: the real trade-off.

OptionKey exposureSign latencyCeilingWhen it's wrong
HSM (PKCS#11)Non-extractable, CKA_EXTRACTABLE=false, CKA_SENSITIVE=truesingle-digit to low-tens of ms/op~hundreds ops/s per deviceOne HSM is a single point of failure; run ≥2 in separate AZs
MPC / threshold (2-of-3 GG20 for ECDSA, FROST for Schnorr/ed25519)No node ever holds the full key50–200 ms LAN, more over WANScales with nodesInteractive protocol: abort handling and node liveness are yours; no hardware root of trust
Hot wallet (software key)Key in memorymicrosecondsvery highOnly for balances you can afford to lose
Cold / offlineAir-gappedminutes–hours, manuallowCannot meet an automated SLA

Rule: hot for balances you would write off, HSM or MPC for treasury, cold for the reserve. Never one tier for everything.

Policy engine. Stateless, evaluated before every signature, deny by default. It checks destination allowlist per chain, per-tx value cap, rolling-window velocity cap, fee/gas cap, chain ID match, contract method-selector allowlist, nonce monotonicity, and approver quorum above a threshold.

Python
def authorize(intent, policy, state):
    if intent.chain_id != policy.chain_id: return Deny("chain")
    if intent.to not in policy.allowlist: return Deny("destination")
    if intent.value > policy.per_tx_cap: return Deny("value")
    if state.spent_1h + intent.value > policy.hourly_cap: return Deny("velocity")
    if intent.fee_cap > policy.max_fee: return Deny("fee")
    if intent.nonce != state.next_nonce: return Deny("nonce")
    return Allow()

Nonce management. On Ethereum the nonce is sequential per account; one stuck nonce blocks every later transaction from that account. Keep a single durable allocator per account, persist the counter before signing, and alert on any gap. If a signed transaction is never mined, re-sign the same nonce with a higher fee: never skip it.

Failure modes and detection.

  • HSM failure: in an AWS CloudHSM cluster, keys are replicated across every HSM, so the cluster keeps serving (including writes) as long as one HSM is live. Losing HSMs cuts signing throughput, not availability. Detect via cluster health metrics; keep HSMs in separate AZs so one AZ outage cannot take the last one. (Distinct from quorum authentication, which requires a quorum of crypto officers to approve key-management operations like create/delete: a key-lifecycle control, not a signing-availability one.)
  • Nonce gap: the account stalls. Detect by comparing on-chain nonce to the allocator counter; alert when they diverge for more than a few blocks.
  • Policy bypass: a caller signs directly against custody. Prevent it by making custody accept only requests carrying a policy-engine signature.
  • Key compromise: detect via unexpected signing requests or an address draining; the response is rotate to a new key and move funds, which is why rotation must be rehearsed.

Arithmetic. At ~10 ms per sign per HSM, one HSM is ~100 ops/s; three HSMs give ~300 ops/s, and losing one still leaves ~200 ops/s: well above the 20/s peak. So the extra HSMs buy AZ-failure tolerance, not throughput.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design a fail-closed signed-request verification pipeline.

Answer

Assumptions I'd state first: an HTTP API, asymmetric signatures (Ed25519 or ECDSA P-256), clients hold private keys, the server holds public keys in a JWKS-style store, and requests carry a signature over method, path, body digest, timestamp and nonce. If any of those is wrong (symmetric HMAC, mTLS instead of signatures) the pipeline changes shape, so I'd confirm before designing.

The invariant: no request reaches business logic unless every check passed, and any check that cannot be evaluated is a rejection, not a skip. Order matters twice over: cheap checks gate expensive ones, and you must never act on bytes you haven't verified.

Pipeline, in order:

  1. Bound before parsing. Reject body > 64 KiB, header block > 8 KiB, more than 100 headers, and chunked bodies with no declared length. This runs before any parser touches bytes.
  2. Parse exactly one canonical form. Pick one serialization (RFC 9421 HTTP Message Signatures, or JWS per RFC 7515) and reject the others. Duplicate headers, duplicate JSON keys and mixed-case header names are rejected, not merged: otherwise signer and verifier disagree about what was signed.
  3. Select the algorithm server-side, keyed by key ID. Never read alg from the request. Allow Ed25519 or ECDSA P-256/SHA-256. Reject alg: none, and reject HS256 when the key is an asymmetric public key.
  4. Validate encodings. base64url without padding; JWK kty/crv matches the registered key; signature length exactly 64 bytes for Ed25519 or P-256 raw.
  5. Reconstruct the signing input with domain separation: a fixed context prefix plus method, path, body digest, timestamp, nonce, in canonical order.
  6. Verify the signature over that exact byte string.
  7. Check timestamp within ±30 s of server clock, and nonce unseen.
  8. Check business authorization against current state, not the token's claims.
  9. Atomically consume the nonce and record the effect in one transaction.

Why each step exists. Domain separation stops a signature minted for one purpose being replayed as another. Atomicity closes the TOCTOU between "nonce is fresh" and "nonce is recorded": with a separate check-then-write, two concurrent replays both pass step 7.

Python
def verify(req, key_store, nonce_store):
    if len(req.body) > 64*1024 or len(req.headers) > 100:
        return reject("too_large")
    parsed = parse_canonical(req)              # one form, else reject
    key = key_store.get(parsed.key_id)         # server-side lookup
    if key is None or parsed.alg not in key.allowed_algs:
        return reject("alg")                   # never trust req.alg
    if not valid_encoding(parsed, key):
        return reject("encoding")
    msg = context_prefix + canonical(parsed)
    if not verify_sig(key, msg, parsed.sig):
        return reject("sig")
    if abs(now() - parsed.ts) > 30:
        return reject("skew")
    if not nonce_store.setnx(parsed.nonce, ttl=300):   # atomic
        return reject("replay")
    return authorize_and_apply(parsed)

Trace an algorithm-confusion attempt: request carries alg=HS256 and an HMAC computed over the public key bytes. Step 3 finds key.allowed_algs = {Ed25519}, parsed.alg = HS256 → reject("alg"). Signature verification never runs. Trace a replay: first delivery, setnx returns True, proceeds; second delivery, same nonce, setnx returns False → reject("replay").

Trade-off: fail-closed vs fail-open with alerting. Fail-closed is right when a forged request causes a state change or a data disclosure. For read-only, idempotent, high-volume endpoints, fail-open with a hard alert can be defensible if the alternative is a full outage, but only there. Note that an unavailable verifier is not a passing verifier: if the key store is unreachable, fail closed too.

Failure modes and detection. Algorithm confusion: alert on any HS* presented with an asymmetric key. Replay: counter on nonce-store collisions per key ID. Clock skew rejecting honest clients: histogram of timestamp delta; if p99 > 20 s, widen tolerance or fix NTP. Parser differential: fuzz the canonicalizer and assert a single parse.

Sizing. Nonce TTL must exceed max skew plus max request lifetime: ±30 s skew + 5 s lifetime → TTL ≥ 35 s; use 300 s to cover retries. At 10k rps that's 3M live keys, ~100 bytes each, ~300 MB in Redis.

What would change my decision: if the endpoint were read-only and idempotent, I'd move the signature check to fail-open with alerting, keeping nonce and authorization fail-closed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Compare zk-SNARKs and zk-STARKs for on-chain verification: trusted setup and its trust assumptions, proof size, verifier gas, and post-quantum resistance, and tell me when you'd pick each.

Answer

Pin down what "on-chain verification" costs before comparing anything: the verifier contract's gas plus the calldata that carries the proof. On Ethereum mainnet nonzero calldata is 16 gas/byte, so proof size is a gas line item, not an aesthetic one. Assume Ethereum mainnet, BN254 precompiles at EIP-1108 pricing, and a Groth16 or FRI-based verifier.

The short answer: Groth16-style SNARKs win on proof size and verifier gas and pay for it with a circuit-specific trusted setup; STARKs remove the setup and the pairing assumption and pay with proofs two to three orders of magnitude larger and verifier gas in the millions. If verification happens once per batch, STARKs are usually fine. If it happens per transaction or per user action, SNARKs are usually the only thing that fits.

Groth16 SNARKPLONK/KZG SNARKFRI STARK
proof size~128 B compressed (2 G1 + 1 G2)~400–900 B~45–200 KB
verifier gas on Ethereum~200–250k~250–300klow millions
setupcircuit-specific: powers of tau + phase 2universal SRS, updatable, reusablenone, transparent
soundness rests onq-PKE / discrete log in the pairing groupKZG / discrete logcollision-resistant hash + FRI parameters
post-quantumbroken by Shorbroken by Shorsurvives Shor; Grover halves hash security

Calldata arithmetic makes the gap concrete. A 200 KB STARK proof is 200,000 × 16 = 3.2M gas before the verifier hashes a single byte. A 128-byte Groth16 proof is about 2k gas of calldata. That is why StarkNet proves with a STARK and then wraps the result in a Groth16 proof for the L1 verifier: the wrapper reintroduces a trusted setup, but only for one circuit.

Trusted setup, precisely. Groth16's phase 2 ceremony produces toxic waste; if every participant colludes, or the randomness is recoverable from the transcript, they can forge proofs for that circuit and nothing on-chain detects it. The assumption is "at least one participant was honest and destroyed their randomness." PLONK's universal SRS is updatable and reusable across circuits, so the ceremony is a one-time cost, but it is still a discrete-log assumption. STARKs have no setup, but "no trusted setup" is not "no trust": you still trust the collision resistance of the hash and the FRI parameters, and you trust the verifier contract to bind the public inputs.

Post-quantum. Pairing-based SNARKs die under Shor because they are discrete log. STARKs are hash-based and survive Shor; Grover gives a quadratic speedup, so a 128-bit hash yields roughly 64-bit quantum security: pick 256-bit hashes. Hash-based SNARKs (Fractal, Aurora) exist but are not what "SNARK" means in practice today.

Failure modes worth naming: a ceremony with one participant or a leaked transcript; a verifier that does not bind public inputs, letting a proof be replayed against a different statement; field mismatch when recursing a STARK into a SNARK (Goldilocks, p = 2^64 − 2^32 + 1, versus BN254); gas griefing by oversized proofs; and calling a system post-quantum when the on-chain wrapper is a pairing SNARK.

Pick: SNARK when verification is on-chain per action, proof size hits calldata cost, and you can run or inherit a credible ceremony. Rollup validity proofs, private transfers. STARK when you control the prover and verify rarely, need transparency or PQ resistance, or want fast proving over small fields: L2 batch proving, STARK-based VMs. Hybrid when you want both: prove with a STARK, wrap in Groth16.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Compare lattice-based and hash-based signatures for blockchain integration, focusing on verification cost, signature size, and stateful vs stateless trade-offs.

Answer

Post-quantum alternatives to ECDSA and Ed25519 shift constraints from compute bottlenecks to bandwidth, state management, and memory overhead.

Core Properties and Metrics

  • Lattice-based schemes (e.g., ML-DSA / Dilithium): Rely on the hardness of Module Learning With Errors (M-LWE) and Module Short Integer Solution (M-SIS). They are stateless. At NIST Security Level 2 (ML-DSA-44), public keys are 1,312 bytes and signatures are 2,420 bytes. Verification requires polynomial ring arithmetic over $\mathbb{Z}_q[X]/(X^{256} + 1)$ with Number Theoretic Transforms (NTT), resulting in fast verification (typically <50 µs on standard x86-64), but demanding significant memory and calldata bandwidth.
  • Stateful hash-based schemes (e.g., LMS, XMSS): Rely strictly on standard cryptographic hash functions (such as SHA-256 or SHAKE-256 per FIPS 180-4). Signatures are compact (~1.5–3 KB), and verification requires evaluating a chain of hashes and a Merkle authentication path (~10–30 hash iterations, sub-10 µs verification). However, each leaf one-time signature (OTS) key must never be reused. Reusing an OTS index completely destroys the security of that leaf and leaks private key material.
  • Stateless hash-based schemes (e.g., SLH-DSA / SPHINCS+): Eliminate state management by constructing hypertree structures with few-time signature schemes (FORS). This removes state synchronization risks but results in signatures spanning 7.8 KB to over 40 KB depending on parameters, though verification remains a straightforward series of hash computations.
                      Comparison Overview
┌─────────────────┬──────────────┬──────────────┬──────────────────┐
│ Scheme Family   │ Signature    │ Public Key   │ Verification     │
│                 │ Size         │ Size         │ Complexity       │
├─────────────────┼──────────────┼──────────────┼──────────────────┤
│ ML-DSA-44       │ 2,420 B      │ 1,312 B      │ NTT + Polys      │
│ (Lattice)       │              │              │ (~40-60 µs)      │
├─────────────────┼──────────────┼──────────────┼──────────────────┤
│ LMS / XMSS      │ ~1.5 - 2.5 KB│ ~32 - 64 B   │ 10-30 Hashes     │
│ (Stateful Hash) │              │              │ (<10 µs)         │
├─────────────────┼──────────────┼──────────────┼──────────────────┤
│ SLH-DSA-128s    │ 7,856 B      │ 32 B         │ 100s of Hashes   │
│ (Stateless Hash)│              │              │ (~1-2 ms)        │
└─────────────────┴──────────────┴──────────────┴──────────────────┘

Blockchain Integration Trade-offs

  1. On-Chain Calldata and Gas / Fee Economics: ECDSA signatures are 64–65 bytes. ML-DSA expands payload footprint by ~37x, while SLH-DSA expands it by >120x. In networks where block sizes are bound to 1–2 MB, accepting 2.4 KB to 8 KB per transaction collapses throughput unless signatures are aggregated (e.g., aggregate commitments or zero-knowledge STARK/SNARK proofs of verification over a batch).

  2. State Management in Wallets and Validators: Stateful hash signatures (LMS/XMSS) are practical for firmware updates and validator signing ceremonies where an append-only counter or monotonically incrementing hardware security module (HSM) guarantees no index reuse. They are unacceptable for distributed end-user wallets, multi-device key sharing, or concurrent transaction submission, because network race conditions or state rollbacks (e.g., restoring a wallet from seed phrase) lead to catastrophic key reuse.

  3. Smart Contract Verification Execution Cost: Hash-based verification executes natively with existing hash precompiles (SHA-256 or Keccak-256). Lattice-based schemes require either dedicated EVM/Wasm precompiles for NTT vector operations or incur millions of gas if implemented in raw bytecode.

Summary Recommendation

Use lattice-based schemes (ML-DSA) for general-purpose user-facing transactions where statelessness and fast verification are mandatory, provided the network layer supports large signatures. Reserve stateful hash-based schemes (LMS) strictly for infrastructure-level, single-signer sequential duties such as consensus epoch root signing or validator key ceremonies.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Prepare a blockchain application for post-quantum migration.

Answer

Core (first 90 seconds)

Assume a cryptographically relevant quantum computer running Shor. That breaks ECDSA (secp256k1, secp256r1), Ed25519, RSA and finite-field DH outright: no key size fixes it. Grover only halves symmetric strength and drops SHA-256 collision resistance from 2^128 to ~2^85, so hashes need larger outputs, not replacement. The migration: replace every discrete-log signature with a post-quantum one (ML-DSA (FIPS 204), SLH-DSA (FIPS 205), or FN-DSA once FIPS 206 finalizes) before keys already public on chain become forgeable. Algorithm choice is the easy part. PQ signatures are 10–100× larger, and the exposure clock is already running for reused addresses.

What breaks, with numbers

Shor: Gidney–Ekerå (2019) put RSA-2048 at 20 million noisy physical qubits and 8 hours; ECC-256 needs ~2,330 logical qubits (Roetteler et al., 2017). Not a 2025 machine: an engineering problem, not a physics one. Grover: AES-128 → 64-bit quantum security, so AES-256; SHA-256 preimage 2^256 → 2^128, collision 2^128 → ~2^85 (BHT). SHA-256 stays fine for most collision uses.

Exposure race

A key is safe until it is on chain. Bitcoin P2PK outputs from 2009 have had public keys exposed for 15 years; any spent address is exposed. Ethereum EOAs reveal the pubkey on the first outgoing transaction: receive-only accounts stay hidden. Migration order: already-public keys, then reused addresses, then the rest. Count UTXOs and accounts per exposure class and sum value.

Sizes

schemepubkeysignature
ECDSA secp256k133 B64 B (raw r‖s)
Ed2551932 B64 B
ML-DSA-44 (FIPS 204)1,312 B2,420 B
ML-DSA-651,952 B3,309 B
Falcon-512 (FIPS 206 draft)897 B~666 B
SLH-DSA-SHA2-128s (FIPS 205)32 B7,856 B

Two consequences decide the design:

  • Bitcoin: MAX_SCRIPT_ELEMENT_SIZE is 520 bytes. ML-DSA-44's 2,420-byte signature is 4.7× over it; even Falcon-512's ~666 B does not fit. Raising the push limit is a prerequisite. Sig+pubkey alone is 3,732 WU against 64 WU for a Schnorr key-path spend: ~58×, so a 4,000,000 WU block holds ~1,070 such spends instead of ~62,000.
  • Ethereum: calldata at 16 gas per nonzero byte makes a 2,420-byte signature ~38,720 gas before verification; against a 30M block gas limit that is ~775 such transactions per block. ECDSA recovery's 3,000-gas precompile has no PQ equivalent: you need a verifier contract or a new account type.

Trade-offs

  • Hybrid (ECDSA + ML-DSA) vs straight PQC. Hybrid costs the sum (~2,484 B) and hedges against a break in ML-DSA, a younger scheme. Hybrid when the asset outlives your confidence in lattice hardness and size is not binding (TLS, code signing); straight PQC when witness or calldata budget binds.
  • Migrate in place vs new chain. In place keeps state and liquidity but needs a consensus change and exposes the old key during the transition. A new chain starts clean but needs a bridge, a bigger target than the signature. In place unless governance cannot ship a fork.
  • Falcon vs ML-DSA. Falcon's ~666 B is 3.6× smaller, but its floating-point Gaussian sampling is hard to make constant-time; ML-DSA is bigger and simpler to implement safely.

Failure modes

  • Migration authorized by the old key. If moving funds needs an ECDSA signature, an attacker with a CRQC moves first. Detection: the authorization path is the primitive being retired. Fix: a flag-day consensus rule or a proof-of-knowledge deadline.
  • Silent downgrade in hybrid negotiation. If the verifier accepts either signature, an attacker strips the PQ half. Detection: log the negotiated algorithm; alert on classical-only verification after cutover.
  • Address reuse. Every spend publishes the key. Detection: per-address spend counts; alert on any funded address with ≥1 spend.
  • Size-driven throughput loss. 2,420 B per input makes a one-input transaction ~2.5 KB. Detection: median transaction size and block weight utilization after the fork.

Migration path

  1. Inventory per chain: signature schemes, which keys are already public, asset lifetimes (5-year vesting vs 30-year cold storage), and who can force an upgrade.
  2. Ship versioned addresses now: bech32m already encodes a version, and Bitcoin witness v2 is reserved.
  3. Hybrid where size allows, straight PQC where it does not.
  4. Test at real sizes: 2,420-byte signatures through mempool policy, fee estimator, hardware wallet, indexer. The 520-byte push limit and the 3,000-gas precompile are where it breaks.
  5. Pre-commit the authenticated migration as a consensus rule with a deadline, so the path does not depend on the key you are retiring.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Plan migration from a blockchain signature algorithm.

Answer

Let me clarify the scenario. We're talking about a public blockchain with immutable history, where every node must be able to verify all historical blocks from genesis. That means we can't just swap algorithms; we need a migration that preserves backward compatibility. My core recommendation is to use a soft fork to introduce the new algorithm alongside the old one, with explicit algorithm identifiers in the signature format, and keep old verification code indefinitely for historical blocks. For new blocks, enforce the new algorithm after activation. This is what Bitcoin did with Taproot, activating Schnorr signatures at block 709632 while keeping ECDSA for old transactions.

The soft fork works by placing the new signature type in a new witness version or script type. Old nodes see it as anyone-can-spend, so they don't validate it. New nodes validate it. This avoids a chain split. Downgrade protection is critical: the algorithm identifier must be part of the signed message. For example, in BIP340, the signature is over a tagged hash that includes the algorithm. If you don't do this, an attacker could take a signature and change the algorithm ID to a weaker one. Detection: if you see a signature that verifies under multiple algorithms, that's a red flag. Operational cost: you need to maintain two verification paths, which increases code size and audit surface.

Failure modes: 1) Downgrade attack: if algorithm ID not signed, attacker can force use of weak algorithm. Detection: signature verifies under unexpected algorithm. Cost: funds stolen. 2) Chain split: if you do a hard fork without coordination, some nodes reject new blocks. Detection: network partition. Cost: loss of consensus. 3) Historical verification failure: if you remove old algorithm support, new nodes can't sync from genesis. Detection: sync fails at old blocks. Cost: new nodes can't join. 4) Replay across chains: if you have two chains with same algorithm, signatures can be replayed. Detection: transaction appears on both chains. Cost: double spend.

Tradeoffs: Soft fork vs hard fork: soft fork is backward compatible, but requires new signature to be designed to look like anyone-can-spend to old nodes. Hard fork requires all nodes to upgrade, but allows cleaner design. Deciding criteria: if you have a large network with many unupgraded nodes, soft fork is safer. If you control the network, hard fork is simpler. Dual-validation vs cross-signing: dual-validation means verifiers accept both algorithms. Cross-signing means signers produce both signatures. For blockchain, dual-validation is necessary for historical blocks, but for new blocks you want to enforce one algorithm to avoid ambiguity. Cross-signing is useful for transactions that need to be valid on both old and new nodes during transition, but it doubles size. Deciding criteria: if you need to interoperate with old verifiers that cannot be upgraded, cross-signing is the only way. If you can upgrade all verifiers, dual-validation is simpler.

Bitcoin's ECDSA is implemented in libsecp256k1, and Ed25519 in libsodium. Here's a table comparing common algorithms:

AlgorithmPubkey sizeSignature sizeUsed in
ECDSA secp256k133 bytes71-72 bytesBitcoin, Ethereum
Ed2551932 bytes64 bytesSolana, Cardano
BLS12-38148 bytes96 bytesEthereum 2.0

And a pseudocode snippet for verification with algorithm identifier:

Python
def verify(sig, msg, algo_id):
    if algo_id not in SUPPORTED_ALGOS:
        return False
    # ensure algo_id is part of signed data
    if not check_algo_id_in_signature(sig, algo_id):
        return False
    return SUPPORTED_ALGOS[algo_id].verify(sig, msg)

The key takeaway: plan for a soft fork with explicit algorithm identifiers, keep old verification forever, and test with real vectors from libsecp256k1 and libsodium.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Design key rotation for an immutable smart-contract system.

Answer

Assumptions. EVM chain, Solidity ^0.8.20, OpenZeppelin Contracts v5.x. The contract has no proxy and no upgrade path, so bytecode and storage layout are fixed. "Key" means the account that satisfies the privileged-call check: an EOA owner, a Safe, or an ERC-4337 smart account.

Core answer. Rotation changes which accounts pass the authorization check on future calls. It never rewrites past state, and it cannot: an immutable contract has no hook to re-evaluate old transactions. So the design question is narrower than it sounds: what mutable authority does the deployed contract already expose, and how do you move that pointer without a window where nobody, or somebody else, holds it.

Four mechanisms, ordered by what they cost you:

mechanismhow rotation happenswhen it's the wrong choice
Ownable2Step (OZ v5)transferOwnership(new) sets _pendingOwner; acceptOwnership() from the new key completessingle owner, no threshold, no delay: fine for a low-value contract, not for a treasury
AccessControl rolesgrantRole(ADMIN_ROLE, new) then revokeRole(ADMIN_ROLE, old)if the role's admin is itself a single key, you have moved the problem, not solved it
Safe multisigaddOwner / removeOwner / changeThreshold, each executed as a Safe transaction signed by the current thresholdraising the threshold before adding signers can lock the Safe out permanently
ERC-4337 smart accountrotate the owner key checked inside validateUserOp; the target contract is never touchedonly helps if the privileged caller is the smart account, not a bare EOA

The two-step pattern is the one people get wrong. It does not stop an attacker who holds the old key: it stops you from bricking the contract by transferring to a typo'd address:

SOLIDITY
// OpenZeppelin Contracts v5.x, Solidity ^0.8.20
contract Vault is Ownable2Step {
    function rotate(address newOwner) external onlyOwner {
        transferOwnership(newOwner); // sets _pendingOwner, emits OwnershipTransferStarted
    }
}

If newOwner is wrong, _owner is unchanged and you call transferOwnership again. With single-step Ownable, that mistake is unrecoverable.

Timelock. Put TimelockController (OZ v5) in front of the owner role: schedule then execute after minDelay. A 48-hour minDelay for routine rotation is a defensible default; the delay is the window in which holders can exit if they disagree. The cost is real: during those 48 hours a compromised old key can still call privileged functions, so pair the timelock with a CANCELLER_ROLE guardian that can cancel a scheduled operation but not execute one, and a pauser with narrower power than the owner.

Failure modes and how you see them.

Front-run on rotation. The old key is compromised and the rotation transaction sits in the public mempool. The attacker front-runs with transferOwnership(attacker) and acceptOwnership() in one contract call. Two-step ownership does not prevent this. Detect it by monitoring OwnershipTransferStarted for a pending owner that is not the expected address, and by watching the owner EOA's nonce. Mitigate by submitting through private orderflow (Flashbots Protect) or by pre-committing keccak256(newOwner, salt) on-chain, waiting, then revealing.

Threshold lockout. A Safe at 3-of-5 raises to 5-of-5 before adding signers; one signer loses their key and the Safe is frozen. Detection is trivial and too late: the Safe's getThreshold() equals getOwners().length. Always add owners first, then raise the threshold.

Signature replay. If the privileged path verifies signatures, the EIP-712 domain separator must include chainId and verifyingContract (EIP-712), and transactions must carry EIP-155 chainId. A cached domain separator computed before a chain split replays across both chains.

What would change the decision. If the privileged caller is already an ERC-4337 account, rotate the key there and leave the contract alone: that is the cheapest correct answer. If the contract exposes no mutable authority at all, rotation is impossible in place and the only path is deploying a successor and migrating state, which is a different project with its own risk profile.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Select and govern a cryptographic dependency.

Answer

Assumptions first: Go 1.22 service, TLS 1.3, Ed25519 signatures, no FIPS requirement, and we control the build. If FIPS validation is required, the answer changes.

Core answer: Start with the standard library. Go's crypto/tls, crypto/ed25519, and crypto/ecdh are maintained by the Go security team, have had constant-time review, and are already in your binary. Reach for a third-party library only when stdlib lacks the primitive: Argon2id for password hashing (golang.org/x/crypto/argon2), or a FIPS-validated module. If FIPS 140-2 is required, GOEXPERIMENT=boringcrypto (Go 1.19+) links BoringSSL's validated module; for 140-3, check the current validation list. Never hand-roll crypto.

Trade-offs and deciding criteria:

optionwhen it winscost
stdlibdefault; algorithms present; no CGOmay lag on new primitives
x/cryptoArgon2, bcrypt, chacha20poly1305smaller review surface than stdlib
boringcryptoFIPS 140-2 requiredCGO, build complexity, slower
vendored forknever for cryptomisses advisories; you own patching
bespokenevertiming side channels, no review

Deciding criteria: algorithm coverage, constant-time guarantees, release cadence, audit history, FIPS status, and API misuse resistance.

Failure modes, detection, cost:

  • Library stops receiving patches. OpenSSL 1.1.1 reached EOL 2023-09-11; a service still linking it misses CVE fixes. Detect with govulncheck ./... or osv-scanner in CI. Cost: a forced emergency upgrade.
  • Silent non-constant-time fallback. Comparing MACs with == leaks timing. Detect by requiring crypto/subtle.ConstantTimeCompare in review and running dudect-style timing tests. Cost: key recovery.
  • Vendored fork drifts. You miss CVE-2014-0160 (Heartbleed) because your fork predates the fix. Detect by diffing your SBOM against upstream tags. Cost: data exposure.

Governance: Pin exact versions in go.mod (e.g., golang.org/x/crypto v0.24.0), verify provenance with cosign verify on release artifacts, and run govulncheck on every PR. Rehearse upgrades: keep a canary that exercises protocol vectors (RFC 8448 TLS 1.3 traces, RFC 8032 Ed25519 vectors) so a version bump is a one-line change plus a green test.

Narrow policy API: Wrap the library so callers cannot pick unsafe parameters.

Go
package crypto

type Signer interface {
    Sign(msg []byte) ([]byte, error)
}

func NewEd25519Signer(priv []byte) (Signer, error) {
    if len(priv) != ed25519.PrivateKeySize {
        return nil, fmt.Errorf("bad key size")
    }
    return ed25519Signer{ed25519.PrivateKey(priv)}, nil
}

Callers get Signer, not ed25519.Sign with a raw key. No algorithm negotiation, no nonce reuse.

What would change the decision: FIPS 140-3 requirement → boringcrypto or a validated module. A new primitive not in stdlib → x/crypto after checking its review status. Hardware-backed keys → use the HSM/KMS API instead of software keys.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Build a cryptographic test and observability plan for a wallet backend.

Answer

Clarify first. What am I protecting? Private key material, and the correctness of every signature and derivation the wallet produces. Assumptions I'd state up front: secp256k1 ECDSA and Ed25519, BIP-32/39 derivation, a KMS or HSM signer behind a signing service, and clients that verify Merkle proofs. If any of those is wrong, the plan changes, so I'd confirm them before writing tests.

The test plan has three layers.

LayerWhat runsWhat it catches
ConformanceWycheproof vectors, NIST CAVP/ACVP, RFC 8032 Ed25519 vectors, BIP-32/39/340 vectorsWrong curve math, missing point validation, bad derivation
DifferentialThe same canonical bytes through two independent libraries (Go and Rust, say)Encoding drift: DER vs raw, endianness, length prefixes
AdversarialMalformed lengths, invalid points, low-S enforcement, nonce reuse, replay, modified Merkle siblingsMalleability, key leakage, cross-chain replay

Wycheproof is the one I'd reach for first: it already encodes the edge cases (points not on the curve, signatures with s > n/2, truncated hashes) that hand-rolled vectors miss. Hand-rolled fixtures are only worth it for your own canonicalization format.

Nonce reuse is the test that must fail the build. Two ECDSA signatures over different messages with the same k share the same r. From those, k = (z1 − z2)/(s1 − s2) mod n, and then d = (s1·k − z1)/r mod n. The private key falls out in a few lines of arithmetic. So I'd force k reuse in a test and assert the signer refuses, and I'd use RFC 6979 deterministic nonces so the path is reproducible rather than dependent on an RNG I can't inspect.

Observability, without secrets. Log key ID, request ID and the message hash: never the message, never key bytes.

MetricAlert threshold
Signer p99 latency> 250 ms for 5 min
Signer error rate> 0.5% over 5 min
Nonce counter monotonicityany reuse pages immediately
Rejected-request categoriesspike > 3× baseline
Key version in useany signing with a deprecated version

Trade-offs and deciding criteria. Deterministic nonces (RFC 6979) remove RNG-failure risk but make a fault reproducible; random nonces need a CSPRNG you can actually trust. Criterion: if you can't guarantee a hardware RNG, go deterministic. HSM versus software signer: the HSM keeps the key non-extractable but adds roughly 10–50 ms per signature and a throughput ceiling; a software signer is faster but the key lives in process memory. Criterion: key non-extraction is worth the latency for anything holding real funds.

Failure modes and how they surface. Nonce reuse shows as two signatures sharing r: caught by the forced-reuse test and by the monotonicity metric. DER malleability shows as a high-S signature accepted: caught by rejecting s > n/2. Cross-chain replay shows as a valid signature on the wrong chain: caught by binding chain ID into the signed payload and watching the rejected-category counter. A forged Merkle proof shows as a path that verifies against the wrong root: caught by a fixture with a modified sibling and a wrong-length path.

Curated: · Written: · Reviewed:

Difficulty: Hard