Difference between revisions of "BlockChain"

(Language #2: Javascript)
Line 198: Line 198:
  
 
===Language #2: Javascript===
 
===Language #2: Javascript===
 +
 +
Up next we have Javascript.
 +
 +
Along with HTML and CSS it is one of the three core technologies in World Wide Web Content Production. Javascript is usually used to create highly interactive webpages. So, now we will see how to create a very simple blockchain using Javascript. Huge shoutout to savjee.be for the content in this section.
 +
 +
Suppose, we want to create a simple blockchain in Javascript. Before we do so, there are certain things that we need to address.
 +
 +
 +
 +
'''What is a blockchain and how exactly does it work…code-wise?'''
 +
 +
A blockchain is basically a chain of blocks which contain data. It is basically a glorified linked list. However, what makes it so special? A blockchain is immutable. Meaning, once a data goes inside a block, it can never be changed. How does a blockchain attain immutability? It is because of a simple but ingenious mechanism called “hashing”. Checkout the diagram below:
 +
 +
https://blockgeeks.com/wp-content/uploads/2017/11/image1.png
 +
 +
Image Courtesy: Lauri Hartikka medium article
 +
 +
Each block is connected to the previous block via a hash pointer which contains the hash of the previous block. So, how does this make the chain immutable?
 +
 +
One of the most fascinating properties of [https://blockgeeks.com/guides/cryptocurrencies-cryptography/ cryptographic hash functions] is that if you even change the input by a little bit, it can greatly affect the output hash. Eg. Check this out:
 +
 +
https://blockgeeks.com/wp-content/uploads/2017/11/coding.png
 +
 +
Just changing the first “T” from upper to lower case drastically changed the output hash so much.
 +
 +
'''So, how does this affect the blockchain?'''
 +
 +
Each block is connected to the previous one via the hash pointer. So, if someone were to tamper the data in a block, it would change the hash drastically and as a result, end up affecting the whole chain (as all the blocks are linked). This would freeze up the chain which is an impossibility and hence the blocks remain unchanged.
 +
 +
So, 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 “BlockGeeksCoin”), 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 that’s done, let’s start making our block.
 +
 +
 +
 +
'''Creating the Block'''
 +
<syntaxhighlight lang="javascript">
 +
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)).toString();
 +
}
 +
 +
}
 +
</syntaxhighlight>
 +
 +
Code Analysis
 +
 +
Ok, so this right here is out 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 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'''
 +
<syntaxhighlight lang="javascript">
 +
class Blockchain
 +
{
 +
//Section 1 Genesis block creation
 +
constructor()
 +
{
 +
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;
 +
}
 +
}
 +
</syntaxhighlight>
 +
 +
Code Analysis
 +
 +
Ok, so a lot of things are going on in the chain above, let’s break it down to 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 because while every bock points to the block previous to it, the genesis block doesn’t 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:
 +
 +
<syntaxhighlight lang="javascript">
 +
createGenesisBlock()
 +
{
 +
return new Block(0, “01/01/2017”, “Genesis block”, “0”);
 +
}
 +
</syntaxhighlight>
 +
 +
Now that we have built the genesis block, let’s build the rest of the chain.
 +
 +
====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.
 +
 +
<syntaxhighlight lang="javascript">
 +
getLatestBlock()
 +
{
 +
return this.chain[this.chain.length - 1];
 +
}
 +
</syntaxhighlight>
 +
 +
Now that we have determined the latest block, let’s see how we are going to add new blocks.
 +
<syntaxhighlight lang="javascript">
 +
addBlock(newBlock) {
 +
newBlock.previousHash = this.getLatestBlock().hash;
 +
newBlock.hash = newBlock.calculateHash();
 +
this.chain.push(newBlock);
 +
}
 +
</syntaxhighlight>
 +
 +
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 we are going to do here is simple. Compare the previousHash value of the new block with the hash value of the latest block.
 +
 +
https://blockgeeks.com/wp-content/uploads/2017/11/image3.png
 +
 +
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.
 +
 +
<syntaxhighlight lang="javascript">
 +
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)
 +
{
 +
  return false;
 +
}
 +
}
 +
return true;
 +
}
 +
</syntaxhighlight>
 +
 +
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 BlockGeeksCoin.
 +
 +
*let BlockGeeksCoin = new Blockchain();
 +
*BlockGeeksCoin.addBlock(new Block(1, “20/07/2017”, { amount: 4 }));
 +
*BlockGeeksCoin.addBlock(new Block(2, “20/07/2017”, { amount: 8 }));
 +
 +
 +
And that’s it!
 +
 +
'''So what happened here?'''
 +
 +
We created a new cryptocurrency based on the blockchain and named it BlockGeeksCoin. 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.
 +
 +
(Thank you savjee.be for the amazing and simple explanation.)
  
 
===Language #3: Python===
 
===Language #3: Python===

Revision as of 04:46, 8 October 2018

Blockchain Coding

Blockchain Coding: The Many different Languages You Need! The blockchain technology is incredibly fascinating. It won’t be far-fetched to think of a future which will be built entirely on it. So, what do you need to learn in order to start developing on the blockchain? Which languages will give you the edge? In this guide, we will go through some of the more major ones.

Problems with developing blockchain software

Before we begin, let’s checkout some of the challenges that a blockchain developer faces. Creating and maintaining a public blockchain is not easy because of a number of reasons.

Reason #1: Security

Blockchains, as David Schwartz puts it, should be fortresses. Firstly, the code is public and open for all to see. Anyone can look over the code and check for bugs and vulnerabilities. However, unlike other open code resources, the downside of finding vulnerabilities on blockchain code is massive. Any programmer can hack in and get away with potentially millions and millions of dollars. Because of these legitimate security concerns, development on blockchain is usually very slow.

Reason #2: Resource Management

It is important to keep pace with the network. You cannot fall too far behind and not keep up with all the network demands. You should be well equipped to handle remote and local queries.

Reason #3: Performance

The blockchain must always perform at its highest possible capabilities, but for that to happen the language chosen must be extremely versatile. The thing is that there are certain tasks in the blockchain which are parallelizable whilst there are some tasks which can’t be done in parallel.

A good example of “parallelizable” task is digital signature verification. All that you need for signature verification is the key, transaction and the signature. With just three data you can conduct verifications in a parallelized manner.

However, not all the functions on a blockchain should be done that way. Think of transaction execution itself. Multiple transactions can’t be executed in parallel; it needs to be done one at a time to avoid errors like double spends. Some languages are good at parallel operations while some are good in non-parallel operations

Reason #4: Isolation

What is deterministic behavior?

  • If A + B = C, then no matter what the circumstances, A+B will always be equal to C. That is called deterministic behavior.
  • Hash functions are deterministic, meaning A’s hash will always be H(A).


So, in blockchain development, all transaction operations must be deterministic. You cannot have a transaction that behaves one way and then behaves another way the next day. Similarly, you cannot have smart contracts that work in two different ways in two different machines.

The only solution to this is isolation. Basically you isolate your smart contracts and transactions from non-deterministic elements.

Blockchain Development Languages

we have discussed the main problems that blockchain developers face. Now let’s finally check out some of the languages that the developers can use to code on the blockchain.

Language #1: C++

First and foremost, let’s start with the granddaddy of them all, the evergreen C++. C++ was created by Bjarne Stroustrup as an extension of the C language. The Language was designed to have the flexibility and efficiency of the C but with some major differences. The biggest difference between C and C++ is that while C is process-oriented, C++ is object oriented.

What this means is that, in C++, the data and functions are wrapped into one neat little package called “objects” which means that once an object is created, it can easily be called and reused in other programs, which greatly reduces coding time.

Let’s look at the simplest C++ program in the world. The “Hello World” program:

#include <iostream.h>
main()
{
cout << "Hello World!";
return 0;
}

This code will print: Hello World!

So, why do people still use C++ for coding? Surely there are way more glamorous languages now, why do people still insist on going back to C++? Why is the bitcoin blockchain coded on C++?

Well, as it happens, C++ has certain features that makes it very appealing. (Shout out Peter Wiulle and David Schwartz for the following explanation).

Feature #1: Memory Control

Not only should blockchains be secured fortresses but they should have effective resource management as well. A blockchain is supposed to interact with a lot of untrusted endpoints while still giving quick service to any and all nodes.

This quick and prompt service is critical for the success of a cryptocurrency like bitcoin. Remember, they are all based on the principle of “consensus”, all nodes on the network must accept and reject the exact same blocks, or else there could be a fork in the chain.

In order to satisfy all these demands and perform at the highest level, you need tight and complete control over CPU and memory usage. C++ gives that to its users.

Feature #2: Threading

As we have discussed before, one of the main challenges of the blockchain programming is the integration of tasks that parallelize well and the tasks that don’t parallelize. Most languages specialize in one, however C++’s threading ability is good enough to handle both parallel and non-parallel tasks. A thread is a set of instructions that can be executed simultaneously. Not only does C++ allow fir superb multithreading facilities with effective inter-thread communication, it also optimizes single-thread performance.

Feature #3: Move Semantics

One of the most interesting aspects of C++ is move semantics. Move semantics provides a way for the contents to be moved between objects rather than be copied outright. Let’s checkout the differences between copy semantics and move semantics. (Following data taken from Peter Alexander’s answer in “Stackoverflow”).

Copy Semantics:

assert(b == c);
a = b;
assert(a == b && b == c);

So what is happening here? The value of b goes into a and b remains unchanged at the end of the whole thing.

Now, consider this.

Move Semantics:

assert( b = = c);
move (a,b);
assert (a = =c );

What is happening here?

Can you see the difference between the two blocks of codes?

When we are using the move semantics, the value of “b” need not be the unchanged. That is the difference between copy semantics and move semantics. The biggest advantage of move semantics is that you can get copies of certain data only when you need them, which greatly decreases redundancy in the code and gives a huge performance boost. So as you can see, this efficient memory management and high performance are both desirable for the blockchain.

Feature #4: Compile Time Polymorphism

What is polymorphism?

Remember when we called C++ an “object oriented programming (OOP) language”? Polymorphism happens to be an OOP property. Using polymorphism, you use a particular feature in more than one ways. In C++ polymorphism can be used in two ways:

  • Compile time polymorphism.
  • Run time polymorphism.

Over here, we will only be focusing on compile time polymorphism. There are two ways that C++ implements compile time polymorphism:

  • Function Overloading.
  • Operator Overloading.


Function Overloading:

Function overloading is when you have many functions of the same name but with different parameter intake.

Consider this program:

#include <bits/stdc++.h>
using namespace std;

class A
{
void func (int x)  //first instance of the function takes only one integer value
{
cout<<x<<endl;
}

void func (double x) //second instance of the function takes only one double value
{
cout<<x<<endl;
}

void func (int x, int y) //third instance of the function takes two integer values
{
cout<<x=y<<endl;
}

}

int main()

{
A obj1 //making one object of the class A
//now we are going to call the functions
obj1.func(2);
obj1.func(2.65);
obj1.func(2,5);
return 0;
}

Now when you run this function the output will be:

  • 2
  • 2.65
  • 7

So, as you can see, the same function func() was used in 3 different ways.

Operator Overloading:

In C++ the same operator can have more than one meaning.

  • Eg. “+” can be used both for mathematical addition and for concatenation.
  • Concatenation basically means taking two strings and combining them as one.
  • So 3+4 = 7.

AND

  • Block+geeks = Blockgeeks.
  • The same operator, did two different functions, this is operator overloading.

The Compile time polymorphism helps a lot in blockchain development. It helps in putting responsibilities separately in various functions and, in turn, boosting the performance of the whole system.

Feature #5: Code Isolation

C++ has namespace features which can be imported from one program to another. Namespace helps in avoiding name collisions. Also, since C++ has classes, it can act as boundaries between various APIs and help in making clear separation.

A class in C++ is a user defined type or data structure declared with keyword class that has data and functions as its members. You can access the functions declared in the class by declaring objects of that particular class.

Feature #6: Maturity

The language is both mature and regularly updated. There are at least 3 solid compilers, as David Schwartz says, and the new features are aimed at solving real issues. Debuggers and analytical tools of all kinds are available for everything from performance profiling to automatic detection of issues of all kinds. This means the language is constantly growing to incorporate newer and better features.

Because of the above features, Satoshi Nakamoto chose C++ to be the base language of the bitcoin source code.






Language #2: Javascript

Up next we have Javascript.

Along with HTML and CSS it is one of the three core technologies in World Wide Web Content Production. Javascript is usually used to create highly interactive webpages. So, now we will see how to create a very simple blockchain using Javascript. Huge shoutout to savjee.be for the content in this section.

Suppose, we want to create a simple blockchain in Javascript. Before we do so, there are certain things that we need to address.


What is a blockchain and how exactly does it work…code-wise?

A blockchain is basically a chain of blocks which contain data. It is basically a glorified linked list. However, what makes it so special? A blockchain is immutable. Meaning, once a data goes inside a block, it can never be changed. How does a blockchain attain immutability? It is because of a simple but ingenious mechanism called “hashing”. Checkout the diagram below:

image1.png

Image Courtesy: Lauri Hartikka medium article

Each block is connected to the previous block via a hash pointer which contains the hash of the previous block. So, how does this make the chain immutable?

One of the most fascinating properties of cryptographic hash functions is that if you even change the input by a little bit, it can greatly affect the output hash. Eg. Check this out:

coding.png

Just changing the first “T” from upper to lower case drastically changed the output hash so much.

So, how does this affect the blockchain?

Each block is connected to the previous one via the hash pointer. So, if someone were to tamper the data in a block, it would change the hash drastically and as a result, end up affecting the whole chain (as all the blocks are linked). This would freeze up the chain which is an impossibility and hence the blocks remain unchanged.

So, 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 “BlockGeeksCoin”), 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 that’s done, let’s start making our block.


Creating the Block

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)).toString(); 
} 

}

Code Analysis

Ok, so this right here is out 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 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

class Blockchain
{
//Section 1 Genesis block creation
 constructor() 
{ 
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 Analysis

Ok, so a lot of things are going on in the chain above, let’s break it down to 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 because while every bock points to the block previous to it, the genesis block doesn’t 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:

createGenesisBlock()
{
return new Block(0, 01/01/2017, Genesis block, 0);
}

Now that we have built the genesis block, let’s build the rest of the chain.

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.

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); 
}

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 we are going to do here is simple. Compare the previousHash value of the new block with the hash value of the latest block.

image3.png

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.

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) 
{ 
   return false; 
} 
} 
return true; 
}

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 BlockGeeksCoin.

  • let BlockGeeksCoin = new Blockchain();
  • BlockGeeksCoin.addBlock(new Block(1, “20/07/2017”, { amount: 4 }));
  • BlockGeeksCoin.addBlock(new Block(2, “20/07/2017”, { amount: 8 }));


And that’s it!

So what happened here?

We created a new cryptocurrency based on the blockchain and named it BlockGeeksCoin. 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.

(Thank you savjee.be for the amazing and simple explanation.)

Language #3: Python

Language #4: Solidity

Best Blockchain Certification, Training & Course