Implement decentralized blockchain applications to build scalable Dapps Key Features Understand the blockchain ecosystem and its terminologies Implement smart contracts, wallets, and consensus protocols Design and develop decentralized applications using Bitcoin, Ethereum, and Hyperledger Book Description The Blockchain is a revolution promising a new world without middlemen. Technically, it is an immutable and tamper-proof distributed ledger of all transactions across a peer-to-peer network. With this book, you will get to grips with the blockchain ecosystem to build real-world projects. This book will walk you through the process of building multiple blockchain projects with different complexity levels and hurdles. Each project will teach you just enough about the field's leading technologies, Bitcoin, Ethereum, Quorum, and Hyperledger in order to be productive from the outset. As you make your way through the chapters, you will cover the major challenges that are associated with blockchain ecosystems such as scalability, integration, and distributed file management. In the concluding chapters, you'll learn to build blockchain projects for business, run your ICO, and even create your own cryptocurrency. Blockchain by Example also covers a range of projects such as Bitcoin payment systems, supply chains on Hyperledger, and developing a Tontine Bank Every is using Ethereum. By the end of this book, you will not only be able to tackle common issues in the blockchain ecosystem, but also design and build reliable and scalable distributed systems. What you will learn Grasp decentralized technology fundamentals to master blockchain principles Build blockchain projects on Bitcoin, Ethereum, and Hyperledger Create your currency and a payment application using Bitcoin Implement decentralized apps and supply chain systems using Hyperledger Write smart contracts, run your ICO, and build a Tontine decentralized app using Ethereum Implement distributed file management with blockchain Integrate blockchain into existing systems in your organization Who this book is for If you are keen on learning how to build your own blockchain decentralized applications from scratch, then this book is for you. It explains all the basic concepts required to develop intermediate projects and will teach you to implement the building blocks of a blockchain ecosystem. Table of Contents Hello world in blockchain Building a Bitcoin Payment System Building Your Own Cryptocurrency Peer-to-Peer Auctions in Ethereum Tontine Game with Truffle and Drizzle Blockchain-Based Futures System Blockchains in Business Creating an ICO Distributed Storage IPFS and Swarm Supply Chain on Hyperledger Letter of Credit Hyperledger Cover Title Page Copyright and Credits About Packt Foreword Contributors Table of Contents Preface Chapter 1: Say Hello to Blockchain The emergence of blockchain and cryptocurrency From virtual currencies to cryptocurrency The invention of bitcoin What is blockchain? Blocks Transactions Smart contracts Interact with the blockchain Getting started Running a bitcoin client for the first time Synchronizing the blockchain Running Bitcoin Core Running Electrum Method 1 – Building a raw transaction using Bitcoin Core Funding our address Unspent transaction output Creating the transaction Transaction structure Signing the transaction Sending the transaction Retrieving your message online from the blockchain Using the local blockchain Method 2 – build a raw bitcoin transaction in JavaScript Preparation Let's code Types of blockchains Classification of blockchains Summary Chapter 2: Building a Bitcoin Payment System What is Bitcoin? Why choose Bitcoin as a platform? Getting started with Bitcoin Setting up a Regtest environment First commands Transactions in bitcoin Mining Bitcoin scripting Building a P2PKH script using JavaScript Building a custom script Building a payment gateway Project description Bitcoin payment protocol overview Prerequisites Project setup Certificate management Merchant side Building a payment request URI Routing Checkout view Proceeding with payment Requesting payment details Receiving and acknowledging payment Invoicing Client side Previewing your application Payment protocol using BitcoinJ Prerequisites BitcoinJ installation BitcoinJ client Bitcoin wallet configuration Requesting payment Sending a payment Testing the code Bitcoin smart contracts What is Rootstock? Rootstock setup Interactions with RSK Account settings Writing your first bitcoin smart contract Deploying the contract Interacting with the contract Summary Chapter 3: Building Your Own Cryptocurrency Compiling Bitcoin from source Preparing your build system Installing dependencies Bitcoin-qt - Qt5 GUI for Bitcoin Cloning the Bitcoin source code Building Bitcoin Core Checking your build worked New cryptocurrency – Readercoin Cloning Bitcoin Readercoin rebranding Changing the ports Changing pchMessageStart Genesis block New pszTimestamp New nonce, epoch time, and nbits New genesis hash Editing the Merkle root Removing the seed nodes Checkpoints ChainTxData Rewarding Halving Total supply POW parameters – target New block time Difficulty adjustment time interval Difficulty adjustment rate Time maturity Block size BIPs: Bitcoin Improvement Proposals Compiling and testing Design and graphics (Qt wallet) Redesign of the Bitcoin-Qt wallet Graphical interface addition Building a Readercoin network Readercoin mining Sending transactions Building a transaction and block explorer Iquidus setup requirements Creating Iquidus's database Installing Iquidus Iquidus configuration Syncing databases with the blockchain Wallet preparation Starting the explorer Building an exchange market Summary Chapter 4: Peer-to-Peer Auctions in Ethereum Introduction to Ethereum Ethereum virtual machine and smart contracts Ether and gas Your first smart contract What's a DApp? DApp architecture Building an auction DApp Auction description Auction contract in Solidity Contract code analysis State variables Variable state types Visibility and access modifiers Enumerations Arrays Mappings Structures Functions Modifiers Condition and error verification Events Inheritance Constructors Time in Solidity Special variables and functions The fallback function Function overloading The bidding function Canceling an auction Withdrawing bids Contract destruction Remix IDE Bidding form in web3.js Introduction to the web3.js API Step 1 – talking to the blockchain Step 2 – interaction with the smart contract The ABI Call versus send transactions Invoking contract methods via a call Invoking contract methods via a transaction Callbacks Reading state variables Watching events Indexing events and filtering Numbers in Ethereum and floating point Transaction status receipt Deployment environment – multiple ways to enjoy! Option 1 – Ganache Option 2 – Testnet Connecting MetaMask to Testnet Option 3 – private network Geth installation Creating new accounts Genesis file Node initialization Connecting Ethereum nodes RPC tests Mining process Contract deployment Compiling and deploying contracts using solc Proof of authority (POA) and difficulty adjustment Option 1 – editing the Ethereum client code Option 2 – POW Running the auction DApp Contract and transaction cost How cost is calculated Deployment cost Function execution cost Contract destruction cost Potential optimization Solidity tips and tricks Summary Chapter 5: Tontine Game with Truffle and Drizzle Background Prerequisites Truffle quick start Installing Truffle Saying hello to Truffle Running Truffle for the first time Preparing the migration Configuring Truffle Compiling the contract Migrating the contract Setting up Ganache The Tontine contract General structure UML model Preparing the contracts Cplayer as a CRUD contract Smart contract data location The CRUD data repository CRUD – Create CRUD – Read Mapping iterations CRUD – Update Function overloading CRUD – Delete Tontine interfaces – Itontine Interface implementation – Ctontine contract Smart contract interaction Contract instantiation Contract creation Reading the storage of a remote contract Editing the storage of a remote contract Joining the game Calling remote functions Option one – using the ABI Option two – using low-level calls Using call to send ether The ping() method The eliminate() method The share_pension() method Standard integer division The claimReward method The this keyword Truffle unit tests Preparing the testing environment Migrating the contracts Running Ganache Preparing the tests Testing addPlayer() Testing findPlayer() Testing removePlayer() Testing Ctontine Testing a payable function Testing events Testing claimReward() Time manipulation Running the tests Testing with Solidity Debugging with Truffle and Remix Debugging with Truffle Spotting the error Breakpoints and watching values Debugging with Remix Attaching the debugger to the code Watching values Setting breakpoints Frontend with Drizzle Prerequisites What is the Drizzle box? Getting started with the Drizzle box Running the demo Starting the web UI Hacking the Drizzle box The game’s homepage Trying the DApp Connecting Ganache to MetaMask Running the Tontine DApp Showtime – ready to play? Getting help Summary Chapter 6: Blockchain-Based Futures System Project presentation Futures smart contract Blockchain oracles Web3j Prerequisites Setting up the Web3J Maven project Installing web3j Wallet creation Java client The wrapper generator Initializing web3j Setting up Ethereum accounts Deploying the contract Interacting with smart contracts Calling a contract function Calling view methods Web3j events Enhancement Summary Chapter 7: Blockchains in Business Public versus private and permissioned versus permissionless blockchains Privacy and anonymity in Ethereum Why are privacy and anonymity important? The Ethereum Enterprise Alliance Ethereum's licensing Blockchain-as-a-Service Quorum Privacy Higher performance and throughput Permission and governance The Quorum client Quorum Node Constellation Our project Prerequisites Bringing up the network Interacting with the network Testing the network Deploying the public contract Deploying the private contract Permissioning the network Summary Chapter 8: Creating an ICO What is an ICO? Project setup Token contracts ERC-20 token standard Name and symbol (optional) totalSupply (required) decimals (optional) Transfer event (required) balanceOf (required) transfer() (required) The constructor Delegated transfer allowance (required) approve() (required) Approval event (required) transferFrom() (required) The complete token contract ERC-223 token standard ERC-721 non-fungible token standard Token sale contracts Hard cap Soft cap Uncapped Dutch auction Reverse dutch auction Considerations Implementing our token sale contract Constructor Token supply Buying tokens Ending the sale The complete token sale contract Contract security Known attack vectors Integer overflow/underflow Reentrancy OpenZeppelin Testing the code The public test networks Ropsten Rinkeby Kovan Migrating the code Testing our token contract Testing our token sale contract Deploying to a test network Running Geth on Rinkeby Configuring Truffle to work with Geth The Truffle console Provisioning the token sale contract Verifying our contract code on Etherscan Creating a frontend website Setting up the frontend development Frontend directory structure index.html app.js Running the frontend code Interacting with the frontend Summary Suggestions for further work Chapter 9: Distributed Storage IPFS and Swarm Background Swarm and IPFS Installing IPFS Installing Swarm Hosting our frontend Serving your frontend using IFPS Using IPNS Serving your frontend using Swarm ENS IPFS file uploader project Project setup The web page index.html main.js Summary Chapter 10: Supply Chain on Hyperledger Food industry supply chain Quick Hyperledger overview Hyperledger Fabric End-to-end transaction flow Hyperledger Composer Setting up the development environment Prerequisites Installing Hyperledger Fabric Fabric's Chaincode Writing Chaincode The Init function The Invoke function Hyperledger data storage The Query function Error handling Building a business network Privacy in Hyperledger Define services in a compose file Resources and profiles Fabric channel and Genesis block Generate peers and orderer certificates Start the Docker containers Join the channel and install Chaincode Chaincode compilation and deployment Interacting with Chaincode Running the project Interacting over REST API/JSON-RPC Setting up the development environment Register users Querying the Chaincode from UI Hyperledger Composer Get Hyperledger Composer and Playground Composer Playground Summary Chapter 11: Letter of Credit (LC) Hyperledger LC concepts and design Development environment Setting up the IDE Getting Hyperledger Fabric running Creating a composer Fabric application Creating our first business network using Hyperledger Composer Models definition JavaScript transaction logic Access control definition LC business network Initial LC model Participant onboarding Initial agreement LC request LC approval LC advising Goods shipping Document delivery Debit payment Payment transfer Pay the seller LC closure Deploying the LC Deploying business network Generating a REST server Testing LC project Participant onboarding Initial agreement LC request LC approval LC advising Goods shipping Present document Deliver document Debit payment Payment transfer Pay the seller LC closure Hyperledger Fabric on IBM Cloud Summary Other Books You May Enjoy Index Implement decentralized blockchain applications to build scalable Dapps Key Features Understand the blockchain ecosystem and its terminologies Implement smart contracts, wallets, and consensus protocols Design and develop decentralized applications using Bitcoin, Ethereum, and Hyperledger Book Description The Blockchain is a revolution promising a new world without middlemen. Technically, it is an immutable and tamper-proof distributed ledger of all transactions across a peer-to-peer network. With this book, you will get to grips with the blockchain ecosystem to build real-world projects. This book will walk you through the process of building multiple blockchain projects with different complexity levels and hurdles. Each project will teach you just enough about the field's leading technologies, Bitcoin, Ethereum, Quorum, and Hyperledger in order to be productive from the outset. As you make your way through the chapters, you will cover the major challenges that are associated with blockchain ecosystems such as scalability, integration, and distributed file management. In the concluding chapters, you'll learn to build blockchain projects for business, run your ICO, and even create your own cryptocurrency. Blockchain by Example also covers a range of projects such as Bitcoin payment systems, supply chains on Hyperledger, and developing a Tontine Bank Every is using Ethereum. By the end of this book, you will not only be able to tackle common issues in the blockchain ecosystem, but also design and build reliable and scalable distributed systems. What you will learn Grasp decentralized technology fundamentals to master blockchain principles Build blockchain projects on Bitcoin, Ethereum, and Hyperledger Create your currency and a payment application using Bitcoin Implement decentralized apps and supply chain systems using Hyperledger Write smart contracts, run your ICO, and build a Tontine decentralized app using Ethereum Implement distributed file management with blockchain Integrate blockchain into existing systems in your organization Who this book is for If you are keen on learning how to build your own blockchain decentralized applications from scratch, then this book is for you. It explains all the basic concepts required to develop intermediate projects and will teach you to implement the building blocks of a blockchain ecosystem. Downloading the example code for this book You can download the example code files for all Packt books you hav .. Implement decentralized blockchain applications to build scalable Dapps * Understand the blockchain ecosystem and its terminologies * Implement smart contracts, wallets, and consensus protocols * Design and develop decentralized applications using Bitcoin, Ethereum, and Hyperledger The Blockchain is a revolution promising a new world without middlemen. Technically, it is an immutable and tamper-proof distributed ledger of all transactions across a peer-to-peer network. With this book, you will get to grips with the blockchain ecosystem to build real-world projects. By the end of this book, you will not only be able to tackle common issues in the blockchain ecosystem, but also design and build reliable and scalable distributed systems. * Grasp decentralized technology fundamentals to master blockchain principles * Build blockchain projects on Bitcoin, Ethereum, and Hyperledger * Create your currency and a payment application using Bitcoin * Implement decentralized apps and supply chain systems using Hyperledger * Write smart contracts, run your ICO, and build a Tontine decentralized app using Ethereum * Implement distributed file management with blockchain * Integrate blockchain into existing systems in your organization If you are keen on learning how to build your own blockchain decentralized applications from scratch, then this book is for you. It explains all the basic concepts required to develop intermediate projects and will teach you to implement the building blocks of a blockchain ecosystem. 1. Hello world in blockchain 2. Building a Bitcoin Payment System 3. Building Your Own Cryptocurrency 4. Peer-to-Peer Auctions in Ethereum 5. Tontine Game with Truffle and Drizzle 6. Blockchain-Based Futures System 7. Blockchains in Business 8. Creating an ICO 9. Distributed Storage IPFS and Swarm 10. Supply Chain on Hyperledger 11. Letter of Credit Hyperledger