We come from A dummy blockchain implementation in C (I)

1. Parties

All the ingredients are ready, so now it is time to code the main function. As I already said, it is going to be a voting system. For that, I have created the next enum with all the parties available in the electoral system:

And a function which randomly gets a vote:

1. First block: genesis

In order to create a new element are necessary three steps:

  1. To create the transaction. We create a transaction getting the name of the party.
  2. To create the block with its three fields: previous hash, current hash and a transaction.
  3. To create the node element of the list (the block) and to insert it to the list.

It is common to call the first block in a blockchain as genesis. As there is no previous block, we set the previous block hash to zero

2. Adding votes

Once the first element has been inserted, it is possible to create a loop to create as many blocks as wanted. It follows the three steps from above.

That is all. After compiling and executing we can read the output in the terminal. Each vote (or block) is displayed below the previous one, and it is formed by the hash of the previous vote, the current hash and the name of the voted party. Its current hash it is formed by all the votes previously summited.

You can see the final code here. The core is the snippets showed in the post, but more auxiliary code has been added, mainly to print the linked list.

Ten votes stored in a blockchain

Disclaimer: This article is full of simplifications and abstractions in order to get the fundamental. Although one of the key points of blockchain is that database isn’t stored in any single location but it is shared and transactions are spreading to a P2P network of nodes, here is obviated all the network part.