36,59 €
Explore the essentials of blockchain technology with JavaScript to develop highly secure bitcoin-like applications
Key Features
Book Description
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.
What you will learn
Who this book is for
Learn Blockchain Programming with JavaScript is for JavaScript developers who wish to learn about blockchain programming or build their own blockchain using JavaScript frameworks.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 238
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Kunal ChaudhariAcquisition Editor:Devanshi DoshiContent Development Editor:Onkar WaniTechnical Editor: Sachin SunilkumarCopy Editor:Safis EditingProject Coordinator:Kinjal BariProofreader: Safis EditingIndexer:Priyanka DhadkeGraphics:Alishon MendonsaProduction Coordinator:Jyoti Chauhan
First published: November 2018
Production reference: 1291118
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78961-882-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Eric Traub currently works as a software engineer in New York City. He has extensive experience working as a teacher and instructing people in a variety of different subjects. He changed his career from teaching to software engineering because of the excitement it brings to him and the passion that he has for it. He is now lucky enough to have the opportunity to combine both of these passions – software engineering and teaching!
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn Blockchain Programming with JavaScript
About Packt
Why subscribe?
Packt.com
Contributors
About the author
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Setting up the Project
What is a blockchain?
What you will learn...
Environment setup
Project source code
Summary
Building a Blockchain
Before we get building...
An explanation of the JavaScript constructor function 
Explanation of the prototype object
Blockchain constructor function
Building the createNewBlock method
Testing the createNewBlock method
Testing the Blockchain constructor function
Testing the createNewBlock method
Building the getLastBlock method
Creating the createNewTransaction method
Testing the createNewTransaction method
Adding a pending transaction to our blockchain 
 Hashing the data
Understanding the SHA256 hashing function
The hashBlock method
Testing the hashBlock method
What is a Proof of Work?
Creating the proofOfWork method
Testing the proofOfWork method
Creating a genesis block
Testing the genesis block
Summary
Accessing the Blockchain through an API
Setting up Express.js
Installing Express.js
Using Express.js
Building the API foundation
Installing Postman and body-parser
Installing Postman 
Building the /blockchain endpoint
Testing the /blockchain endpoint
Building the /transaction endpoint
Testing the /transaction endpoint
Building the /mine endpoint
Testing the endpoints
/mine endpoint testing 
Testing the / blockchain endpoint
Testing the /transaction endpoint
Summary
Creating a Decentralized Blockchain Network
Creating multiple nodes
Running multiple instances of networkNode.js
Testing the multiple nodes
Adding the currentNodeUrl
New endpoints outline
Defining the /register-and-broadcast-node endpoint
Creating the /register-node endpoint 
The difference between register-and-broadcast-node and register-node endpoint
Defining the /register-nodes-bulk endpoint 
Understanding how all of the endpoints work together 
Building  the /register-and-broadcast-node endpoint 
Continuing to work on the /register-and-broadcast-node endpoint 
A quick recap of how the register-and-broadcast-node endpoint functions 
Building the  /register-node endpoint
Testing the  /register-node endpoint
Installing the request library
Endpoint testing
Building the /register-nodes-bulk endpoint
Testing the /register-nodes-bulk endpoint
Testing all of the network endpoints
Summary
Synchronizing the Network
Understanding the need to synchronize the network 
Refactoring the createNewTransaction method and the /transaction endpoint
Modifications to the createNewTransaction method
Building the addTransactionToPendingTransactions method 
Building the /transaction/broadcast endpoint
Refactoring the /transaction endpoint
Testing the transaction endpoints
Recapping how to create the network 
Testing the transaction endpoints
Updating the mining information
The updated mining process
Refactoring the /mine endpoint
Building the /receive-new-block endpoint
Testing the new and updated /mine endpoints
Summary
Consensus Algorithms
What is the consensus algorithm ?
Building the chainIsValid method
Testing the chainIsValid method
Verifying the output of the test
A tiny modification to verify the results properly
Building the /consensus endpoint
Quick review of the build process
Testing the /consensus endpoint
Summary
Block Explorer
What is a block explorer? 
Defining the block explorer endpoints 
Building the getBlock method
Building the /block/:blockHash endpoint
Testing the /block/:blockHash endpoint 
Defining the getTransaction method
Building the /transaction/:transactionId endpoint
Testing the /transaction/:transactionId endpoint
Adding new transactions and blocks to the blockchain 
Testing the endpoint 
Building the getAddressData method
Knowing the balance 
Developing the /address/:address endpoint
Testing the /address/:address endpoint
Adding the block explorer file
Building the /block-explorer endpoint
Block explorer file explanation
Testing our block explorer
Summary 
In conclusion...
A quick review
Areas of improvement
Other Books You May Enjoy
Leave a review - let other readers know what you think
With the help of this book, you'll get to build your own blockchain prototype and a decentralized network by using the JavaScript programming language. Building your own blockchain will help you understand various concepts related to blockchains, such as how blockchain technology works under the hood, how decentralized blockchain networks function, and how to code the blockchain and decentralized network using JavaScript. Also, you will get to learn why blockchain is such a secure and valuable technology.
The blockchain that you'll build throughout this book will have functionalities that are similar to those you would find on a real-life blockchain, such as Bitcoin or Ethereum. Your blockchain will have functionalities such as the ability to mine new blocks, create new and immutable transactions, and perform a proof of work to secure the blockchain. In addition to these, your blockchain will consist of many other important features. You'll get to explore those as you read further through the chapters.
When you have completed this book, you will have a thorough understanding of how blockchain technology actually works and why this technology is so secure and valuable. You will also have a deep understanding of how decentralized blockchain networks function and why decentralization is such an important feature for securing the blockchain.
Learn Blockchain Programming with JavaScript is for JavaScript developers who wish to learn about blockchain programming or build their own blockchain using JavaScript frameworks.
Chapter 1, Setting Up the Project, covers what a blockchain actually is and enables readers to understand how it functions. Then, you'll get to learn how to set up a project in order to create your very own blockchain.
Chapter 2, Building a Blockchain, covers how to add various functionalities to your blockchain. You will implement the functionalities in the blockchain, creating some amazing methods such as createNewBlock, creatNewTransaction, and getLastBlock. Once these methods are added to the blockchain, you will test them to verify that they are working perfectly. Also, you'll get to learn about the hashing method, that is, SHA256 hashing, and then implement a method to generate a hash for your block data. Also, you'll get to explore what a proof of work is, how it benefits the blockchain, and how to implement it.
Chapter 3, Accessing the Blockchain through an API, explains how to set up Express.js in your project, as well as how to use it to build the API/server. Then, you will build various server endpoints for your blockchain and test these endpoints to verify whether or not they are working properly.
Chapter 4, Creating a Decentralized Blockchain Network, covers how to set up a decentralized network for your blockchain. In this chapter, you will get to learn a lot of new concepts related to how to set up various nodes and interconnect them to form a network. You'll also define various endpoints, such as /register-and-broadcast-node, /register-node, and /register-nodes-bulk. These endpoints will assist you in implementing the decentralized blockchain network.
Chapter 5, Synchronizing the Network, explains how to synchronize the entire decentralized blockchain network so as to have the same transaction data and blocks on all the nodes in the blockchain. You'll implement network synchronization by refactoring the endpoints to broadcast the data to all the nodes present in the network.
Chapter 6, Consensus Algorithm, explains how to build your own consensus algorithm, which implements the longest chain rule. Through implementing this algorithm, you will have built a blockchain that is similar to a real-life blockchain.
Chapter 7, Block Explorer, explains how to build an amazing user interface to explore the blockchain that you have built over the course of the book.
Chapter 8, In Conclusion..., provides a quick summary of everything you will have learned throughout the course of this book. You will also explore what more you can do to improve the blockchain that you have developed.
A basic knowledge of JavaScript is recommended. You will also be required to install Node.js on your system.
The code and implementation of examples in this book were executed on macOS. However, if you want to implement all of these using a Windows PC, you will have to install the necessary requirements for it.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-Blockchain-Programming-with-JavaScript. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Welcome to Learning Blockchain Programming with JavaScript. As the name suggests, in this book, you'll learn how to build a fully functional blockchain from scratch using the JavaScript programming language. The blockchain that you build will have functionalities that are similar to those you would find in a production-level blockchain for examples such as Bitcoin or Ethereum.
In this book, you will understand how blockchain technology actually workes by learning to build your own blockchain and understanding the decentralized network. Toward the conclusion of the book, you will have a full-fledged blockchain prototype that is hosted on a decentralized network, and you'll have gained a great deal of knowledge and understanding as to how blockchains actually work under the hood.
The blockchain that we will create throughout this book will be able to carry out the following functionalities:
Perform a proof of work to secure the blockchain
Create new blocks through a mining process
Create new, immutable transactions
V
alidate the entire blockchain and all of the data within each block
Retrieve address/transaction/
block data
Along with these, the blockchain will have many other important features. You'll get to explore those as you read further through the chapters.
To follow this book, all you'll need is a computer and some basic knowledge of the JavaScript programming language.
Firstly, in this introductory chapter, let's try to understand what blockchain actually is. This will help you to become familiar with the concept of blockchain, as this is a prerequisite for the book. Then we'll move on to learn how to set up the project to create our own blockchain.
So, let's get started!
In this section, let's go through a brief explanation of what a blockchain is. Simply put, a blockchain is an immutable, distributed ledger. Now, these words may seem quite complex, but when we try to break them down, it is very easy to understand them. Let's begin by exploring what a ledger actually is. A ledger is simply a collection of financial accounts or transactions (or in other words, a record of transactions that people have made).
Let's take a look at the following example to get a better understanding of ledgers. In this example, Kim paid Joe $30 and Kevin paid Jen $80. A ledger is simply a document that is used to keep track of these transactions. You can see this depicted in the following screenshot:
Now, what does it mean for a blockchain to be immutable? This means that it cannot be changed—ever. Consequently, when a transaction is recorded, it cannot be undone. Other factors that cannot be changed include the amount of money that was sent or the people who took part in the transaction. Once a transaction is made, no aspects of that transaction can be changed because it is immutable.
In the world today, we see many applications, platforms, and networks that are all centralized. Take Facebook, for example. Everyone who uses Facebook has to trust this company is protecting their data and not abusing it. Compared to this, blockchain is different. Blockchain technology is not centralized like Facebook, Google, or most other entities. Instead, it is a distributed network, which means that any given blockchain network is not controlled by a single entity, but is run by normal, everyday people. Blockchains, such as Bitcoin, are supported and hosted by thousands of people worldwide. Consequently, all of our data, or the ledger in this case, is not at the mercy of a single company or entity. This proves to be a great benefit of blockchain technology because by being distributed, we do not have to trust a single company with our data. Instead, our data is persisted by the entire network of thousands of different people who are all acting independently.
Each individual who contributes to the blockchain network is called a node, and each node has the exact same copy of the ledger. Therefore, the ledger data is hosted and synchronized across the entire network.
So, a blockchain is an immutable distributed ledger. This means that it is a ledger in which the transactions can never be changed and the blockchain itself is distributed across the network and run by thousands of independent people, groups, or nodes.
The blockchain is a very powerful technology which is still in its infancy, but its future is very exciting. There are many ways that blockchain technology can be applied to our world today to make certain industries more secure, efficient, and trustworthy. Some industries that could be transformed with the help of blockchain technology include financial services, healthcare, credit, governments, energy industries, and many others. Pretty much every industry out there could benefit from a more secure, distributed form of data management. You can observe that blockchain technology is at a very exciting stage right now, and many people are excited about what the future holds for it.
Now that we're aware of what blockchain is, let's move onto setting up our project environment to build our blockchain.
This book will help you to gain a deeper understanding of blockchain technology by building your own blockchain from scratch. Blockchain is a fairly new technology, and while it can seem tough and slightly overwhelming to learn at first, we're going to take a step-by-step approach and break it down in order to understand how it works under the hood. By the time you finish this book, you will have a very solid understanding of how blockchain technology works, and you will have built your own entire blockchain as well.
In this book, we will start by building the blockchain itself. At this point, we will build a blockchain data structure that has the following abilities:
Proofing work
Mining new blocks
Cr
eating transactions
Validating the chain
Retrieving address data and other functionalities
Thereafter, we will create an API or a server that will allow us to interact with our blockchain from the internet. Through our API, we will be able to use all of the functionality that we have built into our blockchain data structure.
Furthermore, you'll be learning to create a decentralized network. This means that we'll have multiple servers running and acting as separate nodes. We'll also make sure that all of the nodes interact with each other properly and share data with each other in the correct format. In addition, you'll learn how to synchronize the entire network by making sure that any new nodes or transactions that are created are broadcast throughout the entire network.
We'll then move onto creating a consensus algorithm. This algorithm will be used to make sure that our entire blockchain stays synchronized and that this algorithm will be used to make sure that each node in our network has the correct blockchain data.
Finally, we will create a block explorer. This will be a user interface that will allow us to explore our blockchain in a user-friendly manner, and it will also allow us to query our blockchain for specific block transactions and addresses.
Firstly, however, we need to set up our development environment.
Let's get started with building our blockchain project. The first thing we're going to do is open our terminal and create our blockchain directory by typing commands into the terminal, as seen in the following screenshot:
Let's begin by creating a folder called programs. Inside this folder, let's create a directory called blockchain. This directory is currently empty. Inside of this blockchain directory is where we're going to be doing all of our programming. We are going to be building our entire blockchain inside of this blockchain directory.
Now our blockchain directory is ready, and the first thing that we need to do is to add some folders and files into it. The first folder that we want to put into the directory will be called dev, so we want to make sure that we are inside of the blockchain directory, and then let's type the following command into the terminal:
mkdir dev
Inside this dev directory is where we are going to be doing most of our coding. This is where we're going to build our blockchain data structure and create our API to interact with our blockchain, test it, and fulfill other similar tasks. Next, inside this dev folder, let's create two files: blockchain.js and test.js. To do this, enter the following command:
cd devtouch blockchain.js test.js
The touch term in the preceding command line will help us in creating the mentioned files. The blockchain.js file is where we will type our code to create the blockchain and the test.js file is where we will write code to test our blockchain.
Next, let's return back to our blockchain directory by typing the following command in the terminal:
cd ..
In the blockchain directory, let's run the following command to create the npm project:
npm init
After running the preceding command, you will get some options on your terminal. To set up the project, you can just press Enter through those options.
So, this is pretty much all we need to do in order to set up our project folder structure. Now, if you go to our blockchain directory and open it with a text editor such as Sublime or Atom (or whatever you would like), you will get to see the file structure, as seen in the following screenshot:
The blockchain directory consists of the dev folder that we just created. Inside the dev folder, we can observe our blockchain.js and test.js files. Also, when we run the npm init command, it creates the package.json file for us. This .json file will keep track of our project and any dependencies that we need, allowing us to run scripts. We'll be working more inside of this package.json file in further chapters, so you'll become more familiar with it as we progress through the book.
Before we start coding our blockchain, it is worth noting that the entire source code for this book can be found on GitHub at the following link: https://github.com/PacktPublishing/Learn-Blockchain-Programming-with-JavaScript. In this repository, you'll find the completed code for the entire project, and you will also be able to explore all of the files that we will be building in further chapters. Therefore, this may be a good resource for you to use as you make your way through the book.
To summarize this introductory chapter, we began by exploring what a blockchain actually is and understanding how it functions. Then we moved onto setting up our project to create our very own blockchain. We also had a quick overview of all of the topics you'll get to learn about in this book.
In the next chapter, we'll build our blockchain by learning about the constructor function, prototype object, block method, transaction method, and many more important concepts.
In the previous chapter, we learned about what a blockchain is and how it functions. In addition, we learned how to set up a project to build our blockchain. In this chapter, you will begin building the blockchain and all of its functionalities. First, let's create the blockchain data structure using a constructor function, and then we'll add a lot of different types of functionalities to our blockchain by adding different methods to its prototype.
We're then going to give the blockchain certain functionalities, such as creating new blocks and transactions, as well as the ability to hash data and blocks. We'll also give it the ability to do a proof of work and many other functionalities that a blockchain should be able to do. We'll then make sure that the blockchain is fully functional by testing the added functionalities as we progress.
By building each piece of the blockchain step by step, you will gain a better understanding of how blockchain actually works under the hood. You may also realize that once you dive into it, creating a blockchain is not as complicated as it sounds.
In this chapter, we'll cover the following topics:
Learning how to create a Blockchain constructor function
Building and testing various methods such as
createNewBlock
,
createNewTransaction
, and
hashBlock
