Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Block Chain Eg

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Blockchain By Example

A developer's guide to creating decentralized applications


using Bitcoin, Ethereum, and Hyperledger

Bellaj Badr
Richard Horrocks
Xun (Brian) Wu

BIRMINGHAM - MUMBAI
Table of Contents
Preface 1
Chapter 1: Say Hello to Blockchain 7
The emergence of blockchain and cryptocurrency 8
From virtual currencies to cryptocurrency 8
The invention of bitcoin 9
What is blockchain? 11
Blocks 12
Transactions 12
Smart contracts 12
Interact with the blockchain 13
Getting started 13
Running a bitcoin client for the first time 14
Synchronizing the blockchain 15
Running Bitcoin Core 16
Running Electrum 19
Method 1 – Building a raw transaction using Bitcoin Core 20
Funding our address 20
Unspent transaction output 21
Creating the transaction 22
Transaction structure 24
Signing the transaction 25
Sending the transaction 28
Retrieving your message online from the blockchain 28
Using the local blockchain 29
Method 2 – build a raw bitcoin transaction in JavaScript 31
Preparation 31
Let's code 32
Types of blockchains 35
Classification of blockchains 35
Summary 37
Chapter 2: Building a Bitcoin Payment System 39
What is Bitcoin? 40
Why choose Bitcoin as a platform? 40
Getting started with Bitcoin 41
Setting up a Regtest environment 41
First commands 42
Transactions in bitcoin 43
Mining 44
Bitcoin scripting 44
Building a P2PKH script using JavaScript 47
Building a custom script 48
Table of Contents

Building a payment gateway 50


Project description 50
Bitcoin payment protocol overview 51
Prerequisites 53
Project setup 53
Certificate management 54
Merchant side 54
Building a payment request URI 56
Routing 57
Checkout view 57
Proceeding with payment 58
Requesting payment details 58
Receiving and acknowledging payment 59
Invoicing 60
Client side 61
Previewing your application 65
Payment protocol using BitcoinJ 69
Prerequisites 69
BitcoinJ installation 70
BitcoinJ client 70
Bitcoin wallet configuration 71
Requesting payment 72
Sending a payment 73
Testing the code 76
Bitcoin smart contracts 78
What is Rootstock? 79
Rootstock setup 79
Interactions with RSK 80
Account settings 81
Writing your first bitcoin smart contract 82
Deploying the contract 83
Interacting with the contract 84
Summary 85
Chapter 3: Building Your Own Cryptocurrency 87
Compiling Bitcoin from source 88
Preparing your build system 88
Installing dependencies 88
Bitcoin-qt - Qt5 GUI for Bitcoin 89
Cloning the Bitcoin source code 90
Building Bitcoin Core 90
Checking your build worked 91
New cryptocurrency – Readercoin 92
Cloning Bitcoin 93
Readercoin rebranding 94
Changing the ports 96
Changing pchMessageStart 97
Genesis block 98

[ ii ]
Table of Contents

New pszTimestamp 100


New nonce, epoch time, and nbits 101
New genesis hash 101
Editing the Merkle root 101
Removing the seed nodes 102
Checkpoints 103
ChainTxData 105
Rewarding 105
Halving 106
Total supply 107
POW parameters – target 108
New block time 109
Difficulty adjustment time interval 110
Difficulty adjustment rate 110
Time maturity 112
Block size 112
BIPs: Bitcoin Improvement Proposals 114
Compiling and testing 115
Design and graphics (Qt wallet) 117
Redesign of the Bitcoin-Qt wallet 118
Graphical interface addition 119
Building a Readercoin network 125
Readercoin mining 129
Sending transactions 132
Building a transaction and block explorer 133
Iquidus setup requirements 133
Creating Iquidus's database 134
Installing Iquidus 134
Iquidus configuration 134
Syncing databases with the blockchain 135
Wallet preparation 136
Starting the explorer 136
Building an exchange market 137
Summary 138
Chapter 4: Peer-to-Peer Auctions in Ethereum 139
Introduction to Ethereum 140
Ethereum virtual machine and smart contracts 141
Ether and gas 142
Your first smart contract 142
What's a DApp? 143
DApp architecture 143
Building an auction DApp 145
Auction description 145
Auction contract in Solidity 146
Contract code analysis 148
State variables 148
Variable state types 149

[ iii ]
Table of Contents

Visibility and access modifiers 149


Enumerations 150
Arrays 150
Mappings 150
Structures 151
Functions 152
Modifiers 153
Condition and error verification 153
Events 154
Inheritance 155
Constructors 156
Time in Solidity 156
Special variables and functions 157
The fallback function 158
Function overloading 158
The bidding function 158
Canceling an auction 159
Withdrawing bids 160
Contract destruction 161
Remix IDE 162
Bidding form in web3.js 168
Introduction to the web3.js API 170
Step 1 – talking to the blockchain 173
Step 2 – interaction with the smart contract 173
The ABI 173
Call versus send transactions 174
Invoking contract methods via a call 174
Invoking contract methods via a transaction 174
Callbacks 175
Reading state variables 176
Watching events 176
Indexing events and filtering 176
Numbers in Ethereum and floating point 178
Transaction status receipt 179
Deployment environment – multiple ways to enjoy! 179
Option 1 – Ganache 180
Option 2 – Testnet 181
Connecting MetaMask to Testnet 182
Option 3 – private network 185
Geth installation 185
Creating new accounts 185
Genesis file 186
Node initialization 188
Connecting Ethereum nodes 190
RPC tests 190
Mining process 191
Contract deployment 192
Compiling and deploying contracts using solc 192
Proof of authority (POA) and difficulty adjustment 193
Option 1 – editing the Ethereum client code 193

[ iv ]
Table of Contents

Option 2 – POW 194


Running the auction DApp 196
Contract and transaction cost 197
How cost is calculated 198
Deployment cost 198
Function execution cost 198
Contract destruction cost 199
Potential optimization 199
Solidity tips and tricks 201
Summary 202
Chapter 5: Tontine Game with Truffle and Drizzle 203
Background 204
Prerequisites 204
Truffle quick start 205
Installing Truffle 205
Saying hello to Truffle 206
Running Truffle for the first time 207
Preparing the migration 207
Configuring Truffle 208
Compiling the contract 208
Migrating the contract 209
Setting up Ganache 209
The Tontine contract 212
General structure 212
UML model 213
Preparing the contracts 214
Cplayer as a CRUD contract 214
Smart contract data location 214
The CRUD data repository 216
CRUD – Create 217
CRUD – Read 218
Mapping iterations 219
CRUD – Update 220
Function overloading 221
CRUD – Delete 221
Tontine interfaces – Itontine 222
Interface implementation – Ctontine contract 224
Smart contract interaction 225
Contract instantiation 225
Contract creation 225
Reading the storage of a remote contract 226
Editing the storage of a remote contract 227
Joining the game 228
Calling remote functions 229
Option one – using the ABI 230
Option two – using low-level calls 231
Using call to send ether 232

[v]
Table of Contents

The ping() method 232


The eliminate() method 233
The share_pension() method 233
Standard integer division 234
The claimReward method 235
The this keyword 235
Truffle unit tests 236
Preparing the testing environment 236
Migrating the contracts 237
Running Ganache 238
Preparing the tests 238
Testing addPlayer() 239
Testing findPlayer() 240
Testing removePlayer() 240
Testing Ctontine 241
Testing a payable function 242
Testing events 243
Testing claimReward() 244
Time manipulation 245
Running the tests 246
Testing with Solidity 246
Debugging with Truffle and Remix 249
Debugging with Truffle 249
Spotting the error 251
Breakpoints and watching values 253
Debugging with Remix 254
Attaching the debugger to the code 257
Watching values 258
Setting breakpoints 260
Frontend with Drizzle 261
Prerequisites 262
What is the Drizzle box? 262
Getting started with the Drizzle box 262
Running the demo 263
Starting the web UI 263
Hacking the Drizzle box 265
The game’s homepage 267
Trying the DApp 271
Connecting Ganache to MetaMask 271
Running the Tontine DApp 274
Showtime – ready to play? 276
Getting help 279
Summary 280
Chapter 6: Blockchain-Based Futures System 281
Project presentation 282
Futures smart contract 282

[ vi ]
Table of Contents

Blockchain oracles 284


Web3j 287
Prerequisites 288
Setting up the Web3J Maven project 288
Installing web3j 290
Wallet creation 290
Java client 292
The wrapper generator 292
Initializing web3j 294
Setting up Ethereum accounts 294
Deploying the contract 295
Interacting with smart contracts 295
Calling a contract function 296
Calling view methods 298
Web3j events 299
Enhancement 300
Summary 301
Chapter 7: Blockchains in Business 303
Public versus private and permissioned versus permissionless
blockchains 303
Privacy and anonymity in Ethereum 304
Why are privacy and anonymity important? 305
The Ethereum Enterprise Alliance 306
Ethereum's licensing 306
Blockchain-as-a-Service 307
Quorum 308
Privacy 308
Higher performance and throughput 308
Permission and governance 309
The Quorum client 309
Quorum Node 310
Constellation 310
Our project 310
Prerequisites 311
Bringing up the network 312
Interacting with the network 313
Testing the network 314
Deploying the public contract 315
Deploying the private contract 316
Permissioning the network 317
Summary 318
Chapter 8: Creating an ICO 319
What is an ICO? 319
Project setup 320

[ vii ]
Table of Contents

Token contracts 321


ERC-20 token standard 322
Name and symbol (optional) 322
totalSupply (required) 323
decimals (optional) 323
Transfer event (required) 323
balanceOf (required) 324
transfer() (required) 324
The constructor 325
Delegated transfer 326
allowance (required) 326
approve() (required) 326
Approval event (required) 327
transferFrom() (required) 327
The complete token contract 329
ERC-223 token standard 330
ERC-721 non-fungible token standard 331
Token sale contracts 332
Hard cap 332
Soft cap 333
Uncapped 333
Dutch auction 333
Reverse dutch auction 333
Considerations 334
Implementing our token sale contract 334
Constructor 335
Token supply 336
Buying tokens 336
Ending the sale 337
The complete token sale contract 337
Contract security 339
Known attack vectors 339
Integer overflow/underflow 339
Reentrancy 340
OpenZeppelin 341
Testing the code 343
The public test networks 344
Ropsten 344
Rinkeby 344
Kovan 345
Migrating the code 345
Testing our token contract 346
Testing our token sale contract 347
Deploying to a test network 349
Running Geth on Rinkeby 350
Configuring Truffle to work with Geth 351
The Truffle console 352

[ viii ]
Table of Contents

Provisioning the token sale contract 353


Verifying our contract code on Etherscan 355
Creating a frontend website 356
Setting up the frontend development 357
Frontend directory structure 358
index.html 359
app.js 363
Running the frontend code 369
Interacting with the frontend 370
Summary 370
Suggestions for further work 371
Chapter 9: Distributed Storage IPFS and Swarm 373
Background 373
Swarm and IPFS 375
Installing IPFS 376
Installing Swarm 379
Hosting our frontend 380
Serving your frontend using IFPS 380
Using IPNS 381
Serving your frontend using Swarm 383
ENS 383
IPFS file uploader project 386
Project setup 387
The web page 388
index.html 388
main.js 390
Summary 392
Chapter 10: Supply Chain on Hyperledger 393
Food industry supply chain 393
Quick Hyperledger overview 395
Hyperledger Fabric 395
End-to-end transaction flow 397
Hyperledger Composer 398
Setting up the development environment 398
Prerequisites 398
Installing Hyperledger Fabric 399
Fabric's Chaincode 399
Writing Chaincode 400
The Init function 401
The Invoke function 404
Hyperledger data storage 407
The Query function 408
Error handling 409
Building a business network 410

[ ix ]
Table of Contents

Privacy in Hyperledger 412


Define services in a compose file 413
Resources and profiles 416
Fabric channel and Genesis block 418
Generate peers and orderer certificates 419
Start the Docker containers 421
Join the channel and install Chaincode 424
Chaincode compilation and deployment 425
Interacting with Chaincode 427
Running the project 427
Interacting over REST API/JSON-RPC 430
Setting up the development environment 431
Register users 432
Querying the Chaincode from UI 435
Hyperledger Composer 437
Get Hyperledger Composer and Playground 438
Composer Playground 439
Summary 446
Chapter 11: Letter of Credit (LC) Hyperledger 447
LC concepts and design 447
Development environment 449
Setting up the IDE 449
Getting Hyperledger Fabric running 450
Creating a composer Fabric application 451
Creating our first business network using Hyperledger Composer 452
Models definition 454
JavaScript transaction logic 455
Access control definition 456
LC business network 458
Initial LC model 458
Participant onboarding 460
Initial agreement 462
LC request 463
LC approval 465
LC advising 466
Goods shipping 467
Document delivery 469
Debit payment 470
Payment transfer 471
Pay the seller 473
LC closure 474
Deploying the LC 475
Deploying business network 476
Generating a REST server 477
Testing LC project 478

[x]
Table of Contents

Participant onboarding 479


Initial agreement 481
LC request 481
LC approval 482
LC advising 482
Goods shipping 483
Present document 483
Deliver document 483
Debit payment 484
Payment transfer 484
Pay the seller 484
LC closure 485
Hyperledger Fabric on IBM Cloud 485
Summary 493
Other Books You May Enjoy 495
Index 499

[ xi ]

You might also like