34,79 €
Ethereum and Blockchain will change the way software is built for business transactions. Most industries have been looking to leverage these new technologies to gain efficiencies and create new business models and opportunities.
The Ethereum Cookbook covers various solutions such as setting up Ethereum, writing smart contracts, and creating tokens, among others. You’ll learn about the security vulnerabilities, along with other protocols of Ethereum.
Once you have understood the basics, you’ll move on to exploring various design decisions and tips to make your application scalable and secure. In addition to this, you’ll work with various Ethereum packages such as Truffle, Web3, and Ganache.
By the end of this book, you’ll have comprehensively grasped the Ethereum principles and ecosystem.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 387
Veröffentlichungsjahr: 2018
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(s) 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 endeavoured 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: Pravin DhandreAcquisition Editor: Namrata PatilContent Development Editor: Eisha DsouzaTechnical Editor:Ishita VoraCopy Editor: Safis EditingProject Coordinator:Namrata SwettaProofreader: Safis EditingIndexer:Aishwarya GangawaneGraphics:Jisha ChirayilProduction Coordinator: Nilesh Mohite
First published: August 2018
Production reference: 1310818
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-399-8
www.packtpub.com
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.
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
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.
Manoj P R is a tech-savvy person who has been working with distributed ledger technology for more than three years. His passion for the latest technology trends in the market has made him an avid learner and contributor in this space. He specializes in Ethereum, JavaScript, and Go. A self-taught programmer, Manoj started his programming career as a freelancer during his early academic life. He has developed many scalable enterprise blockchain solutions for various clients across the globe. He is currently associated with Conduent Labs as a Blockchain SME. He loves solving real-life problems using technology and is a lively contributor towards open source projects. Apart from work, Manoj likes traveling and writing.
Mayukh Mukhopadhyay is an assistant consultant at Tata Consultancy Services who works on the big data and revenue assurance projects of the world's oldest telecommunication company, where he tames messy data to generate tangible insights. He has authored the book Ethereum Smart Contract Development and engages in occasional pro-bono consultation on blockchain implementation. He has a master's in Software Engineering from Jadavpur University and is an executive MBA candidate at IIT Kharagpur.
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
Ethereum Cookbook
Dedication
Packt Upsell
Why subscribe?
Packt.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
Getting Started
Introduction
Choosing a client for Ethereum
Getting ready
How to do it...
Geth
Parity
There's more...
Setting up a node and participating in a network
Getting ready
How to do it...
Working with the JavaScript console
Getting ready
How to do it...
There's more...
Saving time and money with INFURA
How to do it...
There's more...
Creating your own private Ethereum network
Getting ready
How to do it...
How it works...
There's more...
See also
Creating a blockchain network for development
Getting ready
How to do it...
There's more...
Using Azure Ethereum as a service
Getting ready
How to do it...
How it works...
Using MetaMask and other wallets
Getting ready
How to do it...
MetaMask
MyCrypto
Ethereum wallet–Mist
Using block explorer
How to do it...
There's more...
Understanding everything about accounts
Getting ready
How to do it...
There's more...
Installing a solidity compiler
Getting ready
How to do it...
There's more...
Smart Contract Development
Introduction
Choosing an IDE wisely
How to do it...
There's more...
Writing your first smart contract
Getting ready
How to do it...
How it works...
There's more...
Testing your contract with Remix
How to do it...
There's more...
Static and dynamic types in solidity
Getting ready
How to do it...
There's more...
Constructor and fallback functions
How to do it...
Constructor
Fallback function
Working with struct and enum
How to do it...
Structs
Enums
Control structures in Solidity
How to do it...
Writing functions in solidity
How to do it...
There's more...
Deciding between arrays and mappings
How to do it...
Arrays
Mapping
Where to use function modifiers
How to do it...
Using visibility modifiers efficiently
How to do it...
Essential events – EVM logger
Getting ready
How to do it...
Using storage and memory efficiently
How to do it...
There's more...
Compiling your contract with the solc compiler
Getting ready
How to do it...
There's more...
Deploying contracts using geth
Getting ready
How to do it...
There's more...
Interacting with the Contract
Introduction
Installing and configuring web3.js
Getting ready
How to do it...
Using MetaMask as an injected provider
Getting ready
How to do it...
How it works...
Managing accounts and sending transactions
Getting ready
How to do it...
Compiling and deploying your smart contract
Getting ready
How to do it...
There's more...
Reading data from smart contracts
Getting ready
How to do it...
Writing data into a smart contract
Getting ready
How to do it...
There's more...
Watching events from your DApp
Getting ready
How to do it...
Sending a raw transaction
Getting ready
How to do it...
There's more...
Batch requests using web3.js
Getting ready
How to do it...
Interacting with Ethereum using JSON-RPC
Getting ready
How to do it...
Other ways to interact with your contract
Getting ready
How to do it...
Nethereum
Web3J
The Truffle Suite
Introduction
Installing and configuring the Truffle framework
Getting ready
How to do it...
Making use of Truffle boxes
Getting ready
How to do it...
There's more...
Compiling smart contracts
Getting ready
How to do it...
Advanced Truffle configuration
Getting ready
How to do it...
Migration and deployment in Truffle
Getting ready
How to do it...
Interacting with your contract
Getting ready
How to do it...
There's more...
Debugging a smart contract using Truffle
Getting ready
How to do it...
Writing tests for smart contracts
Getting ready
How to do it...
Writing tests in JavaScript
Writing tests in Solidity
Building DApps and APIs using Truffle
Getting ready
How to do it...
Package management in Truffle
Getting ready
How to do it...
EthPM
npm
There's more...
Getting started with Drizzle
Getting ready
How to do it...
There's more...
Using HD wallet in Truffle
Getting ready
How to do it...
Tokens and ICOs
Introduction
Creating a basic ERC20 token in Ethereum
Getting ready
How to do it...
There's more...
Transferring tokens between accounts
Getting ready
How to do it...
There's more...
Delegating other accounts to spend your token
Getting ready
How to do it...
There's more...
Creating a token that can be minted
Getting ready
How to do it...
Creating a token that can be burnt
Getting ready
How to do it...
There's more...
Creating an ERC223 token
Getting ready
How to do it...
Building your own Initial Coin Offering
Getting ready
How to do it...
Adding features to the ICO contract
Getting ready
How to do it...
There's more...
Providing bonus tokens to investors
Getting ready
How to do it...
There's more...
Whitelisting users for the crowdsale
Getting ready
How to do it...
There's more...
Accepting crypto payments for the crowdsale
Getting ready
How to do it...
MetaMask
Shapeshift
BTC Relay
Creating a wallet that supports all ERC20 tokens
Getting ready
How to do it...
There's more...
Games and DAOs
Introduction
Creating a non-fungible token
Getting ready
How to do it...
There's more...
Asset tracking and movement
Getting ready
How to do it...
Creating a basic game on Ethereum
Getting ready
How to do it...
Building a decentralized lottery on Ethereum
Getting ready
How to do it...
Selecting a winner based on the ticket number
Getting ready
How to do it...
Sharing dividends among investors
Getting ready
How to do it...
Affiliating programs to attract more users
Getting ready
How to do it...
Advanced Solidity
Introduction
Handling errors properly in solidity
Getting ready
How to do it...
require()
revert()
assert()
Abstract and interface contracts
Getting ready
How to do it...
Abstract contracts
Interface contracts
Managing contracts from other contracts
Getting ready
How to do it...
There's more...
Contract inheritance in solidity
Getting ready
How to do it...
Creating libraries in solidity
Getting ready
How to do it...
How it works...
There’s more...
Mathematical and cryptographic functions in solidity
Getting ready
How to do it...
There's more...
Creating upgradable smart contracts
Getting ready...
How to do it...
How it works...
Fetching data from APIs using solidity
Getting ready
How to do it...
How it works...
There's more...
Function as a type in solidity
Getting ready
How to do it...
Understanding solidity assembly
Getting ready
How to do it...
There's more...
Implementing multisig wallets in solidity
Getting ready
How to do it...
Smart Contract Security
Introduction
Integer overflow and underflow
Getting ready
How to do it...
There's more...
Re-entrancy attack
Getting ready
How to do it...
The parity hack
Getting ready
How to do it...
Forcing Ether to a contract
Getting ready
How to do it...
There's more...
Use of private variables
Getting ready
How to do it...
Transaction-Ordering Dependence (TOD)
Getting ready
How to do it...
Call to the unknown
Getting ready
How to do it...
DoS using loops
Getting ready
How to do it...
Security analysis tools for solidity
Getting ready
How to do it...
Uninitialized storage pointer in solidity
Getting ready
How to do it...
Best practices in solidity
How to do it...
Design Decisions
Introduction
Serverless architecture for DApps
Getting ready
How to do it...
Implementing an application-specific wallet
Getting ready
How to do it...
What if you find a bug after deployment?
Getting ready
How to do it...
Generating random numbers in Solidity
Getting ready
How to do it...
Keeping contracts simple, modular, and up to date
Getting ready
How to do it...
Implementing user authentication in Ethereum
Getting ready
How to do it...
Other Protocols and Applications
Introduction
Registering on Ethereum Name Service
Getting ready
How to do it...
How it works...
Whisper–communication protocol for DApps
Getting ready
How to do it...
Swarm–distributed storage platform
Getting ready
How to do it...
Watching Bitcoin transactions using BTCRelay
Getting ready
How to do it...
Scheduling Ethereum transactions using an alarm clock
Getting ready
How to do it...
Using the openzeppelin library
Getting ready
How to do it...
Miscellaneous
Introduction
Using Vyper to write smart contracts
Getting ready
How to do it...
There's more...
Debugging smart contracts with Remix
Getting ready
How to do it...
Deploying contracts using Remix
Getting ready
How to do it...
Generating documentation for solidity code
Getting ready
How to do it...
Writing better code with the help of a linter
Getting ready
How to do it...
Sharing solidity code with others
Getting ready
How to do it...
Other Books You May Enjoy
Leave a review - let other readers know what you think
With this practical guide, you will learn how to set up Ethereum and connect to a network, write and deploy quality smart contracts, use Truffle and Ganache to manage your development, create your own Tokens and ICOs, build decentralized games and organization, create your own wallet that supports multiple tokens, and much more.
You'll also learn about the security vulnerabilities that can arise and various other protocols of Ethereum. Moving on, you’ll learn the various design decisions and tips to make your application scalable and secure. With this book and the advanced topics it covers, you can get well versed with the Ethereum principles and ecosystem.
If you want to set up an Ethereum blockchain network, write and deploy smart contracts, build decentralized applications (DApps) or facilitate peer-to-peer transaction, then this book is for you. It is recommended that the readers should be familiar with basic blockchain concepts and knowledge of JavaScript and NodeJS.
Chapter 1, Getting Started, covers the very basics of Ethereum and its tools. You will find the steps required to set up and run a network and interact with it.
Chapter 2, Smart Contract Development, contains a set of recipes that will help you write smart contracts. It also covers the steps to compile, deploy, and test the contracts that you have written.
Chapter 3, Interacting with the Contract, covers the topics that are essential for building a decentralized application (DApp) that can interact with blockchain and the contracts.
Chapter 4, The Truffle Suite, explains a popular tool in the Ethereum ecosystem. This chapter also explains the use cases that will help you to have a better development workflow and build better DApps.
Chapter 5, Tokens and ICOs, covers the topics necessary for you to build your own Ethereum-based token and distribute it through ICO.
Chapter 6, Games and DAOs, takes you through a series of interesting recipes that will help you create your own decentralized game or organization.
Chapter 7, Advanced Solidity, contains more advanced recipes about the smart contract language that will help you to achieve more complex tasks efficiently in the Blockchain.
Chapter 8, Smart Contract Security, is designed to help you understand more about the common vulnerabilities and ways to avoid them. It also takes you through the set of tools you can use to analyze the code.
Chapter 9, Design Decisions, contains the recipes to help you decide between the common design questions you may come across while developing a fully functional DApp.
Chapter 10, Other Protocols and Applications, walks you through some of the other Ethereum protocols and applications that might come in handy while building your DApp.
Chapter 11, Miscellaneous, includes a few additional recipes that can help you build better DApps.
It is recommended to have a basic idea about blockchain and its concepts to get the most out of this book. This book does not cover the basics of how blockchain works but focuses more on working with Ethereum.
Basic knowledge of JavaScript and NodeJS would be good to have since interaction with Ethereum happens mostly through JavaScript. Support for other languages is also explained.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.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.packtpub.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 version of:
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 athttps://github.com/PacktPublishing/Ethereum-Cookbook. In case 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 athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: http://www.packtpub.com/sites/default/files/downloads/EthereumCookbook_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please 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.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering 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 packtpub.com.
In this chapter, we will cover the following recipes:
Choosing a client for Ethereum
Setting up a node and participating in a network
Working with the JavaScript console
Saving time and money with INFURA
Creating your own private Ethereum network
Creating a blockchain network for development
Using Azure Ethereum as a service
Using MetaMask and other wallets
Using block explorer
Understanding everything about accounts
Installing a solidity compiler
It is really important to understand how to configure and work with various implementations of the Ethereum protocol before developing applications in it. There are several flavors, which can be used interchangeably for development, testing, and deployment. Keywords in Ethereum might be very new to a person who is just getting started, so it is important to understand and use the tools and services in the Ethereum ecosystem.
Ethereum is a distributed public ledger, like Bitcoin. Bitcoin acts more like a peer-to-peer electronic cash system, whereas Ethereum is a decentralized platform for building applications. Ethereum has a built-in Turing complete programming language (solidity), which can be used to write smart contracts. This means that Ethereum has a broader application than other traditional blockchains. Ethereum also has a cryptocurrency (Ether), which can be traded for value or to pay the transaction fee for applications and services in Ethereum.
A smart contract is a computer program that outlines the rules in a relationship. Smart contracts work exactly as intended and cannot be changed at a later point in time. Once deployed, these smart contracts cannot be changed. This gives users trust and transparency. With the help of Ethereum smart contracts, you can create your own tradable tokens, raise funds for your startup, build a decentralized organization, or even make a fun game.
The recipes in this chapter will primarily focus on Ethereum configuration and platform tools, which will help the reader understand more about the Ethereum ecosystem before starting to develop applications.
In this recipe, we will focus on installing various clients that implement the Ethereum protocol. This will help you learn what each client has to offer, and will enable you to choose and work with an efficient implementation based on your requirements.
If you are using macOS, you will need homebrew to install the packages.
There are several clients that implement the Ethereum protocol and we will mainly focus on geth and parity. You can get more information about the remaining protocols from the official Ethereum documentation (http://www.ethdocs.org/).
Geth is the official Go implementation of Ethereum:
To install
geth
on macOS, the easiest way to follow is using
homebrew
. Run the following commands in your Terminal to download and install
geth
:
brew tap ethereum/ethereum brew install ethereum
This command will install the latest stable version of geth on your Mac. If you want to install the development version of geth, then add the --devel flag to the install command:
brew install ethereum --devel
To install
geth
on Ubuntu, run the following commands:
sudo apt-get install software-properties-commonsudo add-apt-repository -y ppa:ethereum/ethereumsudo apt-get updatesudo apt-get install ethereum
If you are using Windows, it is suggested to download the binary from
https://geth.ethereum.org/downloads/
and install it by double-clicking the
geth.exe
file.
Verify the installation by running the
geth
command:
geth version
It will show the current client details, as displayed here:
Parity is an Ethereum client that is built by Parity Technologies. It is a rust-based implementation and offers some additional functionalities over Go Ethereum:
The easiest way to install
parity
on Mac or Ubuntu is to use the one-line binary installer. This will handle all the hassle of downloading and installing the package:
bash <
(
curl https://get.parity.io
-kL
)
If you are using Windows, then download the binary releases from
https://github.com/paritytech/parity/releases
and install them. You can also see supported binaries for other operating systems as well.
You can build and run the client directly from its source code. To build geth from the source in Ubuntu, follow the steps given later. Make sure you have Go and the C compilers installed:
git clone https://github.com/ethereum/go-ethereum
cd go-ethereum
make geth
Here, you will learn how to set up a node using the geth command-line tool. You will also see how to connect to a public network and perform operations such as ledger syncing and mining.
You will need a working installation of the geth command-line interface. You can also start a node with parity or any other Ethereum protocol implementation, but the steps may differ for each client.
Commands starting with $ have to be run on the command prompt/terminal and those starting with > will work only on the web3 JavaScript console.
Verify your installation by running the following version command:
$ geth version
Start your node with the following command:
$ geth
This will start an Ethereum node and will connect with the main network. As soon as it finds any peer nodes, it will start downloading the blocks from them.
You can configure the parameters before starting a node. This will help you do things like connect to a different network, expose APIs, and much more. Let's look at a sample initialization and the parameters used in it:
$ geth --networkid 3 --datadir "./ropsten-db" --keystore "./ropsten-keys" --syncmode "fast" --rpc --rpcport "8546" --rpcapi "web3,eth,miner,admin" --rpccorsdomain "*" --port 30301 console
Let's look into each parameter in detail:
--networkid <id>
: A parameter to identify each network. You can either connect to the main/test network (1=Frontier(default), 2=Morden (disused), 3=Ropsten(PoW), 4=Rinkeby(PoA)) or any private network that you have set up.
--datadir <path>
: Directory path for storing the blockchain database and keystore. You can change the default
keystore
directory with the
--keystore
parameter.
--syncmode <mode>
: A parameter to specify the type of
sync
method. You can choose fast, full, or light, based on your needs.
--rpc
: Enables an RPC server through HTTP. You can also change parameters such as
--rpcaddr
,
--rpcport
, and
--rpcapi
.
--rpccorsdomain <list>
: Domains from which cross-domain requests are accepted. Use
*
as a wildcard or specify domains as a comma-separated list.
--port <port>
: Changes the default network listening port (
30303
).
--console
: Starts the
web3
JavaScript console.
It might take a few minutes to identify the peers that are already on the network. Run the following command to return the list of peers that are currently connected to your node. Your node will start syncing once it finds at least one peer:
> admin.peers
Check the current syncing status by running the following command. It will return false if not syncing:
>
eth.syncing
Run the
geth attach
command if you would like to connect to this node from a different console. You can also explicitly specify the host and the port. In our case, it is
localhost
and
8546
:
$ geth attach http://localhost:8546
The geth command-line utility has an inbuilt JavaScript Runtime Environment (JSRE). This JavaScript console exposes all web3js objects and methods. You can use this JSRE as a REPL (Read, Execute, Print, Loop) console.
In this recipe, we will learn how to connect and use the JSRE in interactive (console) and non-interactive (script) modes.
You should have the geth command-line tool installed on your system to test this recipe. You can either start a node along with the console or connect to an already existing node.
Start the Ethereum console with the
console
or
attach
subcommand. The console command starts the
geth
node and opens the JavaScript console along with it. The
attach
command is used to connect to an existing node. Here, we will connect to an already running node that you started earlier:
$ geth attach http://localhost:8545
If you are starting a new node and would like to see the log information, start the node with this:
$ geth --verbosity 5 console 2>> /tmp/eth-node.log
Too many logs can pollute your console. To avoid this, start the node with a specific verbosity value:
$ geth --verbosity 0 console
Take a look at the
web3
object, which is available for you to interact with:
> web3
For managing the node, you can make use of the
admin
API. For the list of supported admin operations, run the following command:
> admin
You can check the current node information with this:
> admin.nodeInfo
This will return an object with properties such as enode, protocols, ports, name, and other details related to the current node, as displayed here:
To see the list of peers connected to the current node, use the peers object:
> admin.peers
You also have access to methods that can help you enable or disable RPC/WS.
For handling Ethereum blockchain-related tasks, use the
eth
object. Run the following command to see the methods supported by it:
> eth
You can check the latest block number (block height) with this:
> eth.blockNumber
You have an option to read the contents of a block. You can pass any block number as a parameter:
> eth.getBlock(301)
In the following screenshot, you can see the block number, difficulty, gas details, miner, hash, transactions, and much more:
eth also has methods related to accounts, transactions, and contracts. We will talk more about those later in this book.
To manage Ethereum accounts, you can make use of the
personal
method. It has options for creating an account, unlocking the account, sending/signing a transaction, and so on:
> personal
You can play around with mining and its methods through the console:
> miner
This console also has an option to monitor the transaction pool through the
txpool
object:
> txpool
web3
also offers some generic methods to help you with the interaction. Some of the examples include conversion of values, encoding, and hashing. One such example to convert
ether
to
Wei
is given here:
> web3.toWei(1, "ether")
You can also execute JavaScript commands in a non-interactive way. There are two different approaches to doing this:
Use the
--exec
argument, which takes JavaScript as input. This will work with both the
console
and
attach
commands:
$ geth --exec "eth.accounts" attach http://localhost:8545
This will print the list of accounts stored in the current node.
You can execute more complex scripts with the
loadScript
method. The path to your scripts folder can be specified with the
--jspath
attribute:
$ geth --jspath "/home" --exec 'loadScript("sendTransaction.js")' attach http://localhost:8545
If you don't want to set up a full node for you decentralized application, then this is the recipe for you. INFURA provides an infrastructure for Ethereum and you can make use of it for free.
Go to the INFURA signup page (
https://infura.io/signup
) and enter
your
name and email.
Once you acknowledge the terms and conditions and have signed up, you will receive an email from INFURA with the providers for each network.
For each network, you will receive an endpoint and an API key:
Main Ethereum network
:
https://mainnet.infura.io/<api-key>
Test Ethereum network (Ropsten)
:
https://ropsten.infura.io/<api-key>
Test Ethereum network (Rinkeby)
:
https://rinkeby.infura.io/<api-key>
Test Ethereum network (INFURAnet)
:
https://infuranet.infura.io/<api-key>
You can interact with the providers just like you do with your local node. You can use JSON RPC, Web3JS, or even the REST API provided by INFURA to interact with the nodes.
Get the current block number with JSON RPC using cURL:
curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}' "https://mainnet.infura.io/<your-api-key>"
This will return the current block number, as follows:
{"jsonrpc":"2.0","id":1,"result":"0x512bab"}
INFURA also provides an easy-to-use REST API interface for JSON RPC commands. You can use the JSON RPC methods as the path to get the result:
https://api.infura.io/v1/jsonrpc/mainnet/eth_blockNumber?token=<your-api-key>
To use INFURA with your
web3js
application, you can set the endpoints as HTTP providers:
web3
new
Web3
(
new
Web3.providers.HttpProvider
(
"https://mainnet.infura.io/<your_api_key>
"
));
INFURA also provides support for IPFS and you can use their server as a gateway:
IPFS Gateway
:
https://ipfs.infura.io
IPFS RPC
:
https://ipfs.infura.io:5001
This recipe helps you create your own private POW-based Ethereum blockchain. Here, we will be creating an entirely new custom blockchain that cannot interact with the Ethereum main-net. You will have the flexibility to control parameters such as mining and peers. This will come in handy when you want to have a consortium of your own or even for testing purposes.
To step through this recipe, you will need a working installation of the geth command-line interface. No other prerequisites are required.
In steps 1 through 5, we created a private Ethereum network. This should be enough for you to run a single-node network. With the minimum difficulty and maximum gas limit, this network is ideal for development and testing. At this point, your application can connect to the network with the default Ethereum port, 8545.
In steps 6 to 9, we are creating another peer and connecting it to the first node. This allows you to have a multi-node Ethereum network. All the blocks will be synced between these two nodes and will be accessible from both nodes. You can create and connect as many nodes as you want with the procedure explained here. Make sure to set appropriate firewall rules to ensure proper communication.
puppeth is a command-line tool that comes with geth. It can help you create a new Ethereum network, down to the genesis block, bootnodes, miners, and ethstats servers, in a user-friendly way. Start puppeth using the following command:
$ puppeth
You will be asked to enter a network name. You can either enter a new network name or use the one that you already created using puppeth. Once you enter it, you can see the list of things that puppeth can do.
Create a new genesis file using puppeth and use Proof of Authority (clique) as the consensus algorithm. Try creating a private network with the generated genesis file.
This recipe explains how you can create a private network using geth. There are other options for various use cases, such as development and production. You can check out the following recipes to learn more:
Creating a blockchain network for development
Using Azure Ethereum as a service
You don't always have to create a fully functioning node to support your development. There are development networks that can simulate an Ethereum network. In this recipe, you will learn about ganache-cli (previously TestRPC), which is part of the Truffle suit of Ethereum development tools and is a command-line tool that you can use to create your personal blockchain network for Ethereum development.
Since the tool is written in JavaScript and distributed via npm, you will need Node.js(>= v6.11.5) installed on your machine to try this recipe.
Follow these steps to install and create a test Ethereum network using npm:
Install
ganache-cli
using
npm
:
npm install -g ganache-cli
Starting a basic blockchain network is as simple as running this command:
ganache-cli
You will know that your blockchain is ready when you see this screen:
Ganache creates a virtual Ethereum blockchain, and it generates some sample accounts for you to use during development. Each account is filled in 100 Ether so that you only have to focus on development. You can access the network from http://localhost:8545.
You can use a few parameters to customize the blockchain. Here's one such example:
ganache-cli -a 5 -e 2000 -p 8080 -l 999999
-a
: Number of accounts to generate while starting the network. The default is
10
.
-e
: Amount of Ether to allocate for each account. The default is
100
Ether.
-p
: Port number for listening to RPC requests. The default is
8,545
.
-l
: Gas limit for each block. The default is
90,000
.
You can find the complete list of parameters to configure here:
https://github.com/trufflesuite/ganache-cli.
There is a GUI for ganache that offers an easy-to-use interface for creating Ethereum networks. It even offers an intuitive User Interface (UI) for browsing blocks and transactions.
You can download and install the ganache GUI from http://truffleframework.com/ganache/.
Azure offers cloud solutions to deploy and configure Ethereum consortiums with a simple single-click deployment through the Azure portal. In this recipe, you will learn how to deploy a flexible Ethereum network, consisting of a set of load-balanced transaction nodes, with which an application or user can interact to submit transactions, and a set of mining nodes to record transactions.
You will need an Azure subscription to create an Ethereum consortium. Other dependencies will be configured by the provider itself.
Follow these steps to create an Ethereum POW blockchain in Azure:
Log in to the Azure portal and
click
on
Create a resource
from the left navigation bar.
Select
Create Ethereum Proof-of-Work Consortium
under
Blockchain
.
Once you click Create, you can see a five-step wizard that will guide you through the setup process. The first step will ask you to choose a username, password, subscription, location, and so on. Provide the appropriate values and click OK:
Step 2 will ask you to configure the regions in which the nodes should be deployed. For a simple network, one region should be enough.
Step 3 is all about configuring the number of nodes that should be dedicated to mining and transactions. Mining nodes do all the heavy lifting of creating blocks, and transaction nodes take care of broadcasting the transaction from your application. Choose the number of nodes for each category and their respective configuration to meet your needs.
Step 4 focuses more on the parameters of blockchain that you are about to create. You can compare it with the genesis file you will create during private network configuration.
Once you are finished on the Ethereum settings tab, you can choose the
Operations Management Suite
