36,59 €
Discover the advanced features of Solidity that will help you write high-quality code and develop secure smart contracts with the latest ERC standards
Key Features
Book Description
Solidity is among the most popular and contract-oriented programming languages used for writing decentralized applications (DApps) on Ethereum blockchain. If you're looking to perfect your skills in writing professional-grade smart contracts using Solidity, this book can help.
You will get started with a detailed introduction to blockchain, smart contracts, and Ethereum, while also gaining useful insights into the Solidity programming language. A dedicated section will then take you through the different Ethereum Request for Comments (ERC) standards, including ERC-20, ERC-223, and ERC-721, and demonstrate how you can choose among these standards while writing smart contracts. As you approach later chapters, you will cover the different smart contracts available for use in libraries such as OpenZeppelin. You'll also learn to use different open source tools to test, review and improve the quality of your code and make it production-ready. Toward the end of this book, you'll get to grips with techniques such as adding security to smart contracts, and gain insights into various security considerations.
By the end of this book, you will have the skills you need to write secure, production-ready smart contracts in Solidity from scratch for decentralized applications on Ethereum blockchain.
What you will learn
Who this book is for
This book is for developers and data scientists who want to learn Ethereum, blockchain, and Solidity to write smart contracts and develop production-ready code. Basic knowledge of Solidity is assumed.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 590
Veröffentlichungsjahr: 2019
Copyright © 2019 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: Richa TripathiAcquisition Editor:Shriram ShekharContent Development Editor:Manjusha MantriSenior Editor: Afshaan KhanTechnical Editor:Pradeep SahuCopy Editor: Safis EditingProject Coordinator:Prajakta NaikProofreader: Safis EditingIndexer:Rekha NairProduction Designer:Shraddha Falebhai
First published: August 2019
Production reference: 1010819
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83921-826-2
www.packtpub.com
Packt.com
Subscribe to our online digital library for full access to over 7,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.
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
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
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.
I have known Jitendra Chittoda for a good while. Together, we have audited a significant number of smart contracts for different blockchain platforms. Some of these contracts have been widely used, while others handle large amounts of funds.
Prior to working as a smart contract auditor, Jitendra was working as a developer, which gave him a broader perspective of the field, as he has observed it from a variety of standpoints. These multiple viewpoints of blockchain, and Ethereum in particular, have allowed him more general insights.
While many have heard about the power and potential of blockchain and smart contracts, I believe the blockchain journey is still in its infancy. As with many new technologies, a number of mistakes have been made. Some mistakes led to exploits, and some exploits were so large that they made news headlines. One of those attacks was the DAO reentrancy attack.
Given the novelty of the technology, people require guidance. Such guidance is required on different levels. Firstly, many people still do not sufficiently understand what blockchain is really about, what makes it special, and what differentiates it from regular databases. They don't understand the power of smart contracts—which are sometimes called programmable money—and their potential impact on future businesses.
Secondly, while other people understand the power of blockchain, they do not see a clear path to building on top of it. They are not aware of the many small mistakes that can be made along the way, which range from overly expensive smart contracts to a complete loss of control. Hence, these people require detailed and explicit technical guidance.
Given Jitendra's background, he can provide a good overview and many technical recommendations that will not only speed up learning, but can also avoid costly and potentially project-threatening errors. This book starts off with introductions to blockchain before diving into Solidity, its details, its common applications, its most useful helpers, and its security practices.
Hubert Ritzdorf
Chief Technical Officer, ChainSecurity AG
Jitendra Chittoda is a blockchain security engineer at ChainSecurity. His day job is to perform security audit on smart contracts and expose security vulnerabilities in Solidity and Scilla contracts. He has also developed a non-custodial, decentralized, P2P lending contracts for ETHLend. The Solidity contracts that he has developed or audited handle over $100 million worth of cryptoassets. He also served as a tech and security advisor in various ICO projects.
Before finding his passion for blockchain, he coded in Java for over 11 years. He is the founder and leader of Delhi-NCR-JUG, a non-profit meetup group for Java. He holds a master's degree in computer applications and is regularly invited as a speaker at various conferences and meetups.
Natalie Chin is a blockchain developer, college professor, and technical blogger. She is currently teaching at George Brown College in Toronto, helping to lead the first blockchain college program in the world. At STK, she built a level-two scaling solution on Ethereum, allowing instant cryptocurrency purchases. Natalie won three prizes at ETHSanFrancisco, 2018, where her team, Lending Party, built a decentralized application allowing a CDP (cryptocurrency loan) to liquidate into a bank account instantly.
She is an avid hackathon organizer, associated with DeltaHacks and Stackathon, where she inspired new developers to join the blockchain space. Natalie is a Women in Tech ambassador and is always passionate about spreading knowledge about the blockchain field.
Ben Weinberg is a self-taught computer programmer who started off in iOS development with Objective-C and Swift, and, eventually, got caught up in the world of blockchain while working in Jerusalem. He eventually started learning blockchain and web development simultaneously with the goal of entering the blockchain space as a developer. Ben worked at the Toronto-based Bitcoin Bay, writing Solidity smart contracts and leading workshops on Ethereum development and Bitcoin opcodes. He also joined George Brown College, where he assisted aspiring blockchain developers as a lab monitor for George Brown's new blockchain development course. At George Brown, he helped teach full-stack web development, smart contract development, and decentralized application development.
Marc Lijour helps organizations strengthen their competitive advantage with technology such as blockchain and practices such as DevOps. Marc brings consulting experience from the public sector, Cisco, Savoir-faire Linux, and ConsenSys to executives driving innovation. He started the Metamesh Group with 30 consultants spanning across 5 continents. He helped George Brown launch the first blockchain development college program in Canada.
Marc holds degrees in mathematics and computer science, as well as an MBA in technology and innovation. He serves on the board of several not-for-profit organizations, including the Information and Communications Technology Council (ICTC), ColliderX, TechConnex, and the Toronto French Business Network.
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.
Title Page
Copyright and Credits
Mastering Blockchain Programming with Solidity
Dedication
About Packt
Why subscribe?
Foreword
Contributors
About the author
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
Download the color images
Code in action
Conventions used
Get in touch
Reviews
Section 1: Getting Started with Blockchain, Ethereum, and Solidity
Introduction to Blockchain
Understanding blockchain
Blockchain solves the double-spending problem
Properties of blockchain
Distributed ledger
Fault tolerance 
Attack resistance
Remove intermediaries
Consensus protocol
Faster settlement
Lower transaction fees
Transparency
Immutability
Irreversible transactions
Trust in the network
Artificial trust
Trustless systems
Availability
Empower individuals
Chronological order of transactions
Timestamped
Sealed with cryptography
When to use blockchain
When not to use blockchain
Blockchain is slow
Blockchain depends on off-chain oracles
Existing implementations of blockchain
Cross-border payments
Decentralized cloud storage
Decentralized computing
Introduction to Ethereum
Ethereum is for writing decentralized applications
Ethereum architecture
P2P networks
Nodes
Full nodes
Lightweight nodes
Miners
Blocks
Ethereum Virtual Machine (EVM)
Ether currency
Smallest unit – wei
Gas
Gas limit
Gas price
Formulas
Example
Ethereum accounts
Externally owned accounts
Contract accounts
The difference between an EOA and a contract
Ethereum transaction
Transaction fields
From
To
Value
Gas limit
Gas price
Nonce
Data
Transaction hash
Transaction status
Pending status
Success status
Fail status
Dropped status
Transaction operations
Replace/update
Cancel
Testnets
Smart contracts
Immutable code
Irreversible transactions
Think twice before deploying
Limited storage
Every transaction consumes gas in ether
Playing with ether or tokens
Summary
Questions
Getting Started with Solidity
Introduction to the Solidity language
The layout of a Solidity source file
Solidity version with pragma
Importing other source files
Structure of a contract
Declaring state variables
Writing function definitions
Creating a custom modifier using function modifiers
Using events for logging and callback
Custom data types with struct
Custom types for constants with enum
Solidity data types
Understanding Solidity value types
Integer value type
Boolean value type
Address value type
Reading a contract's ether balance
Sending ether using transfer
Sending ether using send
Understanding call and delegatecall functions
Understanding the staticcall function
Adjust gas for a transaction using gas
Forwarding ether to another contract
Changes in Solidity version 0.5.0 
Fixed size byte arrays
Dynamically sized byte arrays
Understanding the bytes data type
Understanding the string type
Passing functions using function types
Get a function type with function selector
Using internal function types
Using external function types
Solidity reference types
Understanding variables' data locations in Solidity
Using arrays in Solidity
Creating a key value map using mapping
Resetting variables using the delete keyword
Assigning variables with units
Specifying ether amounts using ether units
Supported units for time
Global special variables and functions
Using block and transaction properties
Getting block information using the block variable
Getting sender transaction info using the msg variable
Getting the current time using the now variable
Getting transaction info using the tx variable
Special functions
Application Binary Interface encoding functions
Error handling in Solidity
Cryptographic functions
Contract-related functions
Get the contract address using this keyword
Destroying contracts using the selfdestruct function
Destroying contracts using the suicide function
Topics for self-study
Summary
Questions
Further reading
Control Structures and Contracts
Understanding Solidity control structures
Returning multiple values from function
Expression evaluation order
Solidity contracts
Creating contracts
Creating child contracts using the new keyword
Using variable and function visibility
Getter functions for state variables
Creating custom function modifiers
Creating constant state variables
Understanding types of Solidity functions
Using view functions to read state variables
Using pure functions to perform calculations
Using the default fallback function
Overloading functions
Overriding function definition
Using emit and events for event logging
Inheriting contracts
Passing arguments for the base constructor
Understanding inheritance linearization
Creating abstract contracts
Creating interfaces
Creating custom reusable libraries
Using libraries with – using...for directive
Summary
Questions
Section 2: Deep Dive into Development Tools
Learning MetaMask and Remix
Technical requirements
Using the MetaMask plugin
Installing and setting up the MetaMask plugin
Connecting to different Ethereum networks
Getting test ether from faucets
Other features of the MetaMask plugin
Using the Remix Solidity IDE
The Remix IDE overview
Compiler tools present under the Compile tab
Understanding the Run tab
Selecting the environment to connect with
Choosing different wallet accounts
Transaction parameters
Selecting the contract to use
Using deploy and attach
Deploying a contract
Initiating a transaction to execute the function
Initiating a call to a view function and state variables
Connecting the contract folder using remixd
Setting up a local instance of the Remix IDE
Using the blockchain explorer at etherscan.io
Ethereum wallet software
Using myetherwallet.com
Summary
Questions
Using Ganache and the Truffle Framework
Technical requirements
Local blockchain with Ganache
Starting a local blockchain
Creating workspaces for projects
Ganache advance configuration
The command-line version of Ganache
Understanding Truffle framework
Setting up a Truffle project
Truffle configuration files
Configuring the Solidity compiler 
Configuring networks
Choosing which blockchain client to use
Personal blockchain client
Running blockchain nodes
Using Infura
Writing contract migration scripts
Trigger migration using the migrate option
Sample migration script
Using artifacts.require() to get the contract instance
Using module.exports
Deployer
Network considerations
Available accounts
Writing test cases
Writing test cases in JavaScript using Mocha
Writing test cases in Solidity
Debug transactions
Summary
Questions
Taking Advantage of Code Quality Tools
Technical requirements
Using the surya tool
Installing surya
Using surya describe
Generating an inheritance graph
Generating a function call graph
Parsing contracts
Generating function traces
Listing inheritance dependencies
Generating the markdown report
Understanding Solidity linters
Using the solhint linter
Installing the solhint linter
Using solhint
Using the ethlint linter
Installing ethlint
Using solium
The solidity-coverage tool
Installing solidity-coverage
Using solidity-coverage
Summary
Questions
Section 3: Mastering ERC Standards and Libraries
ERC20 Token Standard
Technical requirements
Overview of the ERC20 token standard
Use of ERC20 in crowdfunding
The motivation behind the ERC20 standard
ERC20 standard API
ERC20 implementation
Contract state variables
The balances variable stores account balance
The allowed variable stores approved balances
The totalSupply variable stores the total token supply
The transfer function
Difference between the ether and token transfer functions
Token transfer does not notify the contact
Tokens can be locked
The transfer transaction details
The approve function
Front-running attack on the approve function
Preventing a front-running attack
The transferFrom function
Two-step process for contracts
The allowance function
The balanceOf function
The totalSupply function
Events
The Transfer event
The Approval event
Optional functions
The name function
The symbol function
The decimals function
Advanced functions
The increaseApproval function
The decreaseApproval function
Summary
Questions
ERC721 Non-Fungible Token Standard
Technical requirements
Overview of the ERC721 NFT standard
The ERC721 NFT standard API interface
Understanding the ERC721 implementation
ERC721 inherits from IERC721 and ERC165
ERC721 inherits from ERC165
ERC721 inherits from IERC721
Understanding ERC721 state variables
Token owner mapping kept in _tokenOwner
Approved address mapping kept in _tokenApprovals
The number of tokens per owner kept in _ownedTokensCount
Operator approvals kept in _operatorApprovals
The ERC165 interface code for the ERC721, _INTERFACE_ID_ERC721
The ERC165 interface code for the ERC721Receiver, _ERC721_RECEIVED
The constructor of ERC721
The balanceOf function
The ownerOf function
The approve function
The getApproved function
The setApprovalForAll function
The isApprovedForAll function
The transferFrom function
The safeTransferFrom function
Another safeTransferFrom function
The _exists internal function
The _isApprovedOrOwner internal function
The _mint internal function
The _burn internal function
Another _burn internal function
The _transferFrom internal function
The _checkOnERC721Received internal function
The _clearApproval internal function
Events
The Transfer event
The Approval event
The ApprovalForAll event
The ERC721TokenReceiver interface
The ERC721Metadata interface
The ERC721 enumerable
The ERC721 full implementation
Summary
Questions
Deep Dive into the OpenZeppelin Library
Technical requirements
The OpenZeppelin project 
Installation
Usage
Contract ownership
Contract ownership using Ownable.sol
Claimable ownership using Claimable.sol
Roles library
Managing roles using Roles.sol
Manage PauserRole using PauserRole.sol
Other roles
Life cycle contracts
Pause/unpause functions using Pausable.sol
The ERC20 token standard library
ERC20 interface – IERC20.sol
Full ERC20 implementation using ERC20.sol
Perform safe ERC20 function calls using SafeERC20.sol
Create tokens with metadata using DetailedERC20.sol
Create mintable tokens using ERC20Mintable.sol
Allow token burning using ERC20Burnable.sol
Create pausable tokens using ERC20Pausable.sol
Math-related libraries
Aggregation functions using Math.sol
Arithmetic calculation using SafeMath.sol
Crowdsale
Create crowdsale using Crowdsale.sol
Create whitelisted crowdsale using WhitelistCrowdsale.sol
Other crowdsale contracts
Utility contracts
Check for contracts using Address.sol
Prevent reentrancy attacks using ReentrancyGuard.sol
Summary
Questions
Using Multisig Wallets
Technical requirements
Understanding multisig wallets
Benefits of using multisig wallets
Precautions when using multisig wallets
Learning ConsenSys multisig implementation
Setting up your own multisig wallet
Deploying your multisig wallet contract
Sending ETH from a multisig contract
Controlling contracts with multisig
Summary
Questions
Upgradable Contracts Using ZeppelinOS
Technical requirements
Understanding upgradable contracts
Introduction to ZeppelinOS
Creating a ZeppelinOS project
Deploying the StableToken contract
Upgrading the contract
ZeppelinOS commands
Precautions while using ZeppelinOS
Precautions for state variables
Avoid changing the variable declaration order
Avoid changing variable data types
Avoid adding new variables before existing variables
Avoid removing existing state variables
Always add new variables at the end
Precautions when changing variable names
Avoid initial values in the field declaration
Precautions for contract inheritance
Avoid changing the inheritance order
Avoid adding new state variables in base contracts
Summary
Questions
Building Your Own Token
Technical requirements
Features of our token
Contract architecture design
Designing an ERC20 MST token
Designing an MST crowdsale contract
Setting up the Truffle project
Updating configuration
Creating Solidity contracts
The MSTToken.sol contract
The MSTCrowdsale.sol contract
Compiling contracts
Writing a migration script
Running Ganache
Running migration scripts
Writing test cases
Deploying contracts on testnet
Infura APIs
Updating the configuration
Setting up wallet mnemonics
Installing dependencies
Deploying contracts on testnet
Summary
Questions
Section 4: Design Patterns and Best Practices
Solidity Design Patterns
Security patterns
Withdrawal pattern
Applicability 
Access restriction pattern
Applicability
Emergency stop pattern
Applicability
Creational patterns
Factory contract pattern
Applicability
Behavioral patterns
State machine pattern
Applicability
Iterable map pattern
Applicability
Indexed map pattern
Applicability
Address list pattern
Applicability
Subscription pattern
Applicability
Gas economic patterns
String equality comparison pattern
Applicability
Tight variable packing pattern
Applicability
Life cycle patterns
Mortal pattern
Applicability
Auto deprecate pattern
Applicability
Summary
Questions
Tips, Tricks, and Security Best Practices
Technical requirements
Smart contracts best practices
Avoiding floating pragma
Avoid sharing a secret on-chain
The commit-and-reveal scheme
Be careful while using loops
Avoid using tx.origin for authorization
Preventing an attack
The timestamp can be manipulated by miners
The 15-second blocktime rule
Carefully making external function calls
Avoid dependency on untrusted external calls
Avoid using delegatecall to untrusted contract code
Rounding errors with division
Using assert(), require(), and revert() properly
Gas consumption
Known attack patterns
Front-running attacks
Example of an ERC20 approve function
Preventing an attack on the approve function
Other front-running attacks
Reentrancy attacks
Preventing a reentrancy attack 
Replay attack
Signature replay attacks
Preventing a signature replay attack
Integer overflow and underflow attacks
Ether can be sent forcibly to a contract
Prevention and precaution 
Security analysis tools
Using the Securify tool
Summary
Questions
Assessments
Chapter 1
Chapter 2 
Chapter 3
Chapter 4
Chapter 5
Chapter 6
Chapter 7
Chapter 8
Chapter 9
Chapter 10
Chapter 11
Chapter 12
Chapter 13
Chapter 14
Other Books You May Enjoy
Leave a review - let other readers know what you think
Blockchain technology is at its nascent stage. However, technology is slowly moving forward and new developments using blockchain are emerging. This technology has the power to replace trusted third parties with trusted blockchain networks. Bitcoin was the birth of blockchain technology and has shown the world a new peer-to-peer payment system without needing intermediaries. You could say that Bitcoin was the first generation of blockchain technology. However, Ethereum took this innovative technology to the next level—you could call it blockchain generation two—where you can write decentralized applications using smart contracts. Solidity is the most widely used and popular language for writing smart contracts for decentralized applications.
The book starts with explaining blockchain, Ethereum, and Solidity. It mostly focuses on writing production-ready smart contracts in the Solidity language for Ethereum blockchain. It covers basic Solidity language syntax and control structures, and moves on to writing your own contract. It also deep dives into different libraries that you can use while writing contracts. Later on, it covers tools and techniques to write secure, production-ready smart contracts.
This book is for professional software developers who have started learning blockchain, Ethereum, and the Solidity language and who want to make a career in writing production-ready smart contracts. This book is also aimed at developerswho are interested in building decentralized applications over Ethereum blockchain. This book will help you learn the Solidity language for building smart contracts from scratch and make you proficient in building production-ready smart contracts for decentralized applications.
Chapter 1, Introduction to Blockchain, starts with how blockchain technology came into existence through the innovation of Bitcoin. This chapter discusses the different properties of a blockchain. It also introduces Ethereum and how it is different from the Bitcoin blockchain. Later, this chapter introduces smart contracts.
Chapter 2, Getting Started with Solidity, starts with the basic Solidity language syntaxes and the structure of a contract. You will learn about the different data types available in Solidity. This chapter also discusses globally available variables present in the Solidity language that you can use while writing your smart contract.
Chapter 3, Control Structures and Contracts, deep dives into the control structures of Solidity contracts, the different types of functions supported, contract inheritance, and event logging.
Chapter 4, Learning MetaMask and Remix, discusses setting up your MetaMask plugin and creating wallets using it. This chapter also discusses using the online Remix IDE to create, compile, deploy, and interact with your Solidity contracts.
Chapter 5, Using Ganache and the Truffle Framework, discusses installing and setting up your local blockchain instance using Ganache. This chapter also discusses installing and setting up the Truffle framework, learning how to use its commands, setting up your new Truffle project, writing migration scripts for the Truffle framework, and adding test cases to a project.
Chapter 6, Taking Advantage of Code Quality Tools, discusses improving the quality of your contracts by using open source tools such as surya, which helps in generating different kinds of reports. This chapter also discusses using Solidity linters to lint your code and fix common issues present in your contracts, as well as running Solidity coverage tools to generate code coverage reports.
Chapter 7, ERC20 Token Standard, covers the introduction of the ERC20 token standard. This chapter deep dives into its full implementation details, provides an in-depth study of each function of the standard, and covers different events, optional functions, and a number of advanced functions.
Chapter 8, ERC721 Non-Fungible Token Standard, starts with an introduction to the ERC721 standard and the difference between the ERC20 and ERC721 standards. This chapter deep dives into each of the state variables, functions, and events associated with ERC721 implementation. This chapter also discusses some other optional contracts that can be used with the ERC721 standard.
Chapter 9, Deep Dive into the OpenZeppelin Library, starts with an introduction to OpenZeppelin library contracts. This chapter will help you learn how to install and use OpenZeppelin library contracts in your Truffle project. It also provides in-depth studies of library contracts such as Ownable, Claimable, Roles, PauserRole, Pausable, ERC20, SafeERC20, DetailedERC20, ERC20Mintable, ERC20Burnable, ERC20Pausable, Math, SafeMath, Crowdsale, Address, and ReentrancyGuard.
Chapter 10, Using Multisig Wallets, The multisig wallets are special contracts that require multiple signatures to execute a transaction. This chapter provides an introduction to multisig contracts and their usage. This chapter also covers installing, creating, and setting up your own multisig wallet, as well as how to use and control it.
Chapter 11, Upgradable Contracts Using ZeppelinOS, provides an introduction to the ZeppelinOS development platform. Topics covered include creating a new project using zos commands, creating an upgradable contract, deploying, re-deploying to upgrade the contract, and some precautions to take when using ZeppelinOS for writing upgradable contracts.
Chapter 12, Building Your Own Token, helps you learn how to create your own ERC20 token contract from scratch. You will learn how to draft the specification of a contract, set up a Truffle project, create a contract, choose which OpenZeppelin libraries to use, write migration scripts, write test cases, execute migration scripts and test cases in Ganache, and finally, test your contracts on a testnet such as Rinkeby.
Chapter 13, Solidity Design Patterns, introduces different Solidity design patterns. These are divided into five categories: Security patterns: Withdrawal, Access restriction, and Emergency stop; Creational patterns: Factory pattern; Behavioral patterns: State machine, Iterable map, Indexed map, Address list, and Subscription; Gas economic patters: String comparison and Tight variable packing; and Life cycle patterns: Mortal and Auto deprecate pattern.
Chapter 14, Tips, Tricks, and Security Best Practices, helps you to learn different Solidity smart contract best practices, such as avoiding floating pragma, the 15-second blocktime rule, rounding errors, and gas consumption. It also helps you to learn about different security attacks, such as front-running, reentrancy, signature replay, integer overflow and underflow, and how to prevent these attack patterns.
You should have knowledge of any of the existing programming languages. Solidity language syntaxes are very similar to Java, JavaScript, and Python syntaxes. A developer who has created projects using Java, JavaScript, or Python can pick up and learn Solidity very easily. You should also have some basic knowledge of OOPS concepts, blockchain, wallets, private key, public key, consensus algorithms, and exchanges.
One very important thing to note here is that, in order to write smart contracts for decentralized applications, you need to have a completely new mindset. Up until now, you have probably been building applications using Java, JS, or another language in which you can fix bugs later on, even in the production environment when something goes wrong. However, smart contracts are immutable. If your contract is deployed in production, you are done. If there is a bug left in the contract, you will be unable to fix it. Hence, you need to ensure that all your smart contracts are well-tested and have no bugs present in them.
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 versions of the following:
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/Mastering-Blockchain-Programming-with-Solidity. If 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!
We provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it at https://static.packt-cdn.com/downloads/9781839218262_ColorImages.pdf.
To see the code being executed please visit the following link: http://bit.ly/2Yv6kpm.
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: "Solidity supports different data types, including uint, int, address, and many more."
A block of code is set as follows:
contract
VariableStorage {
uint
storeUint
;
//uint256 storage 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:
contract
VariableStorage {
uint
storeUint
;
//uint256 storage variable
//...
}
Any command-line input or output is written as follows:
$ npm install -g ganache-cli
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "As mentioned earlier, you can start a local Ganache blockchain instance by just clicking on the QUICKSTART button."
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, select your book, click on the Errata Submission Form link, and enter 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.
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.
In this section, the reader will learn about blockchain's what, why, and when. It will also include an overview of Ethereum blockchain, accounts, and transactions.
The following chapters will be covered in this section:
Chapter 1
,
Introduction to Blockchain
Chapter 2
,
Getting Started with Solidity
Chapter 3
,
Control Structures and Contracts
Blockchain technology was born with the invention of Bitcoin—a new form of peer-to-peer (P2P) electronic cash—back in 2008. The Bitcoin white paper was released on October 31, 2008 and the first release of Bitcoin came on January 3, 2009. The blockchain space is still a toddler in terms of adoption and the tools available. It has some unique properties that did not exist before in any of the previous systems or software applications. The most important property of blockchain is establishing trust between two or multiple parties without needing any intermediaries, which opens a new era in programming.
Ethereum is one of the implementations of blockchain. Ethereum is an open source, public, and distributed computing platform. On Ethereum, developers can deploy smart contracts written in the Solidity language and build a decentralized application—also called dApp, Ðapp, Dapp, or DApp.
Smart contracts are small programs where developers can define the rules of the trust that they intended to code. One of the mind-boggling properties of smart contracts is immutability—once they are deployed on the blockchain, their code cannot be changed. This immutable property makes it very hard to program smart contracts and predict errors/bugs beforehand.
In this chapter, we will learn more about blockchain technology, and when and where blockchains should be used. We will also introduce Ethereum and smart contracts.
The following topics will be covered in this chapter:
Introduction to blockchain
Properties of a blockchain
What is Ethereum?
Introduction to smart contracts
Why smart contracts are different from traditional software programs
A blockchain is a timestamped series of immutable transactions that is managed by a cluster of computers using special computer algorithms. These immutable records are not owned by any single entity. A blockchain is a decentralized P2P network of nodes. Each node in a blockchain shares the same copy of data, also called the digital ledger. Each node present in the network uses the same algorithm to reach a consensus.
A blockchain, by design, is resistant to the modification of data. The ledger can record transactions between two parties in a verifiable and permanent way. Whenever there is a change in the ledger using transactions, changes are distributed to all the nodes, to verify and update their own copy of the ledger. Once a transaction is stored and verified by all the nodes in the network, then it is not feasible to change the transaction without altering all the subsequent and previous blocks. That's why blockchain transactions are irreversible, as blockchain transactions and their data are append only.
Each computer that participates in this P2P network is called a node. Each node maintains the records of transactions in multiple consecutive blocks. The P2P network is also used in torrents such as BitTorrent; however, torrent networks are not like blockchains, as they are designed to shares files only.
Blockchain technology is also called Decentralized Ledger Technology (DLT), as each node in the network keeps the same copy of the ledger. Please have a look at the following diagram:
In the preceding diagram, each block is connected with a link (also known as a chain). The chain is usually recognized as the chain of all the blocks. The link between two blocks is implemented by having a record of the cryptographic hash of the previous block in each block, so that you can visit the chain in reverse chronological order.
One question that may arise in your mind is, what is the difference between a traditional software application that processes the transaction and a blockchain that also processes the transaction? Then, why you would need blockchain technology? Well, blockchain technology solved one of the hard problems of computer science—the double-spending problem. Let's understand what is the double-spending problem..
As we know, we can share documents and pictures over the internet with someone. When we share those documents or pictures with another person, we actually share a copy of the file. Once that copy is sent to another person, you and the other person have the same copy of that document.
However, things such as money, bonds, and shares must not be shared as copies, like we do for documents/pictures when we need to transfer them over the internet. If you try to send money P2P, without using any intermediaries, then both parties end up having the same copies of the money. This is called the double-spending problem.
For example, if Alice gives a $10 bill to Bob, then Alice must not hold a copy of the $10 bill, as it's given to Bob. These are called value transfers. To transfer those items that have values over the internet, we need to depend upon Trusted Third Parties (TTPs). Banks and stock exchanges are the TTP on which we rely for transferring values (money and shares) from person A to B. For value transfers between two parties over the internet, they both have to depend upon a trusted middle party (centralized) to process the transactions and ensure the safety of transactions.
Blockchain solved this double-spending problem. Now, for value transfers between two parties, neither of them have to depend upon a middleman (trusted party). They both can do safe transactions directly. Blockchain's decentralized network and consensus algorithm ensures the safety of transactions and prevents the double-spending problem.
Blockchain has properties of both decentralized and distributed networks. Using those types of networks along with cryptography adds more properties. We are covering properties related to the Ethereum blockchain rather than other blockchain implementation properties. The other blockchain implementations might have different properties. Let's discuss those properties.
Multiple nodes make up a distributed blockchain network. All nodes share a common ledger, where records of transactions are kept.
A blockchain network is distributed and each node maintains the same record of the ledger. Even if some nodes in the network are corrupted or go down, it can continue operating safely up to a certain limit, as well as processing transactions with running nodes.
A blockchain network does not have centralized control. The network's resistance to attacks is maintained by the miners who are putting their processing power (using nodes) into use to guard against malicious attacks. These miners earn some incentives to keep the network safe by behaving honestly. This is done by using the distributed network and cryptographic techniques.
Blockchain technology removes the dependence on TTP/middle parties/intermediaries. Using blockchain technology, a transaction can be done directly between two entities/systems. In place of intermediaries, we can place blockchain systems.
This is a protocol that ensures that all nodes participating in the network ensure the safety of the network. All nodes use a consensus protocol (a specific algorithm) to reach a consensus and discard the blocks generated by the attacker/bad node, to avoid catastrophic system failure. For example, Bitcoin and the Ethereum blockchain, at the time of writing, work on the Proof-of-Work (PoW) consensus protocol. Ethereum uses the Ethash PoW consensus algorithm, which is Application Specific Integrated Circuit (ASIC) resistance. In the future, Ethereum will switch its consensus algorithm from PoW to Proof-of-Stake (PoS).
Traditional banking systems can be slow in some cases, as they need additional time for processing a transaction; for example, cross-border payments.. However, with blockchain technology, there are no intermediaries; therefore, the transaction happens directly between entities and the settlement is much faster, compared to traditional systems.
Using the traditional banking system, doing a cross-border payments is costly. The intermediaries take their commission to process the transaction between two parties. But by using blockchain technology, the cost of doing transactions is significantly lower because we can remove the intermediaries and perform the transactions directly.
Some blockchain systems maintain transparency. Ethereum is a public blockchain network. All the transactions of the Ethereum blockchain are public and transparent. Anyone can see the balance and transaction history of any wallet at any time, just by accessing the Ethereum public blockchain via a block explorer. However, some work toward having privacy on the Ethereum blockchain is being done; for example, using the AZTEC protocol.
Every transaction that happens on the Ethereum blockchain is immutable. Smart contracts on the Ethereum blockchain are also immutable. Once the smart contract code is deployed, it cannot be changed. Smart contract code will remain on the blockchain forever. Anyone can see any deployed smart contract any time in the future as well, just by putting its contract address on the block explorers. Data that is being stored in smart contract variables is also immutable, unless there are data removal techniques that have not been exposed by the contract code.
Once a transaction is executed on a blockchain and it receives sufficient confirmation, the transaction becomes irreversible. The irreversible transaction ensures the safety of the value transfer. The higher the number of confirmations received for a transaction, the harder it becomes to reverse the transaction from the attacker.
As of today, we are using the existing TTP systems of bank servers or stock exchange trade servers. These are centralized and are continuously being attacked. If an attacker takes control of the database server of a trade server, it can make changes in the database and put in fake entries.
However, the immutability and irreversibility of transactions makes blockchain technology more trusted. It becomes very hard for an attacker to change any entries in the blockchain transactions. This makes blockchain more trusted in terms of maintaining pure immutability and irreversible transactions. You can trust the Ethereum public mainnet; however, you cannot trust testnet completely (this may change, but at the moment, testnet is only used for testing).
I am going to define two types of trust here—artificial trust and trustless systems.
When replacing trusted middle parties (intermediaries) with blockchain technology, I call it artificial trust. Blockchain technology will be trusted while doing P2P transactions. A person only has to trust the blockchain technology that is going to execute their transaction.
Two people, without knowing each other, can do transactions using blockchain technology. They do not have to trust each other, they only have to trust blockchain technology. For both persons, it is a trustless system.
Centralized systems sometimes have to go through regular maintenance and downtime, resulting in inconvenience to the users. The blockchain is decentralized, so even if some nodes go down/are corrupted, the network will continue to function and will be available to process transactions 24/7.
Each individual entity/person has their own wallet's public and private keys on the blockchain network. Using those wallets, they are in full control of their assets and the privileges available for those wallets. Blockchain assures that the ownership of a person's data is in their hands.
However, an individual can only maintain full control over their cryptocurrency or data when they own the private keys of their wallet. When the private keys of their wallet is maintained by another entity, such as centralized exchanges, they may not have full control.
Blockchains keep their transactions in blocks. Multiple transactions are coupled together and stored in a new block. Next, that new block is appended to the chain of previous blocks. This keeps all the blockchain transactions maintained in chronological order.
Every transaction on the blockchain is stamped with the current time. This enables the blockchain to maintain all the transaction histories of an account. Also, this can be used to prove whether or not a transaction happened on a certain date and at a certain time.
Asymmetric cryptography is used for wallet generation and transaction signing using the Elliptic Curve Digital Signature Algorithm (ECDSA). All transactions are packed together using the Merkle tree and SHA-256 cryptographic algorithms. This makes blockchains secure and reliable to use.
As we have looked into the double-spending problem, blockchain technology solves this problem and opens new opportunities to create programs/systems where we can remove the trusted parties and make value transfers between two people directly.
The first implementation of blockchain is the Bitcoin blockchain. The Bitcoin blockchain solves the problem of making value transfers. A person can transfer bitcoins (these have some value) to another person without needing a middle party to process the transaction. Because trust is now transferred from middle parties (TTP) to the blockchain decentralized network, which uses a consensus algorithm called PoW to ensure the trust and safety of transactions.
The Ethereum blockchain, on the other hand, is a generic blockchain, on which you can write smart contracts and define the rules of the trust. In a way, if you can define trust in a code language, you can write smart contracts.
Use blockchain technology as a tool for the development of specific scenarios. As we have seen in previous sections, blockchain technology can solve some problems where you want to replace an intermediary/middleman/TTP and do P2P value transfer transactions. This also includes problems where it is possible to replace existing trust with software-defined trust, using smart contracts.
You should not use Blockchain to replace your existing database. If your specification requirements can be solved with other software tools and techniques, then you should use those only. If there is no requirement for blockchain in your system architecture, avoid using it. For example, you do not need blockchain when building very high throughput, latency-critical transaction processing systems. However, when blockchain technology improves in terms of high throughput in the future, and you need some of the previously discussed properties of blockchain in your system, it would be a wise decision to use it.
At the time of writing, the implementation of the Ethereum blockchain is slow and cannot handle high transaction throughput. There are some Ethereum upgrades scheduled to improve transaction throughput. Experiments and developments in improving transaction throughput for different blockchain implementations are still going on.
Let's compare the current situation of Ethereum with improvements planned for the future:
As of now, Ethereum is like a single-threaded computer. It can process one transaction at a time.
Sharding of blockchain would improve it and make it like a multithreaded computer. It would be able to process more transactions in parallel.
The
PoS
consensus algorithm would help increase the reliability of the chain when a new block is generated in the blockchain.
Layer 2 solutions, such as plasma and state channels, would enable
off-chain
transactions to process in near real time, and these transactions would be sent to the main chain periodically.
Considering the slowness and limited storage of Ethereum, it is not advisable to use Ethereum for pure database usage or for high processing power requirements. Storage on the blockchain is costly, so we should ensure that we know what we are trying to develop and whether it really requires the blockchain to be involved in its application architecture.
On their own, a blockchain is a separate network. It uses P2P networking over the internet to keep sharing transactions between nodes, but it does not have a way to get the data from outside (such as any data present on the internet, other than blockchain data) of the blockchain network, also known as off-chain data.
For example, the Ethereum blockchain cannot fetch any data from the internet on its own. There are some third-party developed Oracle services; by using them, you can fetch the data from the internet to the blockchain and do your transactions.
If your application is highly dependent upon third-party data available on the internet, then you should not use blockchain. If your off-chain data requirement is small enough, then you can use Oracle services and do your transactions on the Ethereum network. For example, when you just need currency version rates from the internet, you can use Oracle services.
When you are building a decentralized application on a public Ethereum blockchain and require off-chain data, you can use Oracle services such as Oraclize or ChainLink.
When you are building private applications using a private Ethereum blockchain and require off-chain data, you can write your own Oracle service application to read the data from off-chain. You can write your own Oracle to read some private data (such as data that's internal to the company) as well.
There are many industries where blockchain technology can solve some problems. Let's take some examples and existing solutions that use blockchain technology to solve some bigger issues.
Cross-border payments are processed by multiple banks and take some time to process money transfers. Using blockchain, these banks can do cross-border payment transactions fast and almost instantly. Companies such as Ripple and Stellar are solving cross-border payments along with multiple banks. For example, in the year 2018 itself, HSBC bank moved $250 billion using DLT.
You might be keeping your important files/pictures on centralized cloud storage such as Google Drive and DropBox. This centralized cloud storage is prone to attacks and these companies have full control over your files. By using decentralized data storage such as 3Box, you can store your public or private data on the blockchain.
If you have CPU resources available when you are not using your laptop or PC, then you can rent out your CPU power to a decentralized blockchain network. Someone who is in need of higher CPU usage would take your machine's CPU resources over the internet and, in return, pay you a small fee. For example, projects like Golem and iExec.
Ethereum was proposed in 2013 by Vitalik Buterin, a cryptocurrency researcher and programmer. The first production release launched in 2015. Ethereum is an implementation of blockchain, and is an open source, public, and decentralized computing platform. Ethereum gained popularity because of its smart contract's features. Developers can program their smart contracts and execute them on the blockchain platform so that the full potential of the blockchain's different properties can be used.
As discussed before, Bitcoin uses blockchain technology for payments using bitcoins as a currency. Bitcoin also supports a scripting language, with which you can write small scripts. Bitcoin scripts have limited functionalities and it is difficult to write complex scripts on it. Its scripting language is also not Turing-complete (it does not support loops). Bitcoin transactions are slow; normally, it gets processed in 10 minutes or more.
With Ethereum, writing complex smart contracts and utilizing other properties of blockchain becomes easy. Any programmer who knows Java, JavaScript, and other programming languages can easily learn to code in the Solidity language. Solidity is a Turing-complete language. Transactions on Ethereum are processed much faster as compared to Bitcoin transactions. Using all of these potentials, you can write decentralized applications that would run on the Ethereum blockchain.
Ethereum architecture consists of multiple entities that make its blockchain network. An Ethereum network has all the nodes connected to each other using the P2P network protocol; each node keeps the latest copy of the Ethereum blockchain ledger. A user can interact with the Ethereum network via the Ethereum client. The Ethereum client can be a desktop/mobile/web page:
Let's discuss these entities.
In a P2P network, two or more computers are connected to share their resources without going to a centralized server or machine. Nodes connected in a P2P network can share or consume network resources.
Nodes are devices in the blockchain network, which make the mesh of the blockchain network. Nodes can perform various types of tasks, such as being an active computer, cell phone, or disk drive as long as they are connected to the internet, and they participate in a blockchain network.
A node keeps the latest copy of the blockchain data (ledger) and, in some cases, processes the transactions as well. Miners put nodes on the network and willingly share their computing power or disk space. Nodes can be of two types—full nodes or light nodes.
A full node in a blockchain network maintains the complete data structure of the blockchain ledger and participates in the blockchain network by verifying every block and transaction using their consensus rules. Full nodes always keep the latest copy of the ledger.
A light node does not maintain the full copy of the blockchain ledger. It verifies the transaction using a method called Simple Payment Verification (SPV). SPV allows a node to verify whether a transaction has been included in the blockchain or not. This is verified without the need to download the entire blockchain on a machine. A light node just downloads the header information of the blocks, hence lower storage space is required in running light nodes.
Owners of the nodes willingly contribute their computing resources or hard disk space to store and validate transactions; in return, they collect block reward and transaction fees from the transactions. The nodes that perform transaction execution and verification are called miners.
The blockchain maintains a series of blocks. Each block is linked together with the last generated block. A block contains multiple transactions. At the time of writing this book, blocks are generated using a PoW consensus algorithm called Ethash in Ethereum. In future it is planned to change to PoS.
Miners share their processing power with the Ethereum blockchain network to process all pending transactions and generate a new block. Each block is generated in approximately 15 seconds. At the time of writing, a miner who generates the block is rewarded with 3 ETH in their wallet. It is proposed that, in the future, it will be reduced from 3 ETH to 2 ETH per block. It may change in future as well.
Each block has a defined gas limit: as of now, it is 8 million gas per block. This means that the total gas consumed by the transactions included in the block cannot exceed the 8 million gas limit per block.
A block contains a block header and transactions. A block can contain at least one transaction. A new block is added to the blockchain and linked to the previous block. The very first block in the blockchain is called the genesis block:
The block header contains metadata about the block and the previous block. It contains multiple fields, but it's only necessary to understand a few to have an idea of block generation:
The Parent Hash always points to the parent block of the newly generated block. This child-to-parent link goes on until the genesis block.
The Nonce is the number that is found by the miner to solve the cryptographic puzzle.
The Receipts Root is the Keccak 256-bit hash of the root node of the tree structure, which is populated with the receipts of each transaction.
The Timestamp is the time when the block is found and added to the blockchain.
The Transactions Root is the Keccak 256-bit hash of the root node of the tree structure, which is populated with each transaction.
The State Root
