Blockchain – An introduction with Object Pascal overview

A Needed introduction

The Blockchain technology is based on a combination of three concepts that have existed for some time: peer-to-peer technology, cryptography and game theory.

Peer-to-peer technology: torrents use the p2p technology for distribution of information across the nodes. Nodes on the blockchain network communicate via p2p technology and store information about the blockchain locally. Both concepts (blockchain and torrents) don’t need a central server in order to operate.

Cryptography: ensures that transparency and privacy are achieved. Cryptographic hash functions encrypt individual transactions. Blocks and transactions are cryptographically connected, hence keeping the blockchain immutable. Miners check every transaction happening on the network, so cheating is impossible.

Game theory: there is a need of economic incentive in order to participate in the network. Miners would not approve transactions on the blockchain for free. The Bitcoin blockchain pays the miners and this way they stay “motivated”.

Besides others bit more deep differences, when we talk about torrent and blockchain, the last is all about preventing double spending or in other words preventing people from copying information. Torrents are all about copying information. More copies ensure that you have more seeders. No information gets lost in a blockchain. That is not the case with torrents, where an old torrent could loose all its seeders and disappear from the network.

Nowadays the word Blockchain is one of the most used by the media, searched and researched, mostly because of the Bitcoin cryptocurrency success, or what I would call the enthusiasm on it. The Bitcoin in 2017 recorded a market valorization about 900% raising its price to top about US$ 20,0000.00 ATH (at the highest) in December. As virtual coin, the Bitcoin is a software coin – virtual coin, based on a computer algorithm capable of record its transactions and ensure safety by sharing the transaction database among the network. The technology behind the Bitcoin is the Blockchain and besides the Bitcoin and there a lot of other alternative coins (A.K.A. altcoins) that makes use of the same technology, as to mention the Ethereum, Litecoin, Ripple and etc (there are more than 1,0000 coins already in the world).

Blockchain is not restricted to cryptocurrency and/or financial issues, indeed there a number of applications and areas which can be applied, such as smart property, smart contracts , healthcare, music, government, government agencies, academics, public value, passport, personal ids, birth certificates, etc.

“What can blockchain do in the real world?” is becoming the dominant question. 

So, for a developer, understand it today can be a differential for tomorrow.

The Blockchain in itself is quite simple, it is a distributed database that maintains a continuously growing list of ordered records, in a nutshell. The term “blockchain” is usually strongly tied to concepts like transactions, smart contracts or cryptocurrencies. That said, this can drive to understanding that blockchains are necessarily harder task, especially when we think about source-code-wisely.

As the name says, “blockchain” is a chain-of-blocks, tied by hashing the previous block. The initial zero block is commonly designated as “genesis-block”.


Above a simple view of a transaction block.

Each data block will be marked with a signature, it is called “to hash”. To hash a block is to compute its hash function with a secure SHA-2/SHA-256 algorithm, enforcing strong collision resistance.

Man at work!

There a lot of ways you can create a block, for the sake of this article I will try to keep it as easy as possible. Basically, we will use a class and a generic list to support the data – the “blockchain”. We will not dig on the peer-to-peer implementation either work-of-proof (nonce, difficulty and others) or miner. That kind of information (how to) can be more comprehensible from this point if you search for yourself, there are a lot of literature about.

Bellow we have the Block, the place where we will store our data. The data storage in this case is a simple string. We have single method inside the block to calculate its hash value and store.

type
    TBlock = class
        Index: integer;
        PreviousHash: string;
        Timestamp: Int64;
        Data: String;
        Hash: String;
    private
        procedure CalculateBlockHash;
 end;

Now, the process to create the chain implies first to create a initial node, the genesis block as it is called. We will create the genesis block as such:

CreateNextBlock(0, '0', 'genesis-block', Now());

The parameters are:
– Index: integer;
– PreviousHash: string;
– Data: string;
– Timestamp: TDateTime;

Please note that we are using the Timestamp parameter as TDatetime, but the class itself is declared as Int64. That’s because we will convert the TDateTime to Unix time which is the common format used as timestamp, for that is used the function DateTimeToUnix(). The CreateNextBlock is how bellow:

procedure CreateNextBlock(Index: integer; PreviousHash, Data: string; Timestamp: TDateTime);
var
   Block: TBlock;
   Hash: String;
begin
   // create the block
   Block := TBlock.Create;
   Block.Index := index;
   Block.PreviousHash := PreviousHash;
   Block.Data := Data;
   Block.Timestamp := DateTimeToUnix(Timestamp);

   // calculate the hash for new block
   Block.CalculateBlockHash;

   // add block to the chain
   BlockChain.Add(index, Block);
end;

Once the Block is created it is put into a generic list referred as “Blockchain” 🙂 For that list we are using a TDictionary type, so it is defined as:

BlockChain: TDictionary<integer, TBlock>

Now we have our firstborn block and henceforward we just need to feed the Blockchain with new data. A new block can be create calling such code:

procedure CreateNewBlock(TheData: String);
var
   Block: TBlock;
begin
   // get previous block information
   Block := BlockChain.Items[BlockChain.Count - 1];
   CreateNextBlock(Block.Index + 1, Block.Hash, TheData, Now());

   // check if new block is valid
   Block := BlockChain.Items[BlockChain.Count - 1];

   if not ValidateBlock(Block) then
      ShowMessage('Invalid block!');
end;

Now you can see a new function here, ValidateBlock(), because we must ensure the block is valid. This is true especially when we receive new blocks from other nodes and must decide whether to accept them or not. Of course it is not hardly needed when creating a very new block here but for real world solution it is almost mandatory. As always, it is very simple method:

function ValidateBlock(Block: TBlock): boolean;
var
    PrevBlock: TBlock;
begin
  if Block.Index > 0 then
  begin
      Result := False;
      PrevBlock := BlockChain.Items[Block.Index - 1];
      
      // invalid index
      if (PrevBlock.Index + 1 <> Block.Index) then
         Exit;

      // invalid previous hash
      if (PrevBlock.Hash <> Block.PreviousHash) then
         Exit;
     
      // validate block hash
      if (Block.Hash <> Block.CalculateBlockHash) then
         Exit;
  end;
  Result := True;
end;

There are 3 necessary steps into the validation process: check the index, check the previous hash and check the current hash. Failure of either of them render the block invalid.

Finally, here we have the CalculateBlockHash method. It is also far simple, basically you have to get the index, previous hash, time stamp and data, concatenate everything and calculate the SHA-256 hash:

function TBlock.CalculateBlockHash: String;
begin 
      Hash := THashSHA2.GetHashString(Index.ToString + PreviousHash + Timestamp.ToString + Data);
      Result := Hash;
end;

Tadaá! We are using THashSHA2 record that implements the SHA-2 hash type. Other languages will require you to import SHA256 support, as hashlib for Phyton or the crypto-js library for JavaScript.

That’s it. Now, I think you can dig on by yourself and develop you own blockchain solution or at least understand a bit more how it works. I hope that I’ve helped you on this.

2018 By Magno Lima

References: https://bitcoin.org/bitcoin.pdf; https://blockgeeks.com/guides/blockchain-applications/; http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Hash.THashSHA2; http://docwiki.embarcadero.com/Libraries/Tokyo/en/System.Hash.THashSHA2

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *