Category: Blockchain technology

Blockchain technology using Javascript

Hello People. This article is about Blockchain technology using Javascript. As you already know, a blockchain is an open, digital, and duplicated ledger of transactions. Every new transaction history is recorded and stored in an encrypted way that is very difficult to modify. A copy of this recorded information is sent a cross the blockchain network. This makes it highly secure.

Blockchains are blocks of transaction data growing increasingly to create a chain of transaction occurrences. Valid transaction data is logged into the blockchain network following the peer-to-peer rule laid down by participants. Normally, the data in the databases are centralized. This means we operate based on only one server. Chances of risk are high due to failures of the system. Alternatively, decentralization allows data to be stored everywhere, thus making it faster, more secure and a better way of storing data.

We need to first install the crypto library using the command:

npm install --save crypto-js

We’ll use this library to import modules in our project.

We can start by creating a class BlockCypto as shown below:

const SHA256 = require('crypto-js/sha256');
class BlockCypto{
    constructor(index, current_time, info, nextHash=" "){
    this.index = index;
    this.current_time = current_time;
    this.info = info;
    this.nextHash = nextHash;
    this.hash = this.computeHash();     
    }
    computeHash(){
        return SHA256(this.info + this.nextHash + this.current_time + JSON.stringify(this.info)).toString();
    }   
}

Let us see each part of the code here:

We have created the class BlockCrytpo for our block and added a constructor just like any other JavaScript class.

In the constructor, we initialize its properties and assign parameters to it, as follows:

  • crypto-js/sha256: This is the module we’ve imported to calculate the hash of each block. We converted it to string using toString() method as the module will return the object.
  • index: This is a distinctive number tracking the index of every block in the blockchain.
  • current_time: As the name states, it keeps a record of the time when each transaction is completed.
  • info: All completed transactions data are recorded and stored by this method.
  • nexthash: It is pointing to the hash_key of the next block in the network chain. It’s mainly used to keep and maintain the integrity of the blockchain.
  • computeHash: Based on properties passed to this method, it is used to calculate the hashkey of the next block in the chain.
Blockchain technology using Javascript

What is blockchain theorem?

It is a type of database that stores a collection of data together in groups, with certain capacity of storage. The blocks are connected to the already created blocks, this forms a chain of a data tree.

The chain is irreversible as the system is decentralized. Here, each block is assigned a timestamp when added to the chain.

Now, let’s create a class Blockchain that will maintain this operation:

class Blockchain{
    constructor(){
        this.block1chain = [this.startGenesisBlock()];     
    }
    initGenesisBlock(){
        return new BlockCrypto(0, "06/04/2021", "Initial Block in the Chain", "0");
    }
    latestBlock(){
        return this.block1chain[this.block1chain.length - 1];
    }
    addNewBlock(newBlock){
        newBlock.nextHash = this.latestBlock().hash;
        newBlock.hash = newBlock.computeHash();        
        this.block1chain.push(newBlock);
    }
}

Let’s understand the code snippet above.

As usual, we have our constructor which instantiates the blockchain.

But this time, we passed it to the initGenesisBlock() method, which initializes the block in the chain. This property refers to an array of blocks in our case.

  • initGenesisBlock(): This is the first block created in the peer-to-peer network and has not been linked to any other. To our knowledge of indexing it’s at index 0.
  • latestBlock: As named, we use it for finding the last block added in the chain. As explained earlier, it helps to ensure the hash of the current block and map it to the hash of the previous block to ensure the chain integrity.
  • addNewBlock: A new block is added to the chain using this method. The previous hash block is matched to the current hash block to ensure minimal or no tampering with the chain.

Now that our blockchain is ready to work. We are missing something that is a core blockchain principle, the blockchain integrity.

Let’s see how to verify it and test our app.

Verifying blockchain integrity

The main characteristic of a blockchain is that once a block has been added to the network, it can’t be changed without invalidating the entire blockchain integrity.

To perform this, we use digital security or cryptographic hash, which ensures the securing and validation of the blockchain by producing a new hash every time a change is made in the block.

We’ll loop over the entire blockchain to check whether any hash has been tampered with, taking into account the exception of the first block, which is hardcoded.

Besides, this method verifies if the cryptographic-key of each two blocks in series are pointing to one another. If the integrity of the blockchain has been compromised, it returns false; otherwise, in case no anomalies are encountered, it returns true.

We’ll create this method inside the Blockchain class:

checkValidity(){
    // Checking validity
    for(let i = 1; i < this.block1chain.length; i++) {
        const currentBlock = this.block1chain[i];
        const nextBlock= this.blockchain[i-1];
    // Checking current blcok hash
    
    if(currentBlock.hash !== currentBlock.computeHash()) {
        return false;
    }
    // Comparing current block hash with the next block

    if(currentBlock.nextHash !== nextBlock.hash) {
        return false;
    }
    return true;
}

Now, we can test our app and see the results:

But, before we dive into running the code, let’s create a new instance of the Blockchain class and name it thecoin, and add some blocks in the blockchain using random values.

let thecoin = new Blockchain();

thecoin.addNewBlock(new BlockCrypto(1, "06/04/2021", {sender: "Rabin Yitzack", recipient: "Loyd Eve", quantity: 20}));

thecoin.addNewBlock(new BlockCrypto(2, "07/04/2021", {sender: "Anita Vyona", recipient: "Felix Mush", quantity: 349}));

console.log(JSON.stringify(thecoin, null, 4));

Hope this article on Blockchain technology using Javascript is useful to you. Please read Child Tracker IOT project architecture

Blockchain Technology explained

Hello People. This article makes you Blockchain Technology explained. A blockchain is a distributed database that is shared among the nodes of a computer network. It stores information electronically in digital format.

Blockchains are used in cryptocurrency systems, such as Bitcoin, for maintaining a secure and decentralized record of transactions. It guarantees the fidelity and security of a record of data and generates trust without the need for a trusted third party.

Main Features

  • Blockchain is a shared database. It differs from a typical database in the way that it stores information.
  • Blockchains store data in blocks that are then linked together via cryptography.
  • When data comes in, it is entered into a fresh block. Once the block is filled with data, it is chained onto the previous block, which makes the data chained together in chronological order.
  • Most common use of blockchain so far has been as a ledger for transactions. 
  • In Bitcoin, blockchain is used in a decentralized way so that no single person or group has control. All users collectively retain control.
  • Data entered is irreversible. Transactions are permanently recorded and viewable to anyone.
Blockchain Technology explained

Blockchain working process

The purpose of blockchain is to allow digital information to be recorded and distributed, but not edited. In this way, a blockchain is the foundation for immutable ledgers, or records of transactions that cannot be altered, deleted, or destroyed. This is why blockchains are also known as a distributed ledger technology (DLT).

Blockchain’s first widespread application in use was Bitcoin in 2009. In the years since, the use of blockchains has exploded via the creation of various cryptocurrencies, decentralized finance (DeFi) applications, non-fungible tokens (NFTs), and smart contracts.

Blockchain has three important concepts: blocks, nodes and miners.

Blocks

Every chain consists of multiple blocks and each block has three basic elements:

  • The data in the block.
  • A 32-bit whole number called a nonce. The nonce is randomly generated when a block is created, which then generates a block header hash. 
  • The hash is a 256-bit number wedded to the nonce. It must start with a huge number of zeroes (i.e., be extremely small).

When the first block of a chain is created, a nonce generates the cryptographic hash. The data in the block is considered signed and forever tied to the nonce and hash unless it is mined.  

Miners

Miners create new blocks on the chain through a process called mining.

In a blockchain every block has its own unique nonce and hash, but also references the hash of the previous block in the chain, so mining a block isn’t easy, especially on large chains.

Miners use special software to solve the incredibly complex math problem of finding a nonce that generates an accepted hash. Because the nonce is only 32 bits and the hash is 256, there are roughly four billion possible nonce-hash combinations that must be mined before the right one is found. When that happens miners are said to have found the “golden nonce” and their block is added to the chain. 

Making a change to any block earlier in the chain requires re-mining not just the block with the change, but all of the blocks that come after. This is why it’s extremely difficult to manipulate blockchain technology. Think of it as “safety in math” since finding golden nonces requires an enormous amount of time and computing power.

When a block is successfully mined, the change is accepted by all of the nodes on the network and the miner is rewarded financially.

Nodes

One of the most important concepts in blockchain technology is decentralization. No one computer or organization can own the chain. Instead, it is a distributed ledger via the nodes connected to the chain. Nodes can be any kind of electronic device that maintains copies of the blockchain and keeps the network functioning. 

Every node has its own copy of the blockchain and the network must algorithmically approve any newly mined block for the chain to be updated, trusted and verified. Since blockchains are transparent, every action in the ledger can be easily checked and viewed. Each participant is given a unique alphanumeric identification number that shows their transactions.

Combining public information with a system of checks-and-balances helps the blockchain maintain integrity and creates trust among users. Essentially, blockchains can be thought of as the scalability of trust via technology. 

Hope this article on Blockchain Technology explained is useful to you. Please read about Printed Circuit Board designing business

Navigation

× Contact Us