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 Blockchain By Example 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 authors, 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 Shetty Acquisition Editor: Porous Godhaa Content Development Editor: Karan Thakkar Technical Editor: Dinesh Pawar Copy Editor: Safis Editing Project Coordinator: Namrata Swetta Proofreader: Safis Editing Indexer: Priyanka Dhadke Graphics: Jisha Chirayil Production Coordinator: Shantanu Zagade First published: November 2018 Production reference: 1301118 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78847-568-6 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. Foreword From the time Badr Bellaj first told me about his intention to write a book about blockchain, I was highly supportive of his endeavor. I even managed to suggest topics that I, as a veteran developer, still needed to understand. A year later, after reading this book, my expectations have been surpassed and I could not be happier. Therefore, it's my pleasure to provide this foreword and to recommend Bellaj's book, Blockchain by Example. It is generally agreed that blockchain is a disruptive technology that has shaken the IT scene. Consequently, it has increasingly drawn the interest of a lot of developers. However, according to my experience, it's hard for newcomers to find a helpful guide that explains blockchain in the easiest possible terms, and teaches with concrete examples how to use major blockchain solutions to build projects. This book is intended to change this situation and acts as an introduction to blockchain technology from a developer viewpoint. It's an undertaking of great potential value, and Bellaj and his coauthors have done it justice. In fact, this book will help you, step by step, to build realistic projects from scratch using different concepts and technologies, namely Bitcoin, Ethereum, Quorum, and Hyperledger. You'll find, among other topics, how a developer can create a Bitcoin-like coin, run an ICO, and implement privacy-preserving solution in business. This book isn't just for absolute beginners. It's also a good book for introducing experienced programmers to blockchain technologies or even bringing up to speed developers already familiar with these technologies. It helps if you know a bit about blockchain when you step in, but if you don't, hang on and you should pick up the basic ideas as you go along. Bellaj is an educator, and a darn good one. He wants us to acquire practical skills instead understanding only the superficial concepts! He knows that if you and I are ready to learn, we have to practice: we have to do the work. In his chapters, he will continually challenge you to propose new features for the presented project. We are well advised to try to implement what he suggests and to create pull requests. I have enjoyed the book and found it valuable. I think you will, too. Enjoy! Sam Hauer Cofounder of NSApps Contributors About the authors Bellaj Badr is an experienced security and software engineer who loves blockchain with a passion. Currently, he is the CTO at Mchain, a blockchain start-up that develops blockchain solutions for companies. Alongside his role as CTO, he acts as technical consultant, offering strategic and technical consulting to many companies worldwide. Aside from this, he is involved in many blockchain projects involving the establishment of new blockchain business-oriented protocols. Badr is a frequent speaker at developer conferences and is father to two angels. I would like to thank my family for their support and my awesome children, Arwa and Youssef, for letting me finish this book. Richard Horrocks is a freelance Ethereum and full-stack developer based in the UK, and holds a BA and MSc in natural sciences from the University of Cambridge. He worked for many years as a technical lead for Cisco Systems, where he worked on the operating systems of carrier-grade routing hardware, before leaving the world of IT to work as an English teacher. The advent of cryptocurrency piqued his interest sufficiently to lead him back to IT, and, since 2015, he has been working with Ethereum and other cryptocurrencies. His specialist interests are cryptoeconomics and incentive layers, with a particular focus on mechanism design and token engineering. When not in front of a computer, he enjoys yoga and falling off motorbikes. Xun (Brian) Wu is the founder and CEO of SmartChart. He has 16+ years of extensive, hands-on, design and development experience with blockchain, big data, cloud, UI, and system infrastructure. He has coauthored a number of books, including Seven NoSQL Databases in a Week, Hyperledger Cookbook, and Blockchain Quick Start Guide. He has been a technical reviewer on more than 50 technical books for Packt. He serves as a board adviser for several blockchain start-ups and owns several patents on blockchain. Brian also holds an NJIT computer science masters degree. He lives in New Jersey with his two beautiful daughters, Bridget and Charlotte. I would like to thank my parents, wife, and children for their patience and support throughout this endeavor. About the reviewers Karthikeyan Sukumaran has been involved in blockchain research and development for the past three years and has over a decade of industry experience in connection with mobile and web platforms. He has been a CEO for his own blockchain start-up, where he architected multiple blockchain projects for various consulting, automobile, supply chain, logistics, and financial companies. He is also a renowned speaker within the Indian blockchain community. Currently, Karthikeyan is an associate director (DLT Labs—Blockchain R&D) for The Depository Trust and Clearing Corporation (DTCC), India. Aafaf Ouaddah is a veteran security engineer, currently pursuing a PhD involving blockchain. She has wide-ranging experience in distributed systems. Currently, she is a lead researcher investigating security and privacy in distributed systems, blockchain, IoT and fog computing. She has presented more than 10 research papers at various conferences and workshops and has published in reputed international journals with IEEE, Springer, and Elsevier. 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 Preface 1 Chapter 1: Say Hello to Blockchain 6 The emergence of blockchain and cryptocurrency 7 From virtual currencies to cryptocurrency 7 The invention of bitcoin 8 What is blockchain? 10 Blocks 11 Transactions 11 Smart contracts 11 Interact with the blockchain 12 Getting started 12 Running a bitcoin client for the first time 13 Synchronizing the blockchain 14 Running Bitcoin Core 15 Running Electrum 18 Method 1 – Building a raw transaction using Bitcoin Core 19 Funding our address 19 Unspent transaction output 20 Creating the transaction 21 Transaction structure 23 Signing the transaction 24 Sending the transaction 27 Retrieving your message online from the blockchain 27 Using the local blockchain 28 Method 2 – build a raw bitcoin transaction in JavaScript 30 Preparation 30 Let's code 31 Types of blockchains 34 Classification of blockchains 34 Summary 36 Chapter 2: Building a Bitcoin Payment System 37 What is Bitcoin? 38 Why choose Bitcoin as a platform? 38 Getting started with Bitcoin 39 Setting up a Regtest environment 39 First commands 40 Transactions in bitcoin 41 Mining 42 Bitcoin scripting 42 Building a P2PKH script using JavaScript 45 Building a custom script 46