Book Image

Learn Blockchain Programming with JavaScript

By : Eric Traub
Book Image

Learn Blockchain Programming with JavaScript

By: Eric Traub

Overview of this book

Learn Blockchain Programming with JavaScript begins by giving you a clear understanding of what blockchain technology is. You’ll then set up an environment to build your very own blockchain and you’ll add various functionalities to it. By adding functionalities to your blockchain such as the ability to mine new blocks, create transactions, and secure your blockchain through a proof-of-work you’ll gain an in-depth understanding of how blockchain technology functions. As you make your way through the chapters, you’ll learn how to build an API server to interact with your blockchain and how to host your blockchain on a decentralized network. You’ll also build a consensus algorithm and use it to verify data and keep the entire blockchain network synchronized. In the concluding chapters, you’ll finish building your blockchain prototype and gain a thorough understanding of why blockchain technology is so secure and valuable. By the end of this book, you'll understand how decentralized blockchain networks function and why decentralization is such an important feature for securing a blockchain.
Table of Contents (10 chapters)

Building the /mine endpoint

Let's build the final endpoint for our blockchain API: the mine endpoint, this will mine and create a new block:

  1. To create a new block, we are going to use our createNewBlock method, which we already defined in our blockchain.js file. Let's go to our api.js file and create a new block inside the /mine endpoint:
app.get('/mine', function(req, res) {
const newBlock = bitcoin.createNewBlock();
});
  1. This createNewBlock method takes in three parameters: nonce, previousBlockHash, and hash:
Blockchain.prototype.createNewBlock = function(nonce, previousBlockHash, hash) {
const newBlock = {
index: this.chain.length + 1,
timestamp: Date.now(),
transactions: this.pendingTransactions,
nonce: nonce,
hash: hash,
previousBlockHash: previousBlockHash
};

this.pendingTransactions = [];
this.chain.push(newBlock);

return...