#C14238. Simple Blockchain Simulator
Simple Blockchain Simulator
Simple Blockchain Simulator
In this problem, you are required to simulate a simple blockchain. A blockchain is a chain of blocks, where each block contains an index, timestamp, data, a reference to the previous block's hash, and its own hash computed using the SHA-256 algorithm.
The blockchain starts with a genesis block that has index 0, data "Genesis Block", and a previous hash of "0". You will receive a series of commands to either add a block, tamper with a block's data, or validate the blockchain.
The commands are as follows:
- 1 <data>: Add a new block with the provided transaction data. The new block's index will be one more than the latest block, and its previous hash will be the hash of the latest block.
- 3 <index> <data>: Tamper with the block at the specified index by changing its data to the provided data. Note: This command does not update the block's hash, which should cause the chain to become invalid.
- 2: Validate the blockchain. Print
True
if the blockchain is valid orFalse
otherwise. To be valid, for every block (except the genesis block), the following must hold:
\(\text{current.hash} = SHA256(\text{current.index} + \text{current.timestamp} + \text{current.data} + \text{current.previous_hash})\), and
\(\text{current.previous_hash} = \text{previous.hash}\).
You should read the input from stdin
and write the results to stdout
. There may be multiple validate commands; output a result for each as they appear.
Note: The SHA-256 hash must be represented as a 64-character hexadecimal string.
inputFormat
The first line of input contains an integer n representing the number of commands. Each of the following n lines contains a command. The commands have the following format:
- 1 <data>: Add a block with the given transaction data.
- 3 <index> <data>: Tamper with the block at the specified index by changing its data.
- 2: Validate the blockchain. (This command requires output.)
The transaction data is provided as a single word or a string without newline characters.
outputFormat
For every validate command (command type 2), output either True
or False
on a new line to indicate whether the blockchain is valid.
3
1 Transaction1
1 Transaction2
2
True
</p>