Ethereum Smart Contract Development: Build blockchain-based decentralized applications using solidity
()
About this ebook
Ethereum is a public, blockchain-based distributed computing platform featuring smart contract functionality. This book is your one-stop guide to blockchain and Ethereum smart contract development.
We start by introducing you to the basics of blockchain. You'll learn about hash functions, Merkle trees, forking, mining, and much more. Then you'll learn about Ethereum and smart contracts, and we'll cover Ethereum virtual machine (EVM) in detail. Next, you'll get acquainted with DApps and DAOs and see how they work. We'll also delve into the mechanisms of advanced smart contracts, taking a practical approach.
You'll also learn how to develop your own cryptocurrency from scratch in order to understand the business behind ICO. Further on, you'll get to know the key concepts of the Solidity programming language, enabling you to build decentralized blockchain-based applications. We'll also look at enterprise use cases, where you'll build a decentralized microblogging site.
At the end of this book, we discuss blockchain-as-a-service, the dark web marketplace, and various advanced topics so you can get well versed with the blockchain principles and ecosystem.
Related to Ethereum Smart Contract Development
Related ebooks
Mastering Ethereum: Implement advanced blockchain applications using Ethereum-supported tools, services, and protocols Rating: 0 out of 5 stars0 ratingsLearn Ethereum: Build your own decentralized applications with Ethereum and smart contracts Rating: 0 out of 5 stars0 ratingsAdvanced Blockchain Development: Build highly secure, decentralized applications and conduct secure transactions Rating: 0 out of 5 stars0 ratingsSolidity Programming Essentials: A beginner's guide to build smart contracts for Ethereum and blockchain Rating: 0 out of 5 stars0 ratingsBlockchain for Decision Makers: A systematic guide to using blockchain for improving your business Rating: 0 out of 5 stars0 ratingsBlockchain for Enterprise: Build scalable blockchain applications with privacy, interoperability, and permissioned features Rating: 0 out of 5 stars0 ratingsBlockchain Quick Reference: A guide to exploring decentralized blockchain application development Rating: 0 out of 5 stars0 ratingsHands-On Blockchain with Hyperledger: Building decentralized applications with Hyperledger Fabric and Composer Rating: 0 out of 5 stars0 ratingsHands-On Blockchain for Python Developers: Gain blockchain programming skills to build decentralized applications using Python Rating: 0 out of 5 stars0 ratingsBuilding Blockchain Projects: Building decentralized Blockchain applications with Ethereum and Solidity Rating: 0 out of 5 stars0 ratingsBlockchain for Business 2019: A user-friendly introduction to blockchain technology and its business applications Rating: 0 out of 5 stars0 ratingsBlockchain Development with Hyperledger: Build decentralized applications with Hyperledger Fabric and Composer Rating: 0 out of 5 stars0 ratingsBlockchain By Example: A developer's guide to creating decentralized applications using Bitcoin, Ethereum, and Hyperledger Rating: 0 out of 5 stars0 ratingsRipple Quick Start Guide: Get started with XRP and develop applications on Ripple's blockchain Rating: 0 out of 5 stars0 ratingsBlockchain Quick Start Guide: A beginner's guide to developing enterprise-grade decentralized applications Rating: 0 out of 5 stars0 ratingsEthereum Projects for Beginners: Build blockchain-based cryptocurrencies, smart contracts, and DApps Rating: 0 out of 5 stars0 ratingsHyperledger Cookbook: Over 40 recipes implementing the latest Hyperledger blockchain frameworks and tools Rating: 0 out of 5 stars0 ratingsMastering Blockchain Programming with Solidity: Write production-ready smart contracts for Ethereum blockchain with Solidity Rating: 0 out of 5 stars0 ratingsTruffle Quick Start Guide: Learn the fundamentals of Ethereum development Rating: 0 out of 5 stars0 ratingsHands-On Cybersecurity with Blockchain: Implement DDoS protection, PKI-based identity, 2FA, and DNS security using Blockchain Rating: 0 out of 5 stars0 ratingsRust Quick Start Guide: The easiest way to learn Rust programming Rating: 0 out of 5 stars0 ratingsMastering Machine Learning for Penetration Testing: Develop an extensive skill set to break self-learning systems using Python Rating: 0 out of 5 stars0 ratingsHands-On Software Architecture with Golang: Design and architect highly scalable and robust applications using Go Rating: 0 out of 5 stars0 ratingsHands-On Microservices with C# 8 and .NET Core 3: Refactor your monolith architecture into microservices using Azure, 3rd Edition Rating: 0 out of 5 stars0 ratingsMachine Learning with the Elastic Stack: Expert techniques to integrate machine learning with distributed search and analytics Rating: 0 out of 5 stars0 ratingsEmbedded Programming with Modern C++ Cookbook: Practical recipes to help you build robust and secure embedded applications on Linux Rating: 0 out of 5 stars0 ratings
Databases For You
Oracle DBA Mentor: Succeeding as an Oracle Database Administrator Rating: 0 out of 5 stars0 ratingsBlockchain Basics: A Non-Technical Introduction in 25 Steps Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Beginning Microsoft Power BI: A Practical Guide to Self-Service Data Analytics Rating: 0 out of 5 stars0 ratingsAccess 2019 For Dummies Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5COMPUTER SCIENCE FOR ROOKIES Rating: 0 out of 5 stars0 ratingsPractical Data Analysis Rating: 4 out of 5 stars4/5CompTIA DataSys+ Study Guide: Exam DS0-001 Rating: 0 out of 5 stars0 ratingsBehind Every Good Decision: How Anyone Can Use Business Analytics to Turn Data into Profitable Insight Rating: 5 out of 5 stars5/5Python Projects for Everyone Rating: 0 out of 5 stars0 ratingsLearn SQL in 24 Hours Rating: 5 out of 5 stars5/5Access 2016 For Dummies Rating: 0 out of 5 stars0 ratingsGo in Action Rating: 5 out of 5 stars5/5The Analytic Detective: Decipher Your Company’s Data Clues and Become Irreplaceable Rating: 0 out of 5 stars0 ratingsAccess for Beginners: Access Essentials, #1 Rating: 0 out of 5 stars0 ratingsLearn SQL Server Administration in a Month of Lunches Rating: 3 out of 5 stars3/5Learning Oracle 12c: A PL/SQL Approach Rating: 0 out of 5 stars0 ratingsAccess 2010 All-in-One For Dummies Rating: 4 out of 5 stars4/5Learn Git in a Month of Lunches Rating: 0 out of 5 stars0 ratingsAzure SQL Revealed: A Guide to the Cloud for SQL Server Professionals Rating: 0 out of 5 stars0 ratingsA Concise Guide to Object Orientated Programming Rating: 0 out of 5 stars0 ratingsGetting Started with SQL Server 2014 Administration Rating: 0 out of 5 stars0 ratingsPython and SQLite Development Rating: 0 out of 5 stars0 ratingsPractical SQL Rating: 4 out of 5 stars4/5SQL in 30 Pages Rating: 4 out of 5 stars4/5Learning PostgreSQL Rating: 1 out of 5 stars1/5
Reviews for Ethereum Smart Contract Development
0 ratings0 reviews
Book preview
Ethereum Smart Contract Development - Mayukh Mukhopadhyay
Ethereum Smart Contract Development
Build blockchain-based decentralized applications
using solidity
Mayukh Mukhopadhyay
BIRMINGHAM - MUMBAI
Ethereum Smart Contract Development
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, 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: Chandan Kumar
Content Development Editor: Amrita Noronha
Technical Editor: Sayali Thanekar
Copy Editor: Safis Editing, Vikrant Phadke
Project Coordinator: Shweta H Birwatkar
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Graphics: Jisha Chirayil
Production Coordinator: Aparna Bhagat
First published: February 2018
Production reference: 1210218
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78847-304-0
www.packtpub.com
Dedicated to my wife, Mrittika, for loaning me her ACER laptop to complete this book.
And my daughter, Abriti, for keeping her mom super busy while
I was crashing it by mining ethers.
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
PacktPub.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.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.
Contributors
About the author
Mayukh Mukhopadhyay started his career as a BI developer. After the 2008-09 financial crisis, he was at Tata Consultancy Services for one of their Fortune 500 clients in the telecom sector. Holding a master's in software engineering from Jadavpur University, he is presently working as a data insight developer, where he focuses on applying data science and machine learning to raw telecom equipment logs to generate business insights. He has a varied list of academic interests, ranging from audio signal processing, structural bioinformatics, and bio-inspired algorithms to consciousness engineering. Apart from being an Oracle Certified Specialist, he is a Certified Bitcoin Professional, recognized by C4 (Crypto Currency Certification Consortium). He tries to apply blockchain as a technology to different business domains.
To my guide @JU Dr Parama Bhaumik —your lectures on distributed systems were my main inspiration while writing this book.
To my professional network connections Ivan Liljeqvist, Dug Campbell, Mahesh Murthy, Kaushik Sathupadi, Ravinder Deol, Narayan Prusty, and Thomas Wiesner—thanks for your blogs and vlogs. This book is as much your creation as it is mine.
About the reviewer
Daniel Kraft studied applied mathematics and theoretical physics in Graz, Austria, where he obtained his PhD from the University of Graz in 2015. After that, he started as a software engineer in Zurich, Switzerland. He has been very interested in Bitcoin and cryptocurrencies since 2011 and involved in Bitcoin development since 2013. Since 2014, he has been the main developer for Namecoin and Huntercoin, and has successfully reimplemented both on top of the modern Bitcoin Core code base. Wherever possible, Daniel also contributed improvements to the upstream Bitcoin Core. He has published multiple research articles in peer-reviewed journals, two of them directly related to cryptocurrency.
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
Ethereum Smart Contract Development
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
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
Download the color images
Conventions used
Get in touch
Reviews
Blockchain Basics
Understanding distributed systems
The Byzantine Generals' Problem
Losing strategy
Winning strategy
The CAP theorem
Consensus in distributed systems
Understanding the hash function and the Merkle tree
Understanding a blockchain–a developer and trader's perspective
Inside a block
Blockchain mining and forking
Blockchains – evolution, generations, and hype
Summary
Grokking Ethereum
Understanding Ethereum
The notion of decentralization
The Ethereum ecosystem
Mist
Decentralized applications
Middleware
Swarm
Whisper
EVM
Hardware clients and internet
Turing completeness and the magic sauce
Ethereum block, mining, and forking
The Ethereum wallet and client interface
Summary
Hello World of Smart Contracts
A smart contract in seven lines of code
Remix in a nutshell
Increment and decrement operations using Solidity
Coding a loop
Raising an issue on GitHub
Smart contract on a private blockchain
Writing the genesis block
Building a private blockchain
Connecting MIST browser using geth
Mining ethers in a private blockchain
Deploying smart contracts on our private chain
Summary
A Noob's Guide to DApps and DAO
Understanding DApps
Steps to develop a DApp
Architecture of a DApp
What is ethercast?
btcrelay.org
oraclize.it
the-pitts-circus.com
Understanding the design of DAO
The rise and fall of DAO
Summary
Deep-Diving into Smart Contracts
What makes a contract smart
?
Definition and design
Role of code in a smart contract
Basic anatomy of a smart contract design
Smart contract optimization
Smart contract auditing and compliance
Designing a voting DApp
Summary
Solidity in Depth
Need for solidity
Nuances, syntax, and features of solidity
Pragma, import, and comments
Class properties of a contract
Functions
Events
Inheritance
Libraries
Expression and control structures
Units and variables
Optimizer and debugging options
Parity hack demystified
Summary
Primer on Web3.js
Web3.js in the Ethereum ecosystem
Running a smart contract using Web3.js
API structure of Web3.js
Designing an ownership contract
Summary
Developing a Cryptocurrency from Scratch
Token versus coin
ERC20 token development using Truffle
Arbitrage trading for cryptocurrencies
The ICO story
Fiat2Crypto and Crypto2Crypto exchange
Parity hack returns
Summary
Enterprise Use Cases
Banking and payments
Insurance
Supply chain management
Forecasting and prediction market
Charity
Public benefits
Energy management
Art and music
Retail
Real estate
Cyber security
Crowdfunding
Networking and the Internet of Things
Voting
Government
Private transport and ride sharing
Cloud storage
Healthcare
Smart contract use cases
Insurance
Trade finance
Derivatives
Securities
Accounts
Digital identity
Record-keeping
Loans and mortgages
Legal
Supply chain
Clinical trials
Terminal disease research
Decentralized microblogging
Administrative and security constraints
TwtAccount.sol
TwtRegistry.sol
Service setup on the private blockchain
Reading tweets
Summary
BaaS and the Dark Web Market
Playful privacy
Types of blockchain
Private blockchains
Public blockchains
Consortium blockchains
Blockchain-as-a-service
Enterprise platforms for BaaS
IBM Hyperledger
Microsoft Azure EBaaS
Amazon Eris
Dark web marketplace
Project smartCV
Summary
Advanced Topics and the Road Ahead
Common design patterns
Restricting access
Token systems
Factory pattern
Registries
Voting systems
DACs and DAS
Ethereum improvement proposal
Rational behind EIPs
Types of EIP
EIP life cycle
EIP template
Consortium blockchains
Case study on R3 Corda
Tangle beyond blockchain
Shortcomings of a blockchain
Tangle demystified
Iota GitHub analysis
Purchase and storage of Iota
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Preface
If you are reading this line, I want to congratulate you because you have already overcome the most difficult hurdle in the pursuit of the understanding blockchain, and specifically, Ethereum smart contracts. This hurdle is the overwhelming hype surrounding this promising yet premature technology and trying to know what is really going on under the hood.
I am a software developer, and through my book, which you are viewing in your electronic device or physically holding in your hand, we will together embark on a fascinating journey through this enigmatic and revolutionary technology.
The chapters in this book have been arranged in an incremental fashion. We start with a gentle introduction to blockchain using the familiar bitcoin, and quickly dive into the world of Ethereum and the major players in its ecosystem.
Then we proceed to do some hands-on coding of a typical Hello World
smart contract. We then take on the subject of decentralized autonomous organizations, decentralized applications, and smart contract optimization. We also analyze two famous multi-million-dollar hacks that recently occurred in the Ethereum community, along with the preventive measures employed to avoid them in future.
We then move on to the intricacies of the solidity programming language and web3.js library.
The final chapters mainly deal with the development of standardized tokens, the concept of initial coin offering, potential enterprise use cases of smart contracts, designing a decentralized micro-blogging platform, and surfing the dark web marketplace.
We conclude the book by providing primers on advanced topics with promising future prospects such as graph-based DLTs and quantum secured blockchains.
At the onset, I want to have a clear understanding between us. Even though I am the author of this book and it is my sole responsibility to present the facts as accurately as possible in this book, in no possible way do I consider myself as the sole authority on this subject.
As my reader, I want you to realize that I am just another overenthusiastic fellow learner who will try to assist you with your pursuit of knowledge by introducing the optimal amount of information required to kick-start your journey. And I will make you aware of the hurdles and pitfalls I faced along the way so that you can learn from my mistakes.
Enough said. Let's start our journey to blockchain and get our hands dirty with Ethereum Smart Contract Development.
Happy reading!
Who this book is for
This book is dedicated to novice programmers, solution architects, and blockchain enthusiasts who want to build powerful, robust, and optimized smart contracts using solidity from scratch and in combination with other open source JavaScript libraries. If you want to build your own extensive, decentralized applications that can smartly execute on a blockchain, then this book is what you need! An open and inquisitive mind is a necessary and sufficient prerequisite. Some preliminary knowledge of data structures, object-oriented programming, networking concepts, and cryptography is a plus and will help the reader to understand the concepts presented in this book.
What this book covers
Chapter 1, Blockchain Basics, will serve as a warm-up session about blockchain before we deep dive into Ethereum and smart contract development. To really appreciate blockchain, we must understand the two founding pillars on which blockchain as a technology is firmly grounded: distributed systems and cryptography. Once we have covered these two core concepts, we try to understand a blockchain from two different perspectives: as a software developer and as a trader of financial instruments. Then we probe into the internal logical architecture of a block in the blockchain, focusing the bitcoin block structure, and get a gentle introduction to the mining and forking process. We conclude the chapter by discussing how blockchain has evolved in recent years and clearly marking out its current position in the technological hype cycle.
Chapter 2, Grokking Ethereum, will help us to understand the meaning of decentralization and whether Ethereum is truly decentralized. We will also cover its core technological stack and get familiarized with various jargon, such as Mist, EVM, Swarm, Whisper, Ether, and Gas. We will briefly discuss the notion of a Turing-complete language. We'll then revisit forking, mining, and block architecture from the perspective of Ethereum. We'll end this chapter by getting a notion of Ethereum wallets and client interfaces, which will serve as a firm base for smart contract development.
Chapter 3, The Hello World of Ethereum Smart Contract, provides a hands-on guide to developing our first smart contract. As an unspoken tradition of a software developer, we start with a Hello World
program. Then we try some basic arithmetic increment and decrement operations using a contract. We then learn how to code a loop inside a smart contract and how to raise an issue in GitHub. We end this chapter by creating our own private blockchain right from the genesis block, attach it with Geth, and use the Mist browser to deploy one of the smart contracts we studied in this chapter, after mining some ethers.
Chapter 4, A Noob's Guide to DApps and DAOs, develops our understanding towards decentralized applications from a developer's perspective. We introduce the high-level steps to develop a decentralized application. Then we explore a unique marketplace called ethercast, which serves as an aggregator of several DApps. We then move on to design a decentralized autonomous organization. We conclude this chapter with a retrospection of the infamous DAO hack, which led to the ETH/ETC split, from a purely technical perspective.
Chapter 5, Deep-Diving into Smart Contracts, digs deeper into smart contract designs. We start by understanding the textbook definition of a smart contract. Then we move on to understand different smart contract models and the role of code in a smart contract. We go through the basic anatomy of a smart contract and see how a smart contract works. Then we shift our focus to advanced topics such as smart contract optimization, auditing, and ERC20 compliance. We conclude the chapter with a hands-on drill of building a voting DApp.
Chapter 6, Solidity in Depth, is all about the Turing complete solidity language on the Ethereum blockchain. We will start by probing into the design decision of why we really need a new language like solidity. The next sections will cover the nuances of the solidity language and the basic syntax used in it. Specifically, we'll cover contract-oriented features, functions and events, inheritance, libraries, expressions, control structures, units, and variables. Then we'll look at the optimizer and debugging options. We will conclude this chapter by analyzing the code flaw that led to the recent parity wallet hack in the Ethereum blockchain, which stole around $30 million worth of ethers.
Chapter 7, Primer on Web3.js, introduces a special application programming interface library written in JavaScript. This interface connects our web browser with the Ethereum blockchain node. We will begin this chapter by understanding the difference between Geth, Web3.js, and Mist. Then we will learn how to import this API library and get connected with Geth. We will then explore the API structure inside the web3.js library. We'll conclude the chapter by studying the design of an ownership contract.
Chapter 8, Developing Cryptocurrency from Scratch, provides a hands-on tutorial to develop an ERC20 standardized token using the Truffle framework. We then dive in to the concepts of initial coin offering (ICO) and how to identify genuine ICOs among fake and Ponzi schemes. The chapter concludes by discussing various token conversion process and pair-trading concepts.
Chapter 9, Enterprise Use Cases, provides some exciting and promising use cases of Ethereum smart contracts. We also discuss the design of a decentralized micro-blogging platform using solidity.
Chapter 10, BaaS and the Dark Web Market, introduce us to the blockchain framework of Microsoft and IBM. We conclude this chapter by discussing the difference between the Conventional Web and the Dark Web (.onion website and TOR) and how to safely browse the Dark Web to find use cases of cryptocurrencies.
Chapter 11, Advanced Topics and the Road Ahead, deals with exciting topics such as graph-based DLTS with a focus on Tangle, quantum secured blockchain, Ethereum improvement protocols, consortium blockchains, distributed autonomous societies, and common design patterns for solidity.
To get the most out of this book
Inform the reader of the things that they need to know before they start, and spell out what knowledge you are assuming
Some preliminary knowledge of data structures, object-oriented programming, networking concepts, and cryptography