Consequences of Overwatering Your Lawn

Water is essential for the health and growth of a lawn, but it is possible to have too much of a good thing. Overwatering your lawn can lead to a range of negative consequences, from reduced grass…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Programming Blockchain in Javascript

In the last few posts I talked about implementing Blockchain in iOS using Swift. A lot of people emailed me and asking about the Javascript implementation of the Blockchain. This post shows how to implement the core engine of the Blockchain in Javascript using Node.

The first step is to define the models associated with domain objects, represented in the Blockchain. These models consists of the following:

Transaction: A transaction represents a transfer of value. This can be money, merchandise, medical records etc.

Block: A block is mined by a miner which is later filled with transactions and added to the blockchain.

Blockchain: A blockchain represents the linked list of blocks. A blockchain is immutable, which means once the block is added to the blockchain it cannot be altered.

Once, our basic models have been created we can move on to implementing the core functionality of the Blockchain.

We will start by allowing our blocks to add transactions. This is done by adding a “addTransaction” function to the Block class as shown below:

A block is mined based on its key which comprises of the following properties:

index: The current index of the block in the blockchain.

previousHash: The hash of the previous block in the blockchain.

hash: The current hash of the block.

nonce: The magic number which is incremented to find the secret hash which is used to sign the block.

transactions: A list of transactions added to the block.

The key property is a getter property on the Block class as shown below:

Next, we will move to the Blockchain class. Below you can find the complete implementation of the Blockchain class.

That’s pretty much it!

Let’s go ahead and test out our Blockchain by adding few transactions.

We initialize the Blockchain by passing the genesisBlock. In Bitcoin world genesis block contains the rewards for miners. Next, we mined few blocks using the getNextBlock function of the Blockchain. Once, the blocks are mined we add the transactions to the block and add them to the Blockchain.

The video shows blockchain running in action:

Enjoy and happy programming!

Add a comment

Related posts:

Best cheap villa packers Ras al Khaimah

When you are shifting into a new place, it can be exasperating to locate the proper shifting company. There are a lot of choices out there and it can be tough to define how to pick the proper one for…

When online meets offline

Have you thought about your brand today? I mean really thought about it What do you picture when you think about it? Is it alive or just a logo? The greatest mistake online, is to think about your…