32,36 €
Implement blockchain principles in your choice of domain using Ethereum
Key Features
Book Description
The increasing growth in blockchain use is enormous, and it is changing the way business is done. Many leading organizations are already exploring the potential of blockchain. With this book, you will learn to build end-to-end enterprise-level decentralized applications and scale them across your organization to meet your company's needs.
This book will help you understand what DApps are and how the blockchain ecosystem works, via real-world examples. This extensive end-to-end book covers every blockchain aspect for business and for developers. You will master process flows and incorporate them into your own enterprise. You will learn how to use J.P. Morgan's Quorum to build blockchain-based applications. You will also learn how to write applications that can help communicate enterprise blockchain solutions. You will learn how to write smart contracts that run without censorship and third-party interference.
Once you've grasped what a blockchain is and have learned about Quorum, you will jump into building real-world practical blockchain applications for sectors such as payment and money transfer, healthcare, cloud computing, supply chain management, and much more.
What you will learn
Who this book is for
This book is for innovators, digital transformers, and blockchain developers who want to build end-to-end, decentralized applications using the blockchain technology. If you want to scale your existing blockchain system across the enterprise, you will find this book useful, too. It adopts a practical approach to solving real problems in enterprises using a blend of theory and practice.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 254
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: Sunith ShettyAcquisition Editor: Namrata PatilContent Development Editor: Chris D'cruzTechnical Editor: Suwarna PatilCopy Editor: Safis EditingProject Coordinator: Nidhi JoshiProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics:Tom ScariaProduction Coordinator: Nilesh Mohite
First published: September 2018 Production reference: 1250918
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78847-974-5
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.
Narayan Prusty is the founder and CTO of BlockCluster, world's first blockchain management system. He has five years of experience in blockchain. He specializes in Blockchain, DevOps, Serverless, and JavaScript. His commitment has led him to build scalable products for start-ups, governments, and enterprises across India, Singapore, USA, and UAE. He is enthusiastic about solving real-world problems. His ability to build scalable applications from top to bottom is what makes him special. Currently, he is on a mission to make things easier, faster, and cheaper using blockchain. Also, he is looking at ways to prevent corruption, fraud, and to bring transparency to the world using blockchain.
Nikhil Bhaskar is the founder and CEO of Ulixir Inc—a newly founded tech company that builds decentralized and traditional software. He completed B9lab's Ethereum Developer Course, and he is now a certified Ethereum developer. Aside from running Ulixir, he spends his time traveling and eating. He is a bit of a digital nomad; this year, he's lived in five countries and plans to live in six more before the year ends.
Ivan Turkovic is a geek, visionary, start-up enthusiast, writer, blogger, mentor, and advisor. He wrote the book PhoneGap Essentials. Since 2011 he has had a strong interest in Bitcoin and blockchain. In 2013 he co-founded a social start-up, Babberly, which was among the first to use gamification with the help of blockchain.
He is focused on bringing value to the internet users. He employs the latest technologies to build empowering web products and intuitive user experiences. He's interested in technology, entrepreneurship, education, behavior psychology, product management, and marketing. He runs Blaeg, a company that helps start-ups get off the ground with their blockchain technology.
Anand V. is a technology architect who has more than 20 years of experience in IT. He has worked with Verizon Communications, Cognizant, HP, HCL, and Oracle. Currently, he is the managing partner of Anasup Consulting and works with clients on emerging technologies such as blockchain, IoT, cybersecurity, and AI. He is also a specialist in the DevSecOps area and acts as a mentor to many start-up companies. He is a public speaker and regularly writes articles in journals as well as online channels.
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
Blockchain for Enterprise
Packt Upsell
Why subscribe?
packt.com
Contributors
About the author
About the reviewers
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
What are Decentralized Applications?
What is a DApp?
What is a blockchain?
Understanding Byzantine Fault Tolerance
Representation of user accounts 
What are UTXOs?
Popular permissioned blockchain platforms
Ethereum
Quorum
Parity
MultiChain
Hyperledger Fabric 1.0
BigchainDB
InterPlanetary File System
Corda
Transaction validity
Hyperledger Sawtooth
Popular blockchain use cases
Everledger
Walmart's food tracking 
Ghana's land registry 
Dubai's housing rental 
Project Ubin
Summary
Building Blockchain Using Quorum
Overview of Quorum
Ethereum accounts
What are Ethereum transactions?
What is a Merkle tree?
What is forking in blockchain?
Raft consensus
Istanbul Byzantine Fault Tolerence
Private contracts and constellation
Installing Quorum and constellation
Build your first Raft network
Setting up a constellation network
Generating enodes
Creating an account
Creating the genesis block
Starting nodes
Adding or removing nodes dynamically
Building your first IBFT network
Installing IBFT tools
Creating a genesis block
Starting nodes
Adding or removing a validator dynamically
Summary
Writing Smart Contracts
Solidity source files
The structure of a smart contract
Data locations in Solidity
The different types of data
Arrays
Strings
Structs
Enums
Mappings
The delete operator
Conversion between elementary types
Using var
Control structures
Creating contracts using the new operator
Exceptions
External function calls
Features of contracts
Visibility
Function modifiers
The fallback function
Inheritance
The super keyword
Abstract contracts
Libraries
using for
Returning multiple values
Importing other Solidity source files
Globally-available variables
Block and transaction properties
Address-type-related variables
Contract-related variables
Ether units
Proof of existence, integrity, and ownership contract
Compiling and deploying contracts
Summary
Getting Started with web3.js
Introduction to web3.js
Importing web3.js
Connecting to nodes
The API structure
BigNumber.js
Unit conversion
Retrieving gas price, balance, and transaction details
Sending ether
Working with contracts
Retrieving and listening to contract events
Building a client for the ownership contract
The project structure
Building the backend
Building the frontend
Testing the client
Summary
Building Interoperable Blockchains
Understanding blockchain interoperability
What can interoperable blockchains achieve?
Strategies for implementing blockchain interoperability
Single custodian
Multisignature federation
Sidechains or relays
Hash locking
Building a FedCoin
Smart contracts to digitalize fiat currency
Atomic swap smart contracts
Testing
Summary
Building Quorum as a Service Platform
Introduction to cloud computing
Private versus public versus hybrid cloud
IaaS versus PaaS and SaaS
What are containers?
Introduction to Docker
Building a Hello World Docker container
Understanding the microservices architecture
Diving into K8s
Getting into resource objects
Deployments and pods
Services
Ingress controllers and resources
ConfigMaps and secrets
Bind mounts and volumes
Labels and selectors
Getting started with minikube
Installing minikube on macOS
Installing minikube on Ubuntu
Installing minikube on Windows
Starting minikube
Stopping and deleting minikube 
Minikube status
Accessing the K8s dashboard
Deploying the Hello World app on k8s
Pushing images to Docker Hub
Creating deployments and services
Building QaaS
How does QNM work?
Containerizing QNM
Creating QNM deployment and service mainfest files
Creating nodes using the K8s APIs
Summary
Building a DApp for Digitizing Medical Records
Introduction to EMRs data management and sharing systems
Problems with paper-based medical records
Limitations of EMR data management and sharing systems
Centralized versus decentralized EMR management systems
Ensuring data privacy in a blockchain using PRE
The NuCypher PRE library
Installing the library
Using the library
Architecting DApp for EMRs
Smart contracts for identity and access control
Writing Python and JS scripts for testing
Summary
Building a Payment Solution for Banks
Overview of the payment system
Settlement and clearance of InterBank transfers
Digitalizing fiat currency
Using a cell phone number as identity
Building the network
Network permissioning in Quorum
Building the DApp
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Blockchain is growing massively, and is changing the way that business is done. Leading organizations are already exploring the possibilities of blockchain. With this book, you will learn how to build end-to-end, enterprise-level decentralized applications (DApps) and scale them across your organization to meet your company's needs. This book will help you understand what DApps are and the workings of the blockchain ecosystem with some real-world examples. This is an extensive end-to-end book covering every aspect of blockchain, such as its applications for businesses and developers. It will help you be aware of the process flows so you can incorporate them into your own enterprise. You will learn how to use J.P. Morgan's Quorum to build blockchain-based applications. You will also be introduced to how to write applications that can help communicate in enterprise blockchain solutions. You will learn how to write smart contracts that run without censorship and third-party interference.Once you have a good grip on what blockchain is and have learned all about Quorum, you will jump into building real-world practical blockchain applications for sectors such as payment and money transfer, healthcare, cloud computing, supply chain management, and much more.
This book is for innovators, digital transformers, and blockchain developers who want to build end-to-end DApps using blockchain technology. If you want to scale your existing blockchain system across the enterprise, you will find this book useful too. It gives you the practical approach needed for solving real problems in an enterprise using a blend of theory- and practice-based approaches.
Chapter 1, What are Decentralized Applications?, will explain what DApps are and provide an overview of blockchain-based DApps.
Chapter 2, Building Blockchain Using Quorum, introduces the basics of Ethereum blockchain and the features of Quorum. This chapter also teaches you how to set up a Raft network using Quorum and various third-party tools and libraries.
Chapter 3, Writing Smart Contracts, shows how to write smart contracts and use geth's interactive console to deploy and broadcast transactions using web3.js.
Chapter 4, Getting Started with web3.js, introduces web3.js and how to import and connect to geth, and explains how to use it in Node.js or client-side JavaScript.
Chapter 5, Building Interoperable Blockchains, explores what interoperable blockchains can achieve, the various technologies and patterns for achieving blockchain interoperability, and building interoperable blockchain networks to represent FedCoins.
Chapter 6, Building Quorum as a Service Platform, will teach you the basics of cloud computing and containerization by examples. You'll learn how to install minikube, deploy containers on Kubernetes, and develop a Quorum-as-a-service using QNM.
Chapter 7, Building a DApps for Digitizing Medical Records, gets into how to use proxy re-encryption to enable encrypted data sharing in blockchain. Besides proxy re-encryption, you'll also learn about a lot of JavaScript and Python libraries, such as etherumjs-wallet, ethereumjs-tx, ethereumjs-util, and npre. Also, you'll learn about signing transactions using keys stored outside a geth node.
Chapter 8, Building a Payment Solution for Banks, looks at how to implement network permissioning in Quorum and how to build a solution to transfer money using a mobile number.
You must have experience with the JavaScript and Python programming languages.
You must have developed distributed web applications before.
You must understand the basic cryptography concepts, such as signing, encryption, and hashing.
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/Blockchain-for-Enterprise. 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: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.
Since the beginning of internet, all internet-based applications that have been developed have been based on client-server architecture, where there is a centralized server that forms the backend of the application and controls the complete application. These applications often end up with issues such as having a single point of failure, failure to prevent net censorship, lack of transparency, users not trusting their data, activity and identity privacy, and so on. This centralized architecture even made it impossible to build certain kinds of applications. For example, you cannot build a digital currency using this architecture. Due to these issues, a new kind of architecture emerged called Decentralized Applications (DApps). In this chapter, we will learn about DApps.
In this chapter, we'll cover the following topics:
What are DApps?
What is the difference between decentralized, centralized, and distributed applications?
What is a blockchain?
What is the difference between public and permissioned DApps?
Examples of some of the popular consortium DApps, and how they work
What are the various popular platforms on which to build enterprise DApps?
A DApp is a kind of application whose backend runs on a decentralized peer-to-peer network, and its source code is open source. No single node in the network has complete control of the DApp. Remember that, when we say that an application is decentralized we mean technically it's decentralized but the governance can be distributed, decentralized, or centralized.
The major advantages of DApps are that they don't have a single point of failure, and prevent censorship. DApps do have some disadvantages: it's difficult to fix bugs or add features once deployed as everyone in the network has to update their node software, and it's very complicated to couple different DApps together as they are very difficult to build compared to centralized applications and involve very complex protocols.
To be able to use a DApp, you first need the DApp's node server running so that you can connect to the peer-to-peer network. Then, you need a client respective to the DApp that connects to the node server and exposes a UI or command line interface to use the DApp.
Currently, DApps are not yet as mature as centralized applications in terms of performance and scalability.There is still a lot of research and development on these topics such as performance, scalability, users identity, privacy, communication between DApps, data redundancy,and so on.A use case may fit into a DApp, but whether the use case can be made production-ready with the currently available technology can be a challenge. Popular examples of decentralized applications are Torrent, Bitcoin, Ethereum, Quorum, and so on.
A DApp can be public or permissioned. Public DApps are those which anyone can be part of, in other words, they are permissionless, whereas permissioned DApps are those which are not open for everyone to join, so you will need permission to join. A permissioned DApp is called a consortium DApp when the participants of the DApp are enterprises and/or government entities. Similarly, when the participants of a permissioned DApp are only enterprises, then we can call it an enterprise DApp. In this book we will learn everything about permissioned DApps.
Before we get into what a is, we need to understand what a ledger is. A ledger in computer science is software that stores transactions. A database is different from a ledger such that in a database we can add, remove, and modify records, whereas in a ledger we can only append but not delete or modify.
A blockchain is basically a data structure to implement a decentralized ledger. A blockchain is a chain of blocks connected to each other. Every block contains a list of transactions and certain other metadata, such as when it was created, which is it's previous block, the block number, who is the creator of the block, and so on. Every block maintains a hash of the previous block, therefore creating a chain of blocks linked with each other. Every node in the network should hold the complete copy of the blockchain and, when a new node comes in, it will request and download the blockchain from other nodes.
The major advantages of using a blockchain is that it enables the facilitation of transactions without a central trusted party; data is secured using cryptography, and data is immutable, as blockchain removes friction and reduces risk so settlements happen in real time, and so on. Basically, it automates auditing, makes the application transparent, and provides a single source of truth.
In the real world, private blockchains are used in trade finance, cross-border payments, digital identity, the clearing and settlement of tokenized and digital assets, provenance of ownership of a product, record keeping for critical data, signing contracts, multi-party aggregation (namely, they can be used as a shared master repository for common industry information, allowing members to query for data), payment-versus-payment or payment-versus-delivery, and so on.
Every blockchain node maintains a database that contains the blockchain's state. The state contains the final result of running all the transactions in the blockchain. For example, in a blockchain, the state represents the final balances of all addresses. So when you query the blockchain node for an addresses balance, it doesn't have to go through all transactions and calculate the final balance of the address; instead, it directly fetches the balance from the state of the blockchain. Bitcoin uses LevelDB to maintain the state of the blockchain. Even if the database gets corrupted, the database can be restored by simply running all the transactions in the blockchain.
Byzantine Fault Tolerance (BFT) is a characteristic of a decentralized system that indicates that it can tolerate Byzantine failures. A crash failure is when nodes just stopping to do anything (no messages at all) and Byzantine failure is when nodes just don't do anything or exhibit arbitrary behavior. Basically, Byzantine failures include crash failures.
In any decentralized computing environment where a blockchain data structure is used, there is a risk that one or more rogue or unreliable actors could be a reason for the environment to disband. A server cluster will not work well if a few servers within it lose out on passing data to other servers in a consistent manner. In order to be reliable, the decentralized computing environment has to be designed in a way that it has solutions to these kinds of Byzantine failures.
On blockchain-based decentralised applications, there is, by definition, no central authority, so a special kind of protocol called the consensus protocol is used to achieve BFT.
In simple terms, you must be wondering how to ensure that everyone has the same copy of the blockchain, and how to know which blockchain is correct when two nodes publish different blockchains? Also, how do you decide who creates the blocks, as there is nothing such as a master node in decentralized architecture? Well, consensus protocols provide an answer to these questions. A few examples of consensus protocols are Proof-of-Work (PoW), Proof-of-Stake (PoS), Proof-of-Authority (PoA), PBFT, and so on.
A consensus protocol is designed specially for permissioned or public blockchains. A consensus protocol made for a public blockchain is likely to create security and performance issues when implemented in a permissioned blockchain. Every consensus protocol has different performance and scalability vectors. You have to be alert while selecting a consensus protocol for your blockchain-based DApp.
You might have come across the term PoA. PoA is a categorisation of consensus protocols in which there is a set of authorities—nodes that are explicitly allowed to create new blocks and secure the blockchain. Ripple's iterative process, PBFT, Clique, Aura, and so on, are examples of PoA-based consensus protocols.
In blockchain-based applications, user accounts are identified and authenticated using asymmetric key pairs. The private key is used to sign transactions on behalf of the user. Username and password-based accounts systems will not work in blockchain as it cannot be used to prove which user has sent a transaction. The demerits in using private-public key pair include that they are not user-friendly and if you lose the private key then there is no way to recover it. So, it adds a new responsibility for the users to secure their private key. The address of a user account acts as the account identifier on blockchain. The address of a user account is derived from the public key.
Some blockchain applications use the UTXO model for transactions. Blockchain applications such as Bitcoin and MultiChain use this model. Even DLTs such as R3 Corda also use this model. Let's understand this model by understanding how Bitcoin transactions work.
In Bitcoin, a transactions is a collection of zero or more and outputs. These input and output objects are called Unspent Transaction Outputs (UTXO). Outputs of transactions are used as inputs of future transactions. A UTXO can be used as input only once. Each UTXO in Bitcoin contains a denomination and an owner (a Bitcoin address). In this model, the balances of addresses in the unconsumed UTXOs are stored. For a transaction to be valid, these requirements should be met:
The transaction must contain a valid signature for the owner of each UTXO that it consumes
The total denomination of the UTXOs consumed must be equal to or greater than the total denomination of the UTXOs that it produces
A user's balance is computed as the total sum of the denominations of UTXOs that they own. A transaction can consume zero or more UTXOs and produce zero or more UTXOs. For a miner to pay reward to itself, it includes a transaction in the block that consumes zero UTXOs but produces one UTXO with the denomination assigned the amount of Bitcoin it is supposed to award itself.
A UTXO transaction model is suitable when blockchain transactions involve the transfer of asset, but for non-assets transfer transactions such as recording facts, invoking smart contracts, and so on, this model it not suitable.
Now we have a basic idea about what a DApp, blockchain, and DLT is, let's have an overview of what platforms are available to build a permissioned blockchain applications and DApps. We will only go through the ones that are popular on the market, and for which there is a demand.
Ethereum is the most popular DApp after Bitcoin. Ethereum is a decentralized platform that allows us to build other blockchain-based DApps on top of it. In Ethereum, we build DApps using Ethereum smart contracts. Smart contracts are applications that run exactly as programmed without any possibility of downtime, censorship, fraud, or third-party interference. Ethereum can be thought of as a platform to deploy and run smart contracts. Ethereum supports two consensus protocols, PoW and PoA (Clique).
The main public Ethereum network uses PoW for consensus. If you want to deploy your own private Ethereum network, then you have to use PoA. PoW requires a lot of computation power to keep the blockchain secure, therefore it's good for public blockchain use, whereas PoA doesn't have any such computation power requirement; instead it requires a few authority nodes in the network to achieve consensus.
Quorum is a decentralized platform that allows us to build permissioned blockchain-based DApps on top of it. Actually, Quorum is a fork of Ethereum (actually Quorum is a fork of Go Ethereum, which is an implementation of Ethereum using Golang), therefore if you have ever worked on Ethereum then you will find it easy to learn and build permissioned blockchains using Quorum. Many
