A dummy blockchain implementation in C (II)

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:

typedef enum party_code_t {
} party_code;

And a function which randomly gets a vote:

static party_code get_vote()
    int r = rand();
    return r%MAX_PARTIES;

1. First block: genesis

    NODE *head;
    DATA genesis_element;

    transaction genesis_transactions = get_vote()};
    block_t genesis_block = {0, string_hash(genesis_transactions), genesis_transactions};
    genesis_element.info = genesis_block;
    head = add(head, genesis_element);

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


    int previous_hash = genesis_element.info.previous_block_hash;
    for(i=0;i<nvotes;i++) {

        DATA *el
        block_t *b;
        transaction t = {get_vote()};

        b->block_hash = string_hash(t);
        b->transactions = t;
        el->info = *b;
        previous_hash = b->block_hash;
        head = add(head, *el);

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.


No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *