- Apr 06, 2018
- admin
- 0
How BlockChain works?
The basic concept of blockchain is quite simple: a distributed database that maintains a continuously growing list of ordered records. However, it is easy to get mixed up as usually when we talk about blockchains we also talk about the problems we are trying to solve with them. This is the case in the popular blockchain-based projects such as BitCoin and Ethereum . The term “blockchain” is usually strongly tied to concepts like transactions, smart contracts or cryptocurrencies.
This makes understanding blockchains a necessarily harder task, than it must be. Especially source-code-wisely. Here I will go through a super-simple blockchain I implemented in 200 lines of Javascript called NativeChain.
Block structure
The first logical step is to decide the block structure. To keep things as simple as possible we include only the most necessary: index, timestamp, data, hash and previous hash.
The hash of the previous block must be found in the block to preserve the chain integrity.
Block hash
The block needs to be hashed to keep the integrity of the data. A SHA-256 is taken over the content of the block. It should be noted that this hash has nothing to do with “Mining“, since there is no “Proof of work” problem to solve.
Generating a block
To generate a block we must know the hash of the previous block and create the rest of the required content (= index, hash, data and timestamp). Block data is something that is provided by the end-user.
Storing the blocks
A in-memory Javascript array is used to store the blockchain. The first block of the blockchain is always a so-called “genesis-block”, which is hard coded.
Validating the integrity of blocks
At any given time we must be able to validate if a block or a chain of blocks are valid in terms of integrity. This is true especially when we receive new blocks from other nodes and must decide whether to accept them or not.
Choosing the longest chain
There should always be only one explicit set of blocks in the chain at a given time. In case of conflicts (e.g. two nodes both generate block number 72) we choose the chain that has the longest number of blocks.