|
| 1 | +import time |
| 2 | + |
| 3 | +from crypto_hash import crypto_hash |
| 4 | + |
| 5 | +class Block: |
| 6 | + """ |
| 7 | + Block: a unit of storage. |
| 8 | + Store transactions in a blockchain that supports a cryptocurrency. |
| 9 | + """ |
| 10 | + def __init__(self, timestamp, last_hash, hash, data): |
| 11 | + self.timestamp = timestamp |
| 12 | + self.last_hash = last_hash |
| 13 | + self.hash = hash |
| 14 | + self.data = data |
| 15 | + |
| 16 | + def add_block(self, data): |
| 17 | + self.chain.append(Block(data)) |
| 18 | + |
| 19 | + def __repr__(self): |
| 20 | + return ( |
| 21 | + 'Block(' |
| 22 | + f'timestamp: {self.timestamp}, ' |
| 23 | + f'last_hash: {self.last_hash}, ' |
| 24 | + f'hash: {self.hash}, ' |
| 25 | + f'data: {self.data})' |
| 26 | + ) |
| 27 | + |
| 28 | + @staticmethod |
| 29 | + def mine_block(last_block, data): |
| 30 | + """ |
| 31 | + Mine a block based on the given last_block and data. |
| 32 | + """ |
| 33 | + timestamp = time.time_ns() |
| 34 | + last_hash = last_block.hash |
| 35 | + hash = crypto_hash(timestamp, last_hash, data) |
| 36 | + |
| 37 | + return Block(timestamp, last_hash, hash, data) |
| 38 | + |
| 39 | + @staticmethod |
| 40 | + def genesis(): |
| 41 | + """ |
| 42 | + Generate the genesis block. |
| 43 | + """ |
| 44 | + return Block(1, 'genesis_last_hash', 'genesis_hash', []) |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + genesis_block = Block.genesis() |
| 49 | + block = Block.mine_block(genesis_block, 'foo') |
| 50 | + print(f'block: {block}') |
| 51 | + |
| 52 | +if __name__ == '__main__': |
| 53 | + main() |
0 commit comments