Customer Feedback Preface What this book covers What you need for this book Who this book is for Conventions Reader feedback Customer support Downloading the example code Downloading the
Trang 2Mastering Blockchain
Trang 3Table of Contents
Mastering Blockchain
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Customer Feedback
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this bookErrata
Types of consensus mechanism
The history of blockchain
Trang 4Platforms for smart contracts
Transferring value between peers
Applications of blockchain technology
How blockchains accumulate blocks
Tiers of blockchain technology
Delegated Proof of Stake
Proof of Elapsed Time
Deposit-based consensus
Proof of importance
Federated consensus or federated Byzantine consensusReputation-based mechanisms
Practical Byzantine Fault Tolerance
CAP theorem and blockchain
Benefits and limitations of blockchain
Trang 5Decentralized autonomous organizations
Decentralized autonomous corporations
Decentralized autonomous societies
Trang 6Block encryption mode
Keystream generation modes
Message authentication modes
Cryptographic hashes
Electronic code book
Cipher block chaining
Counter mode
Data Encryption Standard (DES)
Advanced Encryption Standard (AES)
Encryption and decryption using RSA
Elliptic curve cryptography (ECC)
Mathematics behind ECC
Point addition
Point doubling
Trang 7Discrete logarithm problem
How to generate public and private key pairs
Private key
Generate public key
How to encrypt and decrypt using RSA with OpenSSLEncryption
Decrypt
ECC using OpenSSL
ECC private and public key pair
Secure Hash Algorithms (SHAs)
Design of Secure Hash Algorithms (SHA)
SHA-256
Design of SHA3 (Keccak)
OpenSSL example of hash functions
Message Authentication codes (MACs)
MACs using block ciphers
HMACs (hash-based MACs)
Merkle trees
Patricia trees
Distributed hash tables (DHTs)
Digital signatures
Sign then encrypt
Encrypt then sign
Elliptic Curve Digital signature algorithm (ECDSA)
How to generate a digital signature
ECDSA using OpenSSL
Trang 8Orders and order properties
Order management and routing systemsComponents of a trade
Keys and addresses
Public keys in bitcoin
Private keys in bitcoin
Bitcoin currency units
Base58Check encoding
Vanity addresses
Transactions
The transaction life cycle
The transaction structure
The script language
Commonly used Opcodes
Types of transaction
Coinbase transactions
What is UTXO?
Transaction feeContracts
Transaction malleabilityTransaction pools
Transaction verificationBlockchain
The structure of a block
The structure of a block header
The genesis block
Trang 9The hashing rate
Paper walletsHardware walletsOnline walletsMobile walletsBitcoin payments
Bitcoin investment and buying and selling bitcoinsBitcoin installation
Setting up a bitcoin node
Setting up the source code
Setting up bitcoin.conf
Starting up a node in testnet
Starting up a node in regtest
Starting up a node in live mainnet
Experimenting with bitcoin-cli
Bitcoin programming and the command-line interfaceBitcoin improvement proposals (BIPs)
Difficulty adjustment and retargeting algorithmsKimoto Gravity Well
Trang 10Dark Gravity Wave
Reward halving rate
Block size and transaction size
Trang 11Ethereum clients and releases
The Ethereum stack
Ethereum blockchain
Currency (ETH and ETC)
Forks
Gas
The consensus mechanism
The world state
The account state
NonceBalanceStoragerootCodehashTransactions
Contract creation transaction
Message call transaction
Elements of the Ethereum blockchain
Ethereum virtual machine (EVM)
Execution environment
Machine stateThe iterator functionRuntime byte codeOpcodes and their meaning
Arithmetic operationsLogical operationsCryptographic operationsEnvironmental informationBlock Information
Stack, memory, storage and flow operations
Trang 12The RIPEMD-160 bit hash function
The identity function
The bloom filter
Transaction validation and execution
The transaction sub state
Trang 13The geth console
Funding the account with bitcoin
Trang 14Applications developed on Ethereum
Scalability and security issues
Summary
8 Ethereum Development
Setting up a development environment
Test Net (Ropsten)
Setting up a Private Net
Starting up the private network
Running Mist on Private Net
Deploying contracts using Mist
Development tools and clients
InstallationTools and libraries
Node.js version 7Local Ethereum block explorerEthereumJS
Contract development and deployment
Introducing solidity
Types
Value types
BooleanIntegersAddressArray value types (fixed size and dynamically sized byte arrays)Literals
Integer literalsString literalsHexadecimal literalsEnums
Function types
Internal functions
Trang 15External functionsReference types
ArraysStructsData locationMappings
Global variables
Control structures
EventsInheritanceLibrariesFunctionsLayout of a solidity source code fileIntroducing Web3
POST requests
The HTML and JavaScript frontend
Installing web3.js
ExampleDevelopment frameworks
Truffle
InstallationTesting using truffleBuild
Another exampleExample project: Proof of IdeaPermissioned distributed ledgersSummary
Trang 16Chaincode services
Events
APIs and CLIs
Components of the Fabric
Peers or nodes
Applications on blockchainChaincode implementationApplication model
CorDappDevelopment environment
Summary
10 Alternative Blockchains
Blockchains
Trang 17Ripple
Transactions
Payments relatedOrder relatedAccount and security relatedApplication layer
Transport layerInterledger layerLedger layerStellar
Rootstock
DrivechainQuorum
Transaction managerCrypto EnclaveQuorumChainNetwork managerTezos
IoT blockchain experiment
First node setup
Raspberry Pi node setup
Circuit
Trang 18Post trade settlement
Financial crime prevention
Media
Summary
12 Scalability and Other Challenges
Scalability
Block size increase
Block interval reduction
Invertible Bloom lookup tables
Secure multiparty computation
Usage of hardware to provide confidentialityCoinjoin
Confidential transactions
MimbleWimble
Security
Smart contract security
Why3 formal verification
Trang 19New programming languages
Hardware research and developmentResearch in formal methods and securityAlternatives to blockchains
Trang 21Mastering Blockchain
Trang 22Copyright © 2017 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 informationpresented However, the information contained in this book is sold without warranty, either express
or implied Neither the author, nor Packt Publishing, and its dealers and distributors will be heldliable for any damages caused or alleged to be caused directly or indirectly by this book
Packt Publishing has endeavored to provide trademark information about all of the companies andproducts mentioned in this book by the appropriate use of capitals However, Packt Publishing cannotguarantee the accuracy of this information
First published: March 2017
Trang 24About the Author
Imran Bashir has a M.Sc in Information Security from Royal Holloway, University of London, and
has a background in software development, solution architecture, infrastructure management, and IT
service management He is also a member of Institute of Electrical and Electronics Engineers (IEEE) and British Computer Society (BCS) Imran has sixteen years of experience in the public
and financial sectors He worked on large scale IT projects for public sector before moving to
financial services industry Since then he has worked in various technical roles for different financialcompanies in Europe’s financial capital, London He is currently working for an investment bank inLondon as Vice President in the technology department
I would like to thank the talented team at Packt including Ajith Menon, Nilesh Sawakhande,
Sumeet Sawant, and Tushar Gupta, who provided prompt guidance and very valuable feedback throughout this project I am also extremely thankful to the reviewer, Daniel Kraft, who provided constructive and very useful feedback that helped tremendously to improve the material in this book.
I thank my wife and children for putting up with my all-night and weekend-long writing sessions Finally, I would like to thank my parents, whose blessings on me have made everything possible for me.
Trang 25About the Reviewer
Daniel Kraft studied mathematics and physics, and holds a PhD in applied mathematics from the
University of Graz in Austria He has been involved in development with cryptocurrencies since
2013, has been the lead developer and chief scientist for both Namecoin and Huntercoin since 2014,and has published two research papers about cryptocurrency in peer-reviewed journals He works as
a software engineer and is a co-founder of Crypto Realities Ltd, a start-up that works on buildingdecentralised multi-player game worlds with blockchain technology
Trang 26For support files and downloads related to your book, please visit www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePub filesavailable? You can upgrade to the eBook version at www.PacktPub.com and as a print book
customer, you are entitled to a discount on the eBook copy Get in touch with us
at service@packtpub.com for more details
At www.PacktPub.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
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt Mapt gives you full access to all Packt books andvideo courses, as well as industry-leading tools to help you plan your personal development andadvance your career
Trang 28Customer Feedback
Thanks for purchasing this Packt book At Packt, quality is at the heart of our editorial process Tohelp us improve, please leave us an honest review on this book's Amazon page at
http://www.amazon.in/dp/1787125440
If you'd like to join our team of regular reviewers, you can e-mail us at
customerreviews@packtpub.com We award our regular reviewers with free eBooks and videos inexchange for their valuable feedback Help us be relentless in improving our products!
Trang 29It is recommended that readers have a basic understanding of computer science and basic
programming experience in order to benefit fully from this book However, if that is not the case thenstill this book can be read easily, as relevant background material is provided where necessary
Trang 30What this book covers
Chapter 1, Blockchain 101, introduces the basic concepts of distributed computing on which
blockchain technology is based It also covers history, definitions, features, types, and benefits ofblockchains along with consensus mechanisms that are at the core of blockchain technology
Chapter 2, Decentralization, covers the concepts of decentralization and its relationship with
blockchain technology Various methods and platforms that can be used to decentralize a process orsystem have also been introduced
Chapter 3, Cryptography and Technical Foundations, introduces the theoretical foundations
cryptography, which is necessary to fully understand blockchain technology Concepts such as publicand private key cryptography, with practical examples, are included Finally, an introduction to
financial markets is also included as there are many interesting use cases for blockchain technology inthe financial sector
Chapter 4, Bitcoin, covers Bitcoin, the first and largest blockchain It introduces technical concepts
related to bitcoin cryptocurrency in detail
Chapter 5, Alternative Coins, introduces alternative cryptocurrencies that were introduced after the
invention of Bitcoin It also presents examples of different altcoins, their properties, and how theyhave been developed and implemented.Chapter 6, Smart Contracts, provides an in-depth discussion
on smart contracts Topics such as history, the definition of smart contracts, Ricardian contracts,
Oracles, and the theoretical aspects of smart contracts are presented in this chapter
Chapter 7, Ethereum 101, introduces the design and architecture of the Ethereum blockchain in detail.
It covers various technical concepts related to the Ethereum blockchain that explains the underlyingprinciples, features, and components of this platform in depth
Chapter 8, Ethereum Development, provides a detailed practical introduction to development of
decentralized applications and smart contracts using the Ethereum blockchain An introduction tosolidity and different relevant tools have also been included in this chapter
Chapter 9, Hyperledger, presents a discussion about the hyperledger project from the Linux
foundation, which includes different blockchain projects introduced by its members
Chapter 10, Alternative Blockchains, introduces alternative blockchain solutions and platforms It
provides technical details and features of alternative blockchains
Chapter 11, Blockchain – Outside of Currencies, provides a practical and detailed introduction to
applications of blockchain technology in fields others than cryptocurrencies, including Internet ofThings, government, media, and finance
Chapter 12, Scalability and Other Challenges, is dedicated to a discussion of the challenges faced
Trang 31by blockchain technology and how to address them.
Chapter 13, Current Landscape and What’s Next, is aimed at providing information about the current
landscape, projects, and research efforts related to blockchain technology Also, some predictionsbased on the current state of blockchain technology have also been made
Trang 32What you need for this book
All examples in this book have been developed on Ubuntu 16.04.1 LTS (Xenial) As such, it is
recommended to use Ubuntu However, any appropriate operating system, either Windows or Linux,can be used, but examples, especially those related to installation, may need to be changed
accordingly
Examples related to cryptography have been developed using the OpenSSL 1.0.2g 1 Mar 2016
command-line tool
Ethereum solidity examples have been developed using Browser Solidity, available online
at https://ethereum.github.io/browser-solidity/ Ethereum's homestead release is used to developEthereum-related examples At the time of writing, this is the latest version available and can bedownloaded from https://www.ethereum.org/
Examples related to IoT have been developed using a Raspberry Pi kit by Vilros, but any latest model
or kit can be used Specifically, Raspberry Pi 3 Model B V 1.2 has been used to build a hardwareexample of IoT Node.js V7.2.1 and npm V3.10.10 have been used to download related packages andrun Node.js server for IoT examples
The Truffle framework has been used in some examples of smart contract deployment, and is
available at http://truffleframework.com/ Any latest version available via npm should be
appropriate
Trang 33Who this book is for
This book is for anyone who wants to understand blockchain technology in depth It can also be used
as a reference by developers who are developing applications for blockchain In addition, this bookcan also be used as a textbook for courses related to blockchain technology and cryptocurrencies Itcan also be used as a learning resource for various examinations and certifications related to
cryptocurrency and blockchain technology
Trang 34In this book, you will find a number of text styles that distinguish between different kinds of
information Here are some examples of these styles and an explanation of their meaning
Code words in text, database table names, folder names, filenames, file extensions, pathnames,
dummy URLs, user input, and Twitter handles are shown as follows:
"This line of code simply uses console.log to print the coinbase by calling web3.eth.coinbase
method."
A block of code is set as follows:
function difference(uint x) returns (uint y)
Any command-line input or output is written as follows:
$ geth datadir ethereum/PrivateNet/ networkid 786 rpc rpccorsdomain 'http://192.168.0.17:9900'
New terms and important words are shown in bold Words that you see on the screen, in menus or
dialog boxes for example, appear in the text like this: "Clicking the Next button moves you to the next
Trang 35Reader feedback
Feedback from our readers is always welcome Let us know what you think about this book-what youliked or disliked Reader feedback is important for us as it helps us develop titles that you will reallyget the most out of To send us general feedback, simply e-mail feedback@packtpub.com, and
mention the book's title in the subject of your message If there is a topic that you have expertise inand you are interested in either writing or contributing to a book, see our author guide
at www.packtpub.com/authors
Trang 36Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get themost from your purchase
Trang 37Downloading the example code
You can download the example code files for this book from your account at
http://www.packtpub.com If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files e-mailed directly to you
You can download the code files by following these steps:
1 Log in or register to our website using your e-mail address and password
2 Hover the mouse pointer on the SUPPORT tab at the top.
3 Click on Code Downloads & Errata.
4 Enter the name of the book in the Search box.
5 Select the book for which you're looking to download the code files
6 Choose from the drop-down menu where you purchased this book from
7 Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latestversion 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/Mastering-Blockchain We also have other code bundles from ourrich catalog of books and videos available at https://github.com/PacktPublishing/ Check them out!
Trang 38Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in thisbook The color images will help you better understand the changes in the output You can downloadthis file from
https://www.packtpub.com/sites/default/files/downloads/MasteringBlockchain_ColorImages.pdf
Trang 39Although we have taken every care to ensure the accuracy of our content, mistakes do happen If youfind a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if youcould report this to us By doing so, you can save other readers from frustration and help us improvesubsequent versions of this book If you find any errata, please report them by visiting
http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission
Form link, and entering the details of your errata Once your errata are verified, your submission will
be accepted and the errata will be uploaded to our website or added to any list of existing errata
under the Errata section of that title
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and
enter the name of the book in the search field The required information will appear under the Errata
section
Trang 40Please contact us at copyright@packtpub.com with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content