Blockchain – An introduction with Object Pascal by Magno Lima

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Blockchain – An introduction with Object Pascal
Magno Lima 2018. Rev Mai/2020
[SHOWTOGROUPS=4,20]
Blockchain – An introduction with Object Pascal
Magno Lima 2018. Rev Mai/2020

This article does not intend to explain the blockchain in deep, because you can find a lot of information out there, but instead we will focus on a very simple application using Object Pascal, for this purpose I think you could also gain an special understanding on how it works.

A needed introduction to the Blockchain technology is necessary here.

The Blockchain technology application can be widely used, not restrict to cryto currencies like Bitcoin, Ethereum and hundred others. There are already a lot of direct application cases using the blockchain. Applications with a vast range of use like:

  • Secure sharing of medical data
  • Music royalties tracking
  • Cross-border payments
  • Real-time IoT operating systems
  • Personal identity security
  • Anti-money laundering tracking system
  • Supply chain and logistics monitoring
  • Voting mechanism
  • Advertising insights
  • Original content creation
  • Cryptocurrency exchange
  • Real estate processing platform
With a very quick world in transformation the Blockchain is no more a niche of programming but you should be serioulsy consider it, at least understand how it works.

Basically the Blockchain technology is a system of recording information in a way that makes it difficult or almost impossible to change it.

A blockchain is essentially a digital ledger of transactions that is duplicated and distributed across the entire network of computer systems on the blockchain. Each block in the chain contains a number of transactions, and every time a new transaction occurs on the blockchain, a record of that transaction is added to every participant’s ledger. The decentralised database managed by multiple participants is known as Distributed Ledger Technology (DLT).

Blockchain is a type of DLT in which transactions are recorded with an immutable cryptographic signature called a hash.

Blockchain consists of three important concepts: blocks, nodes and miners.

Each block is linked to the previous one via the last hash number, this is the block address. The very first block, the seed of a whole chain, is called Genesis Block.

block-chain-small-300x223.png


Below is representation of the genesis block as it appeared in a comment in an old version of Bitcoin (Для просмотра ссылки Войди или Зарегистрируйся). The first section defines exactly all of the variables necessary to recreate the block. The second section is the block in standard print block format, which contains shortened versions of the data in the first section.

GetHash() = 0x000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f hashMerkleRoot = 0x4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33btx New.vin[0].scriptSig = 486604799 4 0x736B6E616220726F662074756F6C69616220646E6F63657320666F206B6E69
7262206E6F20726F6C6C65636E61684320393030322F6E614A2F33302073656D695420656854
txNew.vout[0].nValue = 5000000000
txNew.vout[0].scriptPubKey = 0x5F1DF16B2B704C8A578D0BBAF74D385CDE12C11EE50455F3C438EF4C3FBCF649B6DE611FEA
06279A60939E028A8D65C10B73071A6F16719274855FEB0FD8A6704 OP_CHECKSIG block.nVersion = 1
block.nTime = 1231006505
block.nBits = 0x1d00ffff
block.nNonce = 2083236893 CBlock(hash=000000000019d6, ver=1, hashPrevBlock = 00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e
63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) vMerkleTree: 4a5e1e
It can looks like scary, but don’t be afraid, to understand that you must need to know how this block is formed.

The fundamental structure of a block, in the blockchain, has four main parts:

  1. Timestamp – in milliseconds, responsible to indicate the time of the block creation
  2. Last Hash – the identification of the last block (which address will link one each other)
  3. Hash – the hash computation of the block itself
  4. Data – the payload of data we want to handle
I guess the first 3 parts are very self-explanatory, a date with time and two hash addresses, but the data is exactly what it means, this is your data, what can be a number, a string, an object, a record, this is with you.

So now we will enter in the programming level and see how it works. This article won’t treat about the P2P data transmission but solo to the blockchain concept creation.

Programming a blockchain in Object Pascal

The first thing we should do is to create a block structure. Here, for the sake of simplicity we will work with a simple class to store our data. Take the idea behind it all and make your own blockchain! (If you really interested in a real world project using Pascal and blockchain, I suggest to take a look in the PascalCoin project – Для просмотра ссылки Войди или Зарегистрируйся).

Our Block Structure

Let’s take the class below to use as our block:

type
TBlock = class
Index: integer;
Hash: String;
PreviousHash: string;
Timestamp: Int64;
Data: String;
private
function CalculateBlockHash: String;
end;
Our Data will be a simple string, here you could extend it to whatever you want.

The Methods

Now we must provide some functions to deal with this. Our class has the CalculateBlockHash(), so here it is:

{ TBlock }
function TBlock.CalculateBlockHash: String;
begin
Hash := THashSHA2.GetHashString(Index.ToString + PreviousHash + Timestamp.ToString + Data);
Result := Hash;
end;
The result is a simple sum of the whole payload. As an example, you can transform or apply your own method to calculation there, but here we are following one rule.

The THashSHA2 can be used when you declare the System.Hash unit to your project uses. With newest Delphi (Rio and above) you could use an inline declaration so that would be this way:

function TBlock.CalculateBlockHash: String;
begin
var Hash := THashSHA2.GetHashString(Index.ToString + PreviousHash + Timestamp.ToString + Data);
Result := Hash;
end;
To understand a bit more why should I consider using inline declarations, take a read here: Для просмотра ссылки Войди или Зарегистрируйся

Now, back to our project we should create a function to be responsible in validating our block, this is very important and it is the one of the major reasons to use the blockchain. Be able to validate a block is the strength behind this technology.

The ValidateBlock() is also another very simple function, and again you always can think beyond and expand it all.

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;
// validade block hash
// here we repeat the function as it is intend to
if (Block.Hash <> Block.CalculateBlockHash) then
Exit;
end;
Result := True;
end;
And that’s it! There are 3 tests that a block should pass to granted as a valid block: 1) if it’s index (a kind of serialization) if in a correct sequence, 2) if the block we are testing is point to its correct ancestor (check the last hash) and 3) we calculate again by ourselves if the block hash value is what it is saying it is.

The Chain reaction

As we are talking about chains, so we should keep our data in somewhere. We are using a generic list here:

var
BlockChain: TDictionary<integer, TBlock>;
Also we will have the Genesis Block, so we declare a constant like:

const
GENESIS_BLOCK = ‘genesis-block’;
This is simple as it should be. The Dictionary will carry all our chain of blocks.

To perform a block creation we do as below:

function CreateNextBlock(Index: integer; PreviousHash, Data: string; Timestamp: TDateTime): Boolean;
var
Block: TBlock;
Hash: String;
begin
Result := False;
// The genesis block was already created
if (Index <> 0) and (Data = GENESIS_BLOCK) then
Exit;
// create the new 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);
Result := True;
end;
This function is using 4 parameters (we could create a class or record and pass here, but the intention is to keep it as simple as possible), the Index, the previous Hash, the Data and a date time value. Once we create the Block it will be stored into the BlockChain generic list.

We are not checking there if the index is valid or not, you can (should) do it.

Notice that this function CreateNextBlock() is inserting the new block into the chain list, well the CreateNextBlock() should return a block and not deal with it as I am showing here, and the calling routine it the one that should take the block and insert into the list, but again this

To ignite our chain reaction we need to create the Genesis Block. Here we will identify it simply as a string written “genesis-block”, as our data a string type (again in a real world programming you should ensure that no other genesis block enter into the chain. Let’s do it:

CreateNextBlock(0, ‘0’, GENESIS_BLOCK, Now());
From here we could simply add new data to our blockchain repeating the statement below, but we always must know the previous block hash. We can do this:

var
Block: TBlock;
begin
// get previous block information
Block := BlockChain.Items[BlockChain.Count – 1];
if CreateNextBlock(Block.Index + 1, Block.Hash, Edit1.Text, Now()) then
begin
// check if new block is valid
// get new block
Block := BlockChain.Items[BlockChain.Count – 1];
if ValidateBlock(Block) then
ListBlockChain()
else
ShowMessage(‘Invalid block!’);
end
else
ShowMessage(‘Invalid block! Genesis block already exists.’);
end;
Done!

I hope that this small article could be useful for you, if not intended to create your own cryptocoin or smart contracts, at least understand the basic fundamentals of the blockchain technology.
[/SHOWTOGROUPS]
 
Последнее редактирование модератором: