0% found this document useful (0 votes)
6 views

Miracles of Blockchain-Build your own blockchain-notes

Miracles of Blockchain - Build your own blockchain notes

Uploaded by

Rejin R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Miracles of Blockchain-Build your own blockchain-notes

Miracles of Blockchain - Build your own blockchain notes

Uploaded by

Rejin R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Miracles of Blockchain

4 Days DTE Sponsored FDP, RIT Kottayam

Build your own Blockchain

Rejin R

Asst. Professor, Department of Information Technology,


Government Engineering College Idukki
[email protected]
9496209049
1
Basic ideas of Blockchain
Let’s explore the overall working of blockchain. To better understand the concepts we
need to learn some fundamental aspects:

1. Cryptographic Hash:
A cryptographic hash function is an algorithm that takes an arbitrary amount of data input
and produces a fixed-size output of enciphered text called a hash value, or just “hash.” It’s
essentially a fingerprint of the message input.

Certain cryptographic aspects of hash functions make it a preferable choice for several
cryptographic applications:
A. Fixed Sized output: regardless of the input size or character, the output generated will
be of fixed size.
B. Non-reversibility, or one-way function: a good hash should make it very hard to
reconstruct the original data from the output or hash.
C. Non-predictable: The hash value should not be predictable from the password.
D. Determinism: a given data must always generate the same hash value or enciphered
text.
E. Diffusion, or avalanche effect: a change in just one bit of the original password should
result in change to half the bits of its hash. In other words, when a password is changed
slightly, the output of enciphered text should change significantly and unpredictably.
F. Collision resistance: it should be hard to find two different data that hash to the same
enciphered text.

With the following demonstration let’s explore the above features of Cryptographic hash
functions:
Here we have used an online simulator of hash function. We have to provide data
in the given input field and corresponding hash (SHA256 - Secure Hash Algorithm 256)
value is generated in the below field.
In the first scenario(figure) we have given input “My name is Rejin”. The
corresponding hash obtained is:
9d416f1376b5f4990825f8ca249817928f8ac86c4d10a51a3ff7a38331fcb093
As the second input (figure) we have provided an additional ! symbol at the end of the
first input. The corresponding hash obtained is:
a0fcf3c024ab27c61a96addeff0888370a21f19a3a988f5d0a263c1af8ee6807

2
Fig 1. Cryptographic Hash Functions - Data “My name is Rejin”

Fig 2. Cryptographic Hash Functions - Data “My name is Rejin!”

Observing the above two inputs, Unpredictability and Fixed sized output features
are evident. It can be also observed that slight change in the input has drastically
changed the output hash generated(Avalanche effect). Everytime we give the same
input, the same output will be obtained as a hash value(Determinism).

2. Block:
Extending the idea of the hash function we could define a block. A block records
some or all of the most recent Bitcoin transactions Thus, a block is like a page of a
ledger or record book.
To better understand the concept of block creation, we need to recall the idea of
blockchain mining which we have discussed in the previous section.
Here we use a simulator for blocks. In an abstract way a block includes a block
number, nonce, data and a hash. In the below represented block we can see values for
Block, nonce and value of data is empty. The hash output is the combined hash of block

3
number, nonce and data. Here the block color is given as green. It indicates the block
being a valid one.
We can also observe a special pattern in the output hash, i.e, the first four
characters are zeros.(0000….). This signifies the mining process.

Fig 3. Simulator for a block

Now let’s add some data into the block: “My name is Rejin R”. At this point we
can see that the color of the block is changed to red. This indicates the block being an
invalid one.

Fig 4. Invalid block

By observing the output hash the reason for the block being an invalid one is
clear. The first four characters of the hash output are not zeroes. That is, it doesn’t
satisfy the mining criterion.

4
We could try adjusting the nonce value starting from 0, to make the block a valid
one, but this would be a hectic task as we have to try several possibilities till the mining
criterion is satisfied.
Instead we click on the mining button, which would trigger the mining process,
which essentially is trying nonce value from zero until the first four characters of hash
output are zeroes.

Fig 5. Successful mining

3. Blockchain:

In the simplest of terms, blockchain can be defined as a database that stores data in
blocks. Here information is packaged into blocks, which link to form a chain with other
blocks of similar information., hence the name blockchain.
Here we use a simulator for blockchain. The given blockchain representation has
5 blocks. Block number is sequential from 1 to 5. We can observe that all blocks have a
green color and they are all valid.

5
Fig 6. Blockchain simulator

Each block includes the hash of the previous block, i.e, each block points
backwards to the one before it. The first block in the blockchain is known as genesis
block. Previous block hash value of the genesis block is null as there is no previous
block.

Fig 7. Invalid chain

If we add data to the third block: 3rd, 4th and 5th will become invalid as hash
would not match. This implies, if one block breaks all the subsequent blocks will also
break. To successfully thwart this situation we need to mine the 3rd block, 4th block and
5th block in sequence. This would take a great amount of time depending on the
number of characters fixed as zeroes in the output hash. This reduces the attacker's

6
window of opportunity and adds security. The more blocks in the past the harder and
harder it is to make a change. That’s how a blockchain is going to resist mutation.
Even if we successfully remine all the blocks, the block chain will still hold
the single truth. But how?...
That’s when being distributed has an advantage.

4. Distributed Blockchain:
Distributed trust is the core of blockchain technology. Through the following
demonstration we could grasp a glimpse of how being distributed enhances trust.
Here we use a distributed blockchain simulator. Here Peer A, Peer B and Peer C
have an exact copy of the blockchain.

Fig 8. Peer A

Fig 9. Peer B

7
If we alter the data and mine in the 5 th block in peer B, Peer A and Peer C will still have
the 5th block’s original version. Now the majority(2 by 1) have the correct version of 5th block,
and Peer B will be forced to update 5th block to the original version to continue with the chain.
That’s how a completely distributed peers can all very quickly see if all of the blocks are
identical. Every peer needs to check only the hash of the most recent block of other peers to
see if anything in the past is altered(there is no need to check the entire blockchain).

Till this point we have understood the very fundamental concept of blockchain. We have
worked with a single data in every block. Now let’s extend data to represent transactions.

5. Tokens
Here we use a token demonstration. Instead of a single data, a set of transactions are
represented inside a block.

Fig 10. Tokens Peer A

As we discussed before this is a distributed blockchain where Peer A, Peer B and Peer
C have identical copies of the same blockchain. If we change any of the transaction data, the
block will be easily detected by other peers in the Distributed blockchain.

Each transaction is represented in the form: amount, from and to. Here we are not
representing a balance in the direct form. We can only represent how much amount is
transferred from person A to person B (money movements only).

Eg: Darcy transferred 25$ to Singley.

8
This poses a question: Does Person A have sufficient balance to transfer? To
understand the solution to this question, let’s look into a coinbase transaction.

Fig 11. Invalid block

6. Coinbase transaction
Now we add a coinbase transaction in each block. Here in the example, a 100$ is
transferred to Anderson out of thin air. In the next block another 100$ is transferred. In the
second block onwards Anderson can do transactions as he has 100+100=200$(can transfer a
maximum of 200$).

Fig 12. Coinbase Transaction

9
Now it’s easy to go back in the chain and verify whether a person has sufficient
balance to transfer.

In this way we can represent not just financial transactions, but any kind of transactions
by following the same pattern. Eg: Record of a House from it’s plan to current stage. These
records will be stored as an immutable record.

Here is a question: What if someone adds a transaction that pays someone else’s
money to him? Is this possible?

With what we learned so far it’s perfectly possible. Let’s add some security features to
restrict this - Digital Signatures using public private key pairs

7. Public/Private Key pairs


The public key is open to anyone in the system. The private key however is only stored
by the user. There is no way to derive the private key from a given public key.

Here we use a public/private key simulator. If we provide a sequence of number as


private key corresponding pairs of public keys will be generated here. Clicking on the random
button will generate a random private key and corresponding public key.

Fig 13. Public/Private key pairs

We will use the private key to generate Digital Signature.

8. Digital Signature
Digital signatures are like electronic “fingerprints” in the form of a coded message, the
digital signature securely associates a signer with a document.

When a signer electronically signs a document, the signature is created using the
signer’s private key. First the given document’s hash is generated and it is encrypted with the
signer's private key. The resulting encrypted data is the digital signature.

10
At the verifier side the public key can be used to decrypt the digital signature to get the
hash value. This hash value is then compared with the document's hash value. If both matches
then it proves the message has been signed by the intended signer.

Fig 14. Digital Signature

In the demonstration we type the message “My name is Rejin R”. This message is
signed with a private key. When we click on the sign button the digital signature will be
generated for this message.

Fig 15. Digital Signature Signing

11
Fig 16. Digital Signature Verification

In the verify tab by clicking on the verify button we can see green color around the box,
which indicates successful verification.

If we change the public key a little bit the verification will fail.

Fig 17. Unsuccessful Digital Signature Verification

Instead of just using a plain message now let’s use a transaction structure.

9. Transactions

12
In the demonstration we use the transaction structure which we used in blockchain. Now
the message contains the amount, from and to addresses. Here addresses are public keys.

Fig 18. Transaction with Digital Signature

Fig 19. Transaction verification

When we click on the verify button the transaction will be verified using the public key
(from address). It will be shown in green color, which indicates the person in possession of the
private key has initiated the transaction.
Now let’s consolidate all these ideas into a blockchain concept.

10. Blockchain with Transactions:


In the blockchain transaction demonstration we can see all of the concepts we have
discussed so far (hash, block, distributed, nonce, coinbase, digital signature, etc...).

13
Fig 20. Block chain the whole idea

Here we don’t use names anymore, instead we use address (public key). Signature is
also there for every transaction. If we change Peer A’s last block’s transaction value: $7 to $6
then it will break the block and will also break the signature verification for the transaction. The
block and the signature will appear in red color. Even if we re-mine the block, the transaction
signature verification will still fail since the miner doesn’t have the sender’s private key, so they
can’t come up with the right signature. That’s how public/private key pair message signature
protect each and every transaction and make sure that they are from the intended sender.

Fig 21. Blockchain invalid block

14
Build Your Own Blockchain
Now it’s time to code a primitive version of the blockchain idea we learned so far. This
would help solidify the ideas we learned till this point.
For this we are going to use node.js as our runtime environment for scripting in
javascript. Visual Studio Code is our choice of Integrated Development Environment (IDE).

Software Requirements

Now let's install all of the softwares we need to create our own primitive blockchain version.

1. Google Chrome Browser:

Google Chrome is

Fig 22. Google Chrome browser

2. IDE - Visual Studio Code:

Visual Studio Code is a lightweight but powerful source code editor which runs on your
desktop and is available for Windows, macOS and Linux. It comes with built-in support
for JavaScript, TypeScript and Node.js and has a rich ecosystem of extensions for other
languages (such as C++, C#, Java, Python, PHP, Go) and runtimes (such as .NET and
Unity). It’s a code editor redefined and optimized for building and debugging modern web
and cloud applications.

Fig 23. Visual Studio Code IDE

15
3. Node.JS:

Javascript from its inception was made for browser environments.

Fig 24. Javascript alert command

Fig 25. Javascript console.log command

It is very easy to learn and code javascript, but it was confined within the boundaries of
a web browser. This was the scenario up until 2009, Ryan Dahl an American Software
Engineer changed it all.

16
In 2009 Ryan Dahl introduced Node.js, which is a runtime environment javascript
to execute javascript outside a web browser, in effect it unleashed the hidden potential of
javascript.

Node.js is an open source, cross platform runtime environment for executing


javascript code outside of a browser. Every browser has a javascript engine that
converts javascript code to machine code that browsers can execute.

Fig 26. Popular web browser engines.

Every browser has a javascript engine that converts javascript code to machine
code that browsers can execute. What Ryan Dahl did with Node.js is, he took one of the
fastest Javascript Engine: Google Chrome’s V8 Engine and embedded it within a C++
program and called that program Node.exe. So it contains a javascript engine that can
execute javascript code, and it also contains certain elements that provide an
environment for javascript code, which are basically different from the environment
provided by the browser. Those objects gave Node.js more interesting capabilities: we
can work with File System, Operating System, Listen for web server requests, are to
name a few. We can’t do these functionalities inside of a browser.

Fig 27. Node.js = V8 Engine wrapped inside C++ code

We can install Node.js from https://nodejs.org/en/ (Note: preferably choose LTS version).

17
To check whether node has been successfully installed the following command could be
used in terminal(command prompt):

node -v

This will show the current version of node.js

Let’s write our first node.js program:

Step 1: Create a directory for storing our project files and folders.
Step 2: Open up visual studio code.
Step 3: In Visual studio code click : File -> Open Folder; then select the created
directory of our project.

Fig 28. Open Folder in Visual Studio Code

Step 4: Click on New File icon in the project explorer window on the left side. Name the
newly created file as app.js (or you can give any name)
Step 5: Click to open app.js and type:
console.log(“Welcome to Node.js”);

Step 6: Write click on the project directory and select the option: Open in integrated
terminal. This would open the terminal window with your directory as the current
working directory.

18
Fig 29. Open in integrated Terminal option in Visual Studio Code

Step 7: In the integrated terminal, type:

node app.js

To execute a node.js program, we must type the command node followed by file
name.

Fig 30. Running node application in terminal

We can see the output “Welcome to Node.js” displayed in the integrated terminal
window.

Now let’s write a little bit more than just printing welcome:

Node architecture has small building blocks units, which are called the Node
Module System. There are several core built-in modules in Node.js which are:

os = for handling operating system related functionalities.

fs = for handling file system

events = events handling

http = sending and receiving http requests/responses

19
Fig 31. Node.js core modules

Let’s try out os module:

In the app.js type the following code:

By running the above code we will get output: the available free memory space in the
system.

This is how it works:

In the first statement const os=require(‘os’); we load the os module in the


variable os.

Now we create another variable called freemem.

var freemem=os.freemem(); Now we access the freemem method of the os


module and it will get stored in the variable freemem.

In the third statement we have just printed the freemem variable.

Now we have seen the power of node.js.

20
It’s time to expand our world from core modules to external packages:

Node Package Manager(NPM) is a command line tool as well as a registry of third party
libraries that we can add to our node application. Using npm we can install and use
external libraries in our node project. Npm command line tool will automatically get
installed when we install node.js. To check the version of npm we could use the
command: npm -v.

Before installing any packages it's a good practice to type: npm init -y in
terminal. This would create a file called package.json. This file will keep track of every
package we install in our project. This would be very helpful in the stage of deployment
of our application.

Fig 32. package.json

To install an external third party package in our node project we could use the
following command: npm i

Eg: type npm i colors in our integrated terminal. This would install the
external package colors. Now we can see a folder created inside our directory structure
called node_modules:

Fig 33. Node_modules folder

21
This is the directory where all of the external node packages will get installed and
also and entry will be made in the package.json file. Now as the colors package has
been installed, we can use that package in our project. Type the following statements in
app.js file:

Now we can see the output hello is displayed in the terminal in green color.

We have covered all the fundamental aspects required for our primitive blockchain
implementation. Now let’s code a blockchain:
Coding our primitive Blockchain:

We will use an incremental approach to learn and build a primitive blockchain version. In
parallel we will learn and apply concepts one step at a time:

1. Cryptographic Hash:
Now let’s work with hash function implementation in Node.js:
For this we need to install a package called crypto-js using the command:

npm i crypto-js

This package is a bundle of several cryptographic algorithms.

From crypto-js we will import the sha256 module.

The above statement will import sha256 functionality in the variable SHA256.

22
Now we create a text string and will store it in the variable data. Then we apply
the hash function by calling SHA256(data). We want our hash displayed in string format.
So we use: SHA256(data).toString(). If we print the value in the variable hash, we can
see the hash of the input data.

2. Block:
Now let’s implement the idea of block in our app.js. We will create a class named
Block (Class is a blueprint or template from which objects are created) which contains
the properties we have discussed above: data, hash, time stamp, block height, previous
block hash and nonce. Here the constructor method is utilized(a constructor is a method
which is called automatically whenever an object of a class is created). Also there is a
calculateHash method to calculate the hash with all the block parameters.

23
3. Blockchain:
Now we will try our blockchain idea in Node.js:
We will create a class representing blockchain, in the similar way we created a
class for Block.

1. constructor():
First we create an empty array to store our blocks: this.chain=[]
Next we call createGenesisBlock method with data “Genesis Block” as:
var genesisBlock=this.createGenesisBlock(“Genesis
Block”)
We wrote this statement inside the constructor because we need to
create a genesis block when blockchain is initialized. Our constructor will
ensure this.

24
Next we call addBlock method to add the genesis node to the blockchain:
var this.addBlock(genesisBlock)
2. createGenesisBlock(blockData):
This method is for creating a Genesis Block
First we create object of a Block named newBlock:
var newBlock=new Block();
Then we fill content of each attributes inside the block:
block.data=newData - blocks data will be filled with the input passed
to createGenesisBlock method.
block.timeStamp=Date.now().toString() - timestamp value will
be updated with current system time (after converting to string).
block.blockHeight=0 - block height is set as zero as it is the
Genesis bloc(First block)
block.previousBlockHash=null - previous block hash is set as null
because there is no previous block for Genesis block.
block.hash=SHA256(block.data+block.timeStamp+
block.blockheight+block.previousBlockHash+
block.nonce).toString() - block’s hash is calculated using
data, time stamp, block height, previous block hash and nonce as we discussed
earlier.
After all these updation the block is returned: return newBlock
3. addBlock(newBlock):
This method is for adding a block to the blockchain
This is done by pushing the given input block to the chain:
this.chain.push(newBlock)
4. createBlock(newBlock):
The only difference between createGenesisBlock and createBlock is with block
height and previous block hash.
In the createBlock method block height is set as the current chain length, since
this is the latest block.
block.blockHeight=this.chain.length
Previous block hash is set correctly by accessing the previous block’s hash using
the current block height.

block.blockHeight=this.chain[newblock.blockHeight-1].hash

Now let’s test our code by creating an instance of blockchain and adding two
nodes:

25
The output gets displayed will contain all the three blocks created.

Fig 34. Blockchain output

Now let’s code the mining concept:


For this we add a mining method inside our Blockchain class(code in color
orange). For the mining method we pass block as the input.

26
Inside the mining method we first create a variable to store the resultant hash
value. Then we iterate the value of a variable i through 0 to 100000 and inside the loop
we does the following:

27
We will assign value of block.nonce to i.(this would help us try out all possible
combinations of nonce from 0 to 100000 as we have learned). Using the nonce value we
will compute block hash.
Then this block hash’s first two characters are examined to see whether they are
zeros. (Here we choose block difficulty as two. We could try higher block difficulty values
and could observe mining time taken.). If these criterion is met the block hash will be
updated and the block will be added to the chain using the addBlock method.

Now we need to make one more change to our code. Here we call mining method
instead of addBlock method directly:

Hope this article gives you a birds eye view of the concept of Blockchain.

************************************************************************************************************

28

You might also like