Implement a tamper-evident blockchain with SHA-256 hash links and validation

Quick Overview

Implement a small blockchain class where each block stores its data, its SHA-256 hash and the previous block's hash, with methods to append blocks, read hashes, tamper with data and validate the chain. It tests hash chaining, tamper detection and which blocks validation has to cover.

Implement a tamper-evident blockchain with SHA-256 hash links and validation

Company: Gemini

Role: Software Engineer

Category: Software Engineering Fundamentals

Difficulty: easy

Interview Round: Other

Design a simple blockchain data structure. A blockchain is an ordered list of blocks, where each block stores some `data`, its own cryptographic `hash`, and the `hash` of the previous block. This linkage makes the chain tamper-evident: changing a block's data leaves its stored hash stale, and recomputing that hash breaks the link stored in the next block. Implement a `Blockchain` class that supports appending new blocks, retrieving a block's hash by index, tampering with an existing block's data (for testing integrity), and validating the integrity of the entire chain. The chain is initialized with a single genesis block at index 0, whose `data` is the string `"genesis"` and whose `previousHash` is the string `"0"`. Each block's hash is the lowercase hex digest of SHA-256 applied to the UTF-8 bytes of its `index`, `data` and `previousHash`, joined in the format `f"{index}|{data}|{previousHash}"`. Validation succeeds if and only if every block's stored hash equals the hash recomputed from its current contents, and every non-genesis block's stored `previousHash` equals the stored hash of the preceding block. Implement the following methods: - `addBlock(data: str) -> int`: Append a new block containing the given data, linking it to the current tail. Returns the index of the newly added block. - `getHash(index: int) -> str`: Return the stored SHA-256 hex hash of the block at the given index. - `tamper(index: int, newData: str) -> None`: Overwrite the data field of the block at the given index without recomputing any hashes. Used to simulate tampering for integrity testing. - `isValid() -> bool`: Return `True` if the chain is intact: every block's stored hash matches its recomputed hash, and every non-genesis block's `previousHash` matches the preceding block's stored hash. Example 1: ```text Input: ["Blockchain", "addBlock", "addBlock", "isValid"] [[], ["alice→bob: 10"], ["bob→carol: 5"], []] Output: [null, 1, 2, true] ``` The constructor creates a chain holding only the genesis block at index 0. The two `addBlock` calls append blocks at indices 1 and 2, each recording the hash of the block before it. `isValid` returns `true` because every stored hash matches its recomputed value and every link matches. Example 2: ```text Input: ["Blockchain", "addBlock", "addBlock", "tamper", "isValid"] [[], ["tx1"], ["tx2"], [1, "tx1-hacked"], []] Output: [null, 1, 2, null, false] ``` `tamper` replaces the data of block 1 and leaves its stored hash as it was. Recomputing the hash of block 1 from its new data gives a different digest, so `isValid` returns `false`. ```hint What tamper leaves behind After `tamper`, work out which stored value no longer agrees with the block's contents and which check would notice. Then ask whether any link between blocks has changed. ``` ### Constraints & Assumptions - `1 <= len(data) <= 1000` - `1 <= number of blocks <= 10^4` - Hashes are computed with SHA-256 over the block's `index`, `data` and `previousHash`. - The genesis block has `previousHash` equal to `"0"`. ### Clarifying Questions to Ask - What should `getHash` and `tamper` do for an index outside the chain: raise an error or return a sentinel? - Can `tamper` target the genesis block, and should that make the chain invalid? - Should `isValid` return only a boolean, or also report which block failed? - Can `data` contain the `|` separator, and does that affect the hash format? ### What a Strong Answer Covers - The block representation and the exact hash payload, including how the genesis block is built. - How `addBlock` links a new block to the tail, and why `tamper` must leave the stored hashes alone. - Both checks in `isValid`, which kind of change each one catches, and which blocks the validation loop has to cover. - Index handling and edge cases such as tampering with the genesis block or the last block. - Time and space complexity in terms of the number of blocks and the length of their data. ### Follow-up Questions - If someone edits a block and also recomputes its stored hash, which check catches it, and what would they have to rewrite to pass validation? - How would you make `isValid` report the first broken block, and avoid rescanning the whole chain on every call? - How would you add proof of work so that rewriting history becomes expensive? - When can a delimiter-joined payload like this one let two different blocks hash the same input, and how would you prevent it?

Overview: Implement a small blockchain class where each block stores its data, its SHA-256 hash and the previous block's hash, with methods to append blocks, read hashes, tamper with data and validate the chain. It tests hash chaining, tamper detection and which blocks validation has to cover.

Gemini logo
Gemini
Nov 25, 2026
easySoftware EngineerOtherSoftware Engineering Fundamentals
0
0

Design a simple blockchain data structure. A blockchain is an ordered list of blocks, where each block stores some data, its own cryptographic hash, and the hash of the previous block. This linkage makes the chain tamper-evident: changing a block's data leaves its stored hash stale, and recomputing that hash breaks the link stored in the next block.

Implement a Blockchain class that supports appending new blocks, retrieving a block's hash by index, tampering with an existing block's data (for testing integrity), and validating the integrity of the entire chain.

The chain is initialized with a single genesis block at index 0, whose data is the string "genesis" and whose previousHash is the string "0". Each block's hash is the lowercase hex digest of SHA-256 applied to the UTF-8 bytes of its index, data and previousHash, joined in the format f"{index}|{data}|{previousHash}". Validation succeeds if and only if every block's stored hash equals the hash recomputed from its current contents, and every non-genesis block's stored previousHash equals the stored hash of the preceding block.

Implement the following methods:

  • addBlock(data: str) -> int : Append a new block containing the given data, linking it to the current tail. Returns the index of the newly added block.
  • getHash(index: int) -> str : Return the stored SHA-256 hex hash of the block at the given index.
  • tamper(index: int, newData: str) -> None : Overwrite the data field of the block at the given index without recomputing any hashes. Used to simulate tampering for integrity testing.
  • isValid() -> bool : Return True if the chain is intact: every block's stored hash matches its recomputed hash, and every non-genesis block's previousHash matches the preceding block's stored hash.

Example 1:

Input:
["Blockchain", "addBlock", "addBlock", "isValid"]
[[], ["alice→bob: 10"], ["bob→carol: 5"], []]

Output: [null, 1, 2, true]

The constructor creates a chain holding only the genesis block at index 0. The two addBlock calls append blocks at indices 1 and 2, each recording the hash of the block before it. isValid returns true because every stored hash matches its recomputed value and every link matches.

Example 2:

Input:
["Blockchain", "addBlock", "addBlock", "tamper", "isValid"]
[[], ["tx1"], ["tx2"], [1, "tx1-hacked"], []]

Output: [null, 1, 2, null, false]

tamper replaces the data of block 1 and leaves its stored hash as it was. Recomputing the hash of block 1 from its new data gives a different digest, so isValid returns false.

Constraints & Assumptions

  • 1 <= len(data) <= 1000
  • 1 <= number of blocks <= 10^4
  • Hashes are computed with SHA-256 over the block's index , data and previousHash .
  • The genesis block has previousHash equal to "0" .

Clarifying Questions to Ask Guidance

  • What should getHash and tamper do for an index outside the chain: raise an error or return a sentinel?
  • Can tamper target the genesis block, and should that make the chain invalid?
  • Should isValid return only a boolean, or also report which block failed?
  • Can data contain the | separator, and does that affect the hash format?

What a Strong Answer Covers Guidance

  • The block representation and the exact hash payload, including how the genesis block is built.
  • How addBlock links a new block to the tail, and why tamper must leave the stored hashes alone.
  • Both checks in isValid , which kind of change each one catches, and which blocks the validation loop has to cover.
  • Index handling and edge cases such as tampering with the genesis block or the last block.
  • Time and space complexity in terms of the number of blocks and the length of their data.

Follow-up Questions Guidance

  • If someone edits a block and also recomputes its stored hash, which check catches it, and what would they have to rewrite to pass validation?
  • How would you make isValid report the first broken block, and avoid rescanning the whole chain on every call?
  • How would you add proof of work so that rewriting history becomes expensive?
  • When can a delimiter-joined payload like this one let two different blocks hash the same input, and how would you prevent it?