
Let’s code! Blockchain Tutorial. Milestone # 3
As a blockchain developer, you will face tons of challenges on the back-end. Creating and maintaining a public blockchain is not easy due to a number of reasons.
- Reason # 1: Security
Blockchains, as David Schwartz says, should be strengths. First, the code is public and is open for all to see. Anyone can look at the code and look for errors and vulnerabilities. However, unlike other open source resources, the disadvantage of finding vulnerabilities in the blockchain code is enormous. Any programmer can hack and get away with the possibility of millions and millions of dollars. Due to these legitimate safety concerns, blockchain development is usually very slow.
- Reason # 2: Resource Management
It is important to keep up with the network. You can not stay far behind and not keep up with all the demands of the network. It must be well equipped to handle local and remote queries.
- Reason # 3: performance
The blockchain must always work at its highest possible capacities, but for that to happen, the chosen language must be extremely versatile. The problem is that there are certain tasks in the blockchain that are parallelizable, while there are some tasks that can not be done in parallel.
A good example of a “parallelizable” task is digital signature verification. All you need to verify the signature is the key, the transaction and the signature. With only three data you can perform checks in parallel.
However, not all functions in a chain of blocks should be done that way. Think of the execution of transactions in itself. Multiple transactions can not be executed in parallel; It should be done one at a time to avoid mistakes like double spending. Some languages are good for parallel operations, while others are good at non-parallel operations.
- Reason # 4: Isolation
What is the deterministic behavior?
If A + B = C, then regardless of the circumstances, A + B will always be equal to C. That is called deterministic behavior.
The hash functions are deterministic, which means that the hash of A will always be H (A).
Then, in blockchain development, all transaction operations must be deterministic. You can not have a transaction that behaves in one way and then behave differently the next day. Similarly, you can not have smart contracts that work in two different ways on two different machines.
The only solution for this is isolation. Basically, it isolates its contracts and intelligent transactions from non-deterministic elements.
There are some languages that satisfy most of these needs. If you are a blockchain developer, you definitely need to have some basic knowledge of C ++ and JavaScript.
While C ++ may seem a little outdated, the truth is that it satisfies wonderfully all the functionalities that we have described above. In fact, Satoshi Nakamoto wrote the Bitcoin source code in C ++.
Along with HTML and CSS is one of the three main technologies in World Wide Web Content Production. Javascript is generally used to create highly interactive web pages.
So, now we will see how to create a very simple blockchain using Javascript.
How do we make a block? What does a simple block consist of? In our simple cryptocoin that we are going to make (Let’s call it “BlockCoin”), each block will have the following pieces of information:
- Index: To know the block number.
- Timestamp: To know the time of creation.
- Data: The data inside the block.
- Previous Hash: The hash of the previous block.
- Hash: The Hash of the current block.
Before we continue. You need to understand certain terms that we are going to use in our program:
- This: The “this” keyword is invoked inside a function and enables you to access the values inside a specific object that calls that particular function.
- Constructor : A constructor is a special function which can help create and initialize an object within a class. Each class is restricted to only one constructor.
Now that’s done, let’s start making our block.
Creating the Block
[code lang=”js”]const SHA256 = require ( "crypto-js / sha256" );
class block
{
constructor (index, timestamp, data, previousHash = ” )
{
this . index = index;
this . previousHash = previousHash;
this . timestamp = timestamp ;
this . data = data;
this . hash = this . calculateHash ();
}
calculateHash ()
{
return SHA256 (this . index + this . previousHash + this . timestamp + JSON . stringify (this . data)) . Chain();
}
}[/code]
Code Analysis
Ok, so this is right here is a block. So, in the first line of the code, we called the crypto-js library because the sha256 hash function is not available in JavaScript.
Next, we invoked a constructor inside the class to call for objects which will have certain values. The thing that probably catches your eye is the calculateHash () function. Let’s see what exactly is it doing.
In a block, we take all the contents and hash them to get the hash of that particular block. We are using the JSON.stringify function to turn the data of the block into a string to hash it.
Ok, so we have the block ready and good to go. Now let’s connect the blocks together into a blockchain.
Creating the blockchain: Becoming A Blockchain Developer
[code lang=”js”]Blockchain class
{
// Section 1 Genesis block creation
builder()
{
this . chain = [this . createGenesisBlock ()];
}
createGenesisBlock ()
{
return new Block ( 0 , "01/01/2017" , "Genesis block" , "0" );
}
// section 2 adding new blocks
getLatestBlock ()
{
return this . chain [this . chain . length – 1 ];
}
addBlock (newBlock) {
Newblock . previousHash = this . getLatestBlock () . hash;
Newblock . hash = newBlock . calculateHash ();
this . chain . push (newBlock);
}
// section 3 validating the chain
isChainValid ()
{
for (let i = 1 ; i < this . chain . length; i ++ )
{
const currentBlock = this . chain [i];
const previousBlock = this . chain [i – 1 ];
if (currentBlock . hash ! == currentBlock . calculateHash ()) {
return false;
}
if (currentBlock . previousHash ! == previousBlock . hash)
{
return false;
}
}
return true;
}
}[/code]
Code Analysis
Ok, so a lot of things are going on in the chain, let’s break it down into sections.
- Section 1: The Genesis Block
What is the genesis block?
The genesis block is the first block of the blockchain, and the reason why it is special is that while every bock points to the block previous to it, the genesis block does not point at anything. So, the moment a new chain is created, the genesis block is invoked immediately.
Also, you can see a “createGenesisBlock ()” function wherein we have given the data of the block manually:
[code lang=”js”]createGenesisBlock ()
{
return new Block ( 0 , "01/01/2017" , "Genesis block" , "0" );
} [/code]
- Section 2: Adding The Blocks
Firstly, we will need to know what the last block in the blockchain currently is. For that we use the getLatestBlock () function.
[code lang=”js”]getLatestBlock ()
{
return this . chain [this . chain . length – 1 ];
}
Now That We Have Determined the latest block, let ‘ s see how we are going to add new blocks .
addBlock (newBlock) {
Newblock . previousHash = this . getLatestBlock () . hash;
Newblock . hash = newBlock . calculateHash ();
this . chain . push (newBlock);
} [/code]
So, what is happening here? How are we adding the blocks? How are we checking if the given block is valid or not?
Remember the contents of a block? A block has the hash of the previous block right?
So, what are we going to do here is simple. Compare the previous hash value of the new block with the hash value of the last block.
Image Courtesy: Lauri Hartikka medium article
If these two values match, then this means that the new block is legit and it gets added to the blockchain.
- Section 3: Validating the Chain
Now, we need to check that nobody has been messing with our blockchain and that everything is stable.
We are using the “for” loop to go from the block 1 to the last block. Genesis block is block 0
[code lang=”js”]for (let i = 1 ; i < this . chain . length; i ++ )
{
const currentBlock = this . chain [i];
const previousBlock = this . chain [i – 1 ];
In this part of the code we are defining two terms, current block and previous block . And now we are simply going to find the hash of these two values .
if (currentBlock . hash ! == currentBlock . calculateHash ()) {
return false;
}
if (currentBlock . previousHash ! == previousBlock . hash)</pre>
<pre>{
return false;
}
}
return true;
}[/code]
If the “previousHash” of the current block is not equal to the “Hash” of the previous block, then this function will return False, else it will return True.
Using the blockchain
Now, we are going to finally use the blockchain to create our BlockCoin.
[code lang=”js”]
let BlockCoin = new Blockchain ();
BlockCoin . addBlock (new Block ( 1 , "20/07/2017" , {amount: 4 }));
BlockCoin . addBlock (new Block ( 2 , "20/07/2017" , {amount: 8 }));[/code]
And that’s it!
So what happened here?
We created a new cryptocurrency based on the blockchain and named it BlockCoin. By invoking this new object, I activated the constructor, which in turn created the Genesis block automatically.
We simply added two more blocks to it and gave them some data.
It is that simple.
Post a Comment
You must be logged in to post a comment.