Blockchain Quick Start Guide - Xun (Brian) Wu - E-Book

Blockchain Quick Start Guide E-Book

Xun (Brian) Wu

0,0
23,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Blockchain is a technology that powers the development of decentralized applications.This technology allows the construction of a network with no single control that enables participants to make contributions to and receive benefits from the network directly.

This book will give you a thorough overview of blockchain and explain how a blockchain works.You will begin by going through various blockchain consensus mechanisms and cryptographic hash functions. You will then learn the fundamentals of programming in Solidity – the defacto language for developing decentralize, applications in Ethereum. After that, you will set up an Ethereum development environment and develop, package, build, and test campaign-decentralized applications.The book also shows you how to set up Hyperledger composer tools, analyze business scenarios, design business models, and write a chain code. Finally, you will get a glimpse of how blockchain is actually used in different real-world domains.

By the end of this guide, you will be comfortable working with basic blockchain frameworks, and develop secure, decentralized applications in a hassle-free manner.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 226

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Blockchain Quick Start Guide

 

A beginner's guide to developing enterprise-grade decentralized applications

 

 

 

 

 

 

Xun (Brian) Wu
Weimin Sun

 

 

 

 

 

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Blockchain Quick Start Guide

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(s), 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: Amey VarangaonkarAcquisition Editor: Reshma RamanContent Development Editor:Mohammed Yusuf ImaratwaleTechnical Editor: Jinesh TopiwalaCopy Editor: Safis EditingProject Coordinator: Kinjal BariProofreader: Safis EditingIndexer: Mariammal ChettiyarGraphics:Alishon MendonsaProduction Coordinator :Deepika Naik

First published: December 2018

Production reference: 1241218

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78980-797-4

www.packtpub.com

 
mapt.io

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.

Why subscribe?

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

Packt.com

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. 

Contributors

About the authors

Xun (Brian) Wu is an author, founder, and advisor. He has over 17 years of extensive hands-on experience in the design and development of blockchain, big data, cloud, UI, and system infrastructure. He has worked for top investment banks including JP. Morgan, Citigroup, and the Bank of America. He is the co-author of Seven NoSQL Databases in a Week, Hyperledger Cookbook, and Blockchain By Example,published by Packt. He has been a technical reviewer for more than 50 computer technical books for Packt Publishing. He serves as a board advisor for several blockchain start-ups. He owns several patents on blockchain. Brian holds a master's degree in computer science from NJIT. He lives in New Jersey with his two beautiful daughters, Bridget and Charlotte.

I would like to thank my parents, wife, and kids for their patience and support throughout this endeavor. I'd also like to thank Jianmin Liu, Ryan, and the many others who provided help and inspiration along the way.

 

Weimin Sun has 20 years of experience of working in the financial industry. He has worked for top-tier investment and commercial banks such as J.P. Morgan, Bank of America, Citibank, and Morgan Stanley. He has managed large teams developing IT applications. He has held corporate titles such as Executive Director and Senior VP. He has in-depth knowledge of blockchain technology, data architecture, data modeling, data science, and big data platforms. He is an expert in designing data-driven solutions. He has a Ph.D, an M.B.A, and an M.Sc. He has published several papers on statistics in renowned academic journals. Weimin lives in New Jersey, USA, with his beautiful wife and his talented son.

I would like to thank my wife and son for their lasting support and love. I express my gratitude and appreciation to Ryan Duan for proofreading the entire book and helping to improve the book's quality greatly. I want to thank Professor Yang, Yixian for permitting me to use his idea of making the genealogy analogy to describe blockchain.

About the reviewers

Aasim Ali is a full-stack blockchain engineer at Inncretech LLC, Princeton, New Jersey. He has a master's degree in information systems with a graduate certification in business intelligence from Stevens Institute of Technology, Hoboken, New Jersey. He works with the blockchain and data science R&D team making POCs around AI, Ethereum, and Hyperledger for clients to incorporate in their proprietary systems, which helps them upgrade to new cutting-edge technologies.

I would like to thank my family and friends for supporting me through my journey of life, which helped me grow into a knowledgeable and intellectual person. I would also like to express my special gratitude to my company's co-founder and CTO for believing in me and giving me this opportunity to explore blockchain in depth. I would sincerely like to thank the author and his team for giving me the opportunity to review this book.

 

F. Richard Yu is the chair of the IEEE P2418.3/4 blockchain standards, IEEE fellow, IET fellow, and professor at Carleton University, Canada. He is the leading general co-chair of IEEE conference on blockchain, 2019. Professor Yu has published 6 books and over 490 papers in international top-tier academic journals and conferences, with over 13,000 citations and an H-index of 63. He holds 27 international patents, and his innovative works have been incorporated into industry standards, impacting on millions of pieces of network equipment and billions of mobile devices. He received his PhD from the University of British Columbia (UBC) in 2003.

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Blockchain Quick Start Guide

About Packt

Why subscribe?

Packt.com

Contributors

About the authors

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

Introduction to Blockchain Technology

The genealogy analogy

Bitcoin

Why Bitcoin

A peer-to-peer network

Cryptography and hash functions

The distributed ledger, blocks, transactions, addresses, and UTXO

The consensus mechanism

Forking

Mining and difficulty level

Hacking – the 51% problem

Private keys and Bitcoin wallets

Bitcoin scripting

Altcoins

Ethereum

Enterprise blockchain – Hyperledger

The evolution of blockchain

Summary

Ethereum Fundamentals

An overview of Ethereum

Ethereum basic concepts

Ether

ERC20 tokens

Smart contracts

Ethereum virtual machines

Ethereum gas

Account

Oracle

Other concepts

Performance

Throughput

Proof-of-Stake (PoS)

Casper

Plasma

Sharding

Summary

Overview of Solidity Programming

What is solidity?

Tools for solidity development environment

Browser-based IDE

Remix

EthFiddle

Command-line development management tools

Truffle

Introduction to smart contracts

Layout of a solidity source file

Pragma

Comments

Import

Paths

Relative paths

Structure of a contract

State variables

Data type

Enum type

Struct type

Mapping

Functions

Input parameters

Access modifiers

Output parameters

Modifiers

Events

Constructor

Constant state variables, unit, and functions

Ether units

Time units

Inheritance, abstract, and interface

Common smart contract patterns

Access restriction

State machine

Smart contract security

Keep contract simple and modular

Use the checks-effects-interactions pattern

DoS with block gas limit

Handle errors in external calls

Case study – crowdfunding campaign

Summary

Building an Ethereum Blockchain Application

Decentralized application overview

web3.js quick overview

Provider

DApp development tools

Truffle

Ganache

Setting up an Ethereum development environment

Installing Truffle

Installing Ganache

Creating a Truffle project

Launching the Ganache environment

Deploying a smart contract

Writing a campaign decentralized application

Selecting a web3 provider

Loading account information

Loading project information

Handling the fund function

checkGoalReached

Summary

Exploring an Enterprise Blockchain Application Using Hyperledger Fabric

Key concepts in Hyperledger Fabric

Ledger

Chaincode

Channel

Core component model

Peers

Membership service provider (MSP)

Certificate authority (CA)

Ordering service

Hyperledger Fabric basic transaction flow

Issuance claim

Setting up a Hyperledger Fabric environment

Installation prerequisites

Installing Hyperledger Fabric

Writing chaincode

Development tools

LiteIDE 

JetBrains Gogland

Visual Studio Code

Chaincode key concept and APIs

Defining an issuance claim

Initializing the chaincode

Invoking the chaincode

AddCompany

ReportLost

RequestedInfo

SubmitClaim, ConfirmClaimSubmission, ApproveClaim

Query

getHistory

Configuring Hyperledger Fabric

Generating the certificate

Generating an orderer genesis block

Generating a channel configuration transaction

Overview of Hyperledger Fabric Docker composer configuration files

Fabric project directory structure

Docker-compose-base.yaml

Peer-base.yaml

Starting the Hyperledger Fabric network

Creating a channel

Joining channels

Updating the anchor

Installing chaincode

Instantiating the chaincode

Invoking add broker

Invoking add insurer

Invoking ReportLost

Invoking RequestedInfo

Invoking SubmitClaim

Invoking ConfirmClaimSubmission

Invoking ApproveClaim

Querying claim history

End-to-end test execution 

Summary

Implementing Business Networks Using Hyperledger Composer

Hyperledger Composer – a quick overview

Yeoman generator

Composer REST server

LoopBack connector

JavaScript SDK

Composer playground

Composer-cli

Setting up a Hyperledger Composer environment

Installation prerequisites

Installing the development environment

Analyzing business scenarios

Business network archive

Network model file (.cto)

Script file (.js)

Access control list (ACL) file (.acl)

Query file (.qry)

Designing business models

Implementing the business transaction function

Testing in the playground

Deploying a business network

Integrating with REST server

Generating the Hyperledger Composer REST API

Summary

Blockchain Use Cases

Blockchain use case examples

Payment and settlement services

Import and export finance

Immutable ledger

Regulatory compliance and auditing

Identity theft detection

Funds back-office operation

Collateral management

Healthcare systems

Real estate trading and rental markets

IP market

Elections

HR and recruiting

Public records

Reduce contract disputes

Sharing economy

Integration with IoT

Facilitate commercial and social relationships

How to choose a proper use case

DApp use case – healthcare data sharing

The business problem

A blockchain solution

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Just as we were at the dawn of the internet age in the nineties, we are at the dawn of the blockchain age now. This new technology will disrupt existing business models and give birth to new ones. It will inspire the emergence of community economies built on blockchain networks, where every participant makes contributions to and receives benefits from the community. There will no longer be a single entity controlling and receiving dividends from the economy.

Thanks to its immutability, transparency, and the consensus mechanism for avoiding double-spending, along with other clever designs such as blocks chained with the hashes of the previous blocks, the technology allows untrusting parties to trade with each other directly. As a result, most of the intermediary services currently provided by existing institutions will no longer be needed. As a consequence, blockchain technology is receiving attention the world over.

There are many articles and books on blockchain. However, there are no good books serving beginners who are looking for a quick way to gain a good understanding of the technology as a whole and learn what's needed to be able to develop a complete blockchain application. This quick guide fills in this gap. The book covers coding details on how to develop blockchain applications on Ethereum and Hyperledger Fabric, the two most popular platforms for public and enterprise blockchain, respectively.

Who this book is for

This book benefits readers who are new to the blockchain technology and want to learn about its basics and jump start their development of smart contracts and Decentralized Applications (DApps). Business readers can especially gain from the first two chapters along with the last chapter, which cover what business issues need to be addressed and what possible use cases there are for blockchain. IT readers should read all the chapters and learn how to develop smart contracts and DApps via the many working examples presented in this book.

What this book covers

Chapter 1, Introduction to Blockchain Technology, gives an overview of blockchain and its key concepts, such as cryptography and hash algorithms, the distributed ledger, transactions, blocks, proof of work, mining, and consensus. We cover Bitcoin, the mother of blockchain technology, in detail. We briefly introduce Ethereum by pointing out some limitations of Bitcoin and how they are addressed by Ethereum. While Bitcoin and Ethereum are examples of public blockchains, IBM's Hyperledger is used as an example of enterprise blockchains. Toward the end of this chapter, we look at the evolution of blockchain, through 1.0, 2.0, 3.0, and beyond, and we examine their use cases.

Chapter 2, Ethereum Fundamentals, covers the basic concepts of Ethereum, such as smart contracts, ether, consensus algorithms, EVM, gas, and accounts. We will discuss Ethereum performance and review ideas on how to improve the overall performance via proof of work, casper, plasma, and sharding.

Chapter 3, Overview of Solidity Programming, discusses what solidity is, as well as the tools for the solidity development environment. We then discuss smart contracts and their common patterns. We cover the important topic of smart contract security. Finally, we show how to write a smart contract with a use case of crowdfunding.

Chapter 4, Building an Ethereum Blockchain Application, looks at what a DApp is. We give a quick overview of web3.js. We explain how to set up an Ethereum development environment, as well as how to develop and test a DApp.

Chapter 5, Exploring an Enterprise Blockchain Application Using Hyperledger Fabric, gets into the key concepts of Hyperledger Fabric, along with the core components. We explain how to create a Hyperledger Fabric environment, how to write a chaincode, and how to set up Hyperledger Fabric configuration.

Chapter 6, Implementing a Business Network Using Hyperledger Composer, provides an overview of Hyperledger Composer and talks about how to set up a Hyperledger Composer environment. We discuss business scenarios, the business network archive, and how to implement a business transaction function.

Chapter 7, Blockchain Use Cases, first talks about popular blockchain use cases across industries, including the financial sector, civil services, supply chains, the Internet of Things (IoT), and healthcare, at a high level. We will then proceed to a discussion of the proper use cases for DApps, before then developing a successful DApp. Finally, we take the health data-sharing use case and comment at a high level on building an DApp for it.

To get the most out of this book

We've focused on organizing the book to fit business and IT beginners in blockchain technology. The chapters are arranged to ensure that they can be followed easily and flow naturally.

Business users can skip the chapters with detailed descriptions on how to develop blockchain applications and, instead, focus on the chapters with general descriptions of the technology and use cases.

Veteran IT professionals on blockchain can skip the general description chapters and focus on chapters either on Ethereum or Hyperledger, from which they will gain insights on how to build blockchain applications.

It is recommended that IT users download the code and make modifications for adopting to their own use cases or exercises.

Download the example code files

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-Quick-Start-Guide. 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!

 

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "One important interface is ChaincodeStubInterface, which provides functions that allow you to query, update, and delete assets in the ledger."

A block of code is set as follows:

contract SimpleStorage { uint storedData; // State variable //…}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

pragma solidity ^0.4.15;import 'zeppelin/contracts/math/SafeMath.sol';….contract ExampleCoin is ERC20 { //SafeMath symbol is from imported file SafeMath.sol' using

SafeMath

for uint256; …}

Any command-line input or output is written as follows:

mkdir ~/insurance-claim && cd ~/insurance-claim

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "When the preceding request is validated by mining nodes, the HelloWorld smart contract is invoked."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

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.

Reviews

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.

Introduction to Blockchain Technology

Blockchain technology will disrupt current business models by making intermediary services obsolete. The term blockchain has become a buzzword worldwide. IT technologists are picking up blockchain books in flocks and starting to read about it in the hope of mastering the basic concepts. People are motivated to become professional blockchain application developers. Unless you pick up a well-written book, it often requires you to read many books and articles before the concepts of the blockchain become clear. To assist you in gaining a concise view of how an end-to-end blockchain application works, we outline a high-level introduction of the basic concepts along with the code-level details explaining how an actual application can be developed step by step. At the end of this book, we cover blockchain use cases in examples to inspire you to work on life-changing projects.

In this chapter, we give an overview of blockchain, along with its key concepts such as cryptography and hash algorithms, the distributed ledger, transactions, blocks, proof of work, mining, and consensus. We cover Bitcoin, the mother of blockchain technology, in detail. We briefly introduce Ethereum by pointing out some limitations of Bitcoin and how they are addressed by Ethereum. While Bitcoin and Ethereum are examples of public blockchains, IBM's Hyperledger is used as an example of enterprise blockchains. At the end of this chapter, we mention the evolution of the blockchain: blockchain 1.0, 2.0, 3.0, and beyond, based on their use cases. Specifically, we will cover the following topics on blockchain:

A genealogical analogy for blockchain

The Bitcoin consensus mechanism

A brief discussion of Hyperledger 

Blockchain evolution

The genealogy analogy

One of the authors recently attended a Chinese university alma mater reunion event in Beijing, where blockchain became a hot discussion topic. A very well-regarded schoolmate and scholar, Professor Yang, who has authored books on cryptography and public data safeguards, used genealogy to describe a blockchain. This is a well-thought-out analogy since it explains blockchain intuitively and easily. The analogy is borrowed here to illustrate the basic ideas behind the technology. 

Back in the old days in China, it was a custom for each family of a clan (sharing the same last name) to keep a copy of the genealogical tree of the clan. When members of a family changed due to either marriage or the birth of an offspring, as well as adoption, the new member's name would appear in each copy. However, the new member had to be accepted by the clan before the name could be added in. There were cases when a marriage was not endorsed by a majority of the clan due to various reasons. In this case, the new member's name would not be entered into the genealogy. In other words, when a new member joined in a family, the news was broadcast to other families of the clan. If the clan reached a consensus on accepting the new member, each family would update their copy of the genealogical tree to reflect the change. On the other hand, if the clan decided not to accept the new member, the name would not be added in. The genealogy could be used for verification purposes. For example, if a stranger made a claim to be a member of the clan, or two people with the same last name were eager to find out whether they shared the same ancestor, with the genealogy, it was easy to verify this. The outcome would be accepted since the genealogy was considered reliable thanks to the aforementioned consensus and decentralized records, which were difficult to manipulate unless the majority of families agreed.

A blockchain shares many of the characteristics of a genealogy. They are summarized as follows:

Like a clan consisting of many related families, a blockchain network consists of nodes. Each node is like a family.

Like 

every family keeping a copy of the clan's genealogy, each node of a blockchain maintains a copy of all transactions that have occurred on the chain, starting from the very beginning. The collection of all transactions is a

ledger

. This makes a blockchain a decentralized data repository.

A genealogy starts with a common ancestor of the clan and names with direct relationships, such as parents and children, that are connected by a line for linkage. Similarly, a ledger consists of blocks. Each block contains one or multiple transactions depending on the type of blockchain. (As you will see later, blocks on Bitcoin or Ethereum host multiple transactions, while R3's Corda uses a block with only one transaction). Transactions are like names, and a block is similar to the invisible box containing a couple's names. An equivalent of the root ancestor is called the

genesis block

, which is the first block of a blockchain. Similar to a line linking parents and children, a hash, which will later be explained in more detail, points from the current block to its ancestor block. 

Like the consensus mechanism for adding new names to a genealogy, the Bitcoin blockchain uses a mechanism called Proof-of-Work to decide whether a block can be added to the chain. Like a genealogy, after a block is added to a chain, it is difficult to change (hack) unless one possesses the majority (which is called a 51% attack) of the computing power of the network. 

Genealogy provides transparency in a clan's history. Similarly, a blockchain allows a user to query the whole ledger or just a part of the ledger and find out about coin movements.

Since every family kept a copy of the genealogy, it was unlikely to lose the genealogy even if many copies were lost due to a natural disaster, a war, or other reasons. As long as at least one family survived, the genealogy survived. Similarly, a decentralized ledger will survive as long as at least one node survives.

While genealogy is a good analogy to explain some key concepts of a blockchain, they are not the same. Inevitably, there are features that are not shared by them. For example, the blockchain uses cryptography and hashes extensively for data protection and deterring hackers. A genealogy does not have such a need. Therefore, next we move away from the genealogy analogy and explain key blockchain concepts chronically.

Bitcoin