In the previous post, we introduced mining and created the genesis block. Let's mine more blocks and 'chain' them together - we call this the blockchain.

Initialization

The genesis block is set as the first block in the blockchain. We also keep a running counter how many blocks have been mined.

genesis_hash, genesis_block = init_genesis_block()

blockchain = genesis_block
block_counter = 1

As before, we use port numbers to represent accounts.

port = 7000

Let's review steps 1 to 4 in mining a new block, introduced previously.

  1. Get the hash of the previous block, and combine that with the timestamp and nonce to create a header.
  2. Hash the header twice.
  3. If the first two bytes are not zero, increment the nonce and try again.
  4. If the first two bytes are zero, create a reward transaction and combine that with the header to create a new block.

In addition, we introduce steps 5 to 6. We run all the steps to mine up to 10 blocks.

  1. Append the new block to the blockchain.
  2. Re-initialize the previous hash, timestamp and nonce values to mine the next block.

For our purposes, the first non-zero previous hash is the hash of the genesis block. We set up the loop to iterate through 1,000 nonce values at a time - we'll see why in the next post. Let's also print out (without delimiters) the block hash every time a new block is mined.