Ethereum Cookbook

3 (1 reviews total)
By Manoj P R
    What do you get with a Packt Subscription?

  • Instant access to this title and 7,500+ eBooks & Videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Free Chapter
    Getting Started
About this book

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.

Publication date:
August 2018


Getting Started

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.

POW (Proof of Work), POS (Proof of Stake), IBFT (Istanbul Byzantine Fault Tolerance), Raft, and so on are different commonly used consensus algorithms. These algorithms are used to achieve agreement on a data value among distributed systems. Each algorithm has their own advantages and disadvantages, and various blockchain platforms use them based on their requirements.

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.

While the recipes in this chapter will give you an overview of Ethereum and working with various clients, we encourage you to adopt this proposal according to your needs. Since the software used is still in development and gaining in popularity, some organization's policies and antivirus software will prevent you from using this. In such cases, it is typically a good idea to discuss this with your IT security department—if your company happens to have one—well in advance, to prevent lengthy discussions later on.

Choosing a client for Ethereum

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.

Getting ready

If you are using macOS, you will need homebrew to install the packages.

How to do it...

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 (


Geth is the official Go implementation of Ethereum:

  1. 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
  1. To install geth on Ubuntu, run the following commands:
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
  1. If you are using Windows, it is suggested to download the binary from and install it by double-clicking the geth.exe file.
  2. Verify the installation by running the geth command:
geth version

It will show the current client details, as displayed here:

Since geth is a development version and still gaining in popularity, some antivirus software may consider it a virus. Also, make sure that you are not violating your organization's policies by using this software.


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:

  1. 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 -kL)
  1. If you are using Windows, then download the binary releases from and install them. You can also see supported binaries for other operating systems as well.

There's more...

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
cd go-ethereum
make geth

Setting up a node and participating in a network

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.

Getting ready

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.

How to do it...

  1. Verify your installation by running the following version command:
$ geth version
  1. 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.
If you get stuck anywhere, you can always make use of the inbuilt help interface. Just enter geth help and it will return a comprehensive list of all commands with their respective description that you can run using geth.
  1. 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
  1. Check the current syncing status by running the following command. It will return false if not syncing:
> eth.syncing
  1. 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
Your firewall may restrict the node from communicating with an external peer. This can cause issues with the synchronization process. Also, ensure that you are not exposing your RPC APIs to the internet, which can result in attacks.

Working with the JavaScript console

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.

Getting ready

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.

How to do it...

  1. 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
  1. 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
  1. Take a look at the web3 object, which is available for you to interact with:
> web3
  1. 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.

  1. 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.

  1. 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
  1. You can play around with mining and its methods through the console:
> miner
  1. This console also has an option to monitor the transaction pool through the txpool object:
> txpool
  1. 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")
Since it is a JavaScript console, you have complete ECMA5 functionality (Go Ethereum uses Otto JS VM, which is a JS interpreter written in Go). You can declare variables, use control structures, define new methods, and even use any of setInterval, clearInterval, setTimeout, and clearTimeout.

There's more...

You can also execute JavaScript commands in a non-interactive way. There are two different approaches to doing this:

  1. 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.

  1. 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

Saving time and money with INFURA

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.

How to do it...

  1. Go to the INFURA signup page ( and enter your name and email.
  2. Once you acknowledge the terms and conditions and have signed up, you will receive an email from INFURA with the providers for each network.
  3. For each network, you will receive an endpoint and an API key:
    • Main Ethereum network:<api-key>
    • Test Ethereum network (Ropsten):<api-key>
    • Test Ethereum network (Rinkeby):<api-key>
    • Test Ethereum network (INFURAnet):<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.

  1. 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": []}' "<your-api-key>"

This will return the current block number, as follows:

  1. 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:<your-api-key>

  1. To use INFURA with your web3js application, you can set the endpoints as HTTP providers:
web3 = new Web3(new Web3.providers.HttpProvider ("<your_api_key>"));

There's more...

INFURA also provides support for IPFS and you can use their server as a gateway:


Creating your own private Ethereum network

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.

Getting ready

To step through this recipe, you will need a working installation of the geth command-line interface. No other prerequisites are required.

How to do it...

  1. Create a directory to save your blockchain data:
$ mkdir datadir
  1. Create an account and save it to the directory:
$ geth account new --datadir datadir

You will be asked to enter a password for the account. An address will be displayed once the account is created. The key file for this account will be stored in the /datadir/keystore/ location.

  1. Create a genesis.json file with the following contents:
"config": {
"chainId": 1100,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0
"difficulty": "400",
"gasLimit": "2000000",
"alloc": {
"87db8fceb028cd4ded9d03f49b89124a1589cab0": {
"balance": "100000000000000000000000"

Various parameters in the genesis files are explained here. You can make changes as per your requirements:

  • config: The config object defines the settings for our custom blockchain. chainId is used to identify our network. Set it to a unique value for our private network. Other parameters are related to forking and versioning. Let’s not worry about them, since we are starting a network from scratch.
  • difficulty: This value is used to control the block generation time of a blockchain. The higher the difficulty, the longer it will take to mine each block. In a test network, try to keep it low to avoid long waiting times.
  • gasLimit: This value denotes the total amount of gas that can be used in each block. We will keep it high enough to avoid any bottlenecks during testing.
  • alloc: This object allows us to pre-fill accounts with Ether. This won’t create accounts for you. Since we already have an account created in step 2, use it here to allocate some wei (1 Ether = 1018 wei).
  1. Initialize your genesis file using the following command:
$ geth --datadir ./datadir init ./genesis.json
  1. Start your network:
$ geth --datadir ./datadir --networkid 1100 console 2>> network.log

Running this command will display a console like this in your terminal/command prompt:

You can use this console to interact with your private blockchain. To give you a brief idea, execute the following command to see the list of accounts:

> eth.accounts
  1. If you would like to add another peer to the network, open a second terminal/command prompt to create a second peer with a different data directory and port:
$ geth --datadir ./datadir2 init ./genesis.json
$ geth --datadir ./datadir2 --networkid 1100 --port 30302 console 2>> network.log
  1. Find out the enode address of the first node using the first JavaScript console:
> admin.nodeInfo.enode

This will return the enode address of the current node:

  1. Use the second node’s JavaScript console to connect with the first node:
> admin.addPeer( “enode://315d8f023dfa1ae1b59dc11462f3e13697fc8fe4886034e01530ebe36b2f8cc154a8dd9c21f5b42564668f22ae7173943b9dd9a0fbfc1430cca8c47196872914@”)

We replaced [::] with the IP address and port of the first node.

  1. Verify the connection from both nodes by listing the connected peers:
> admin.peers

How it works...

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.

There's more...

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.

See also

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


Creating a blockchain network for development

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.

Getting ready

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.

How to do it...

Follow these steps to install and create a test Ethereum network using npm:

  1. Install ganache-cli using npm:
npm install -g ganache-cli
  1. Starting a basic blockchain network is as simple as running this command:

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.

  1. 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:

By default, accounts are unlocked and you can do the transaction from any account without a password. You can change this by using the --secure or -n flag. This will lock all accounts by default and you need to unlock each one to send a transaction.

There's more...

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


Using Azure Ethereum as a service

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.

Getting ready

You will need an Azure subscription to create an Ethereum consortium. Other dependencies will be configured by the provider itself.

How to do it...

Follow these steps to create an Ethereum POW blockchain in Azure:

  1. Log in to the Azure portal and click on Create a resource from the left navigation bar.
  1. 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:

  1. 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.
  2. 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.
  3. 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.
  1. Once you are finished on the Ethereum settings tab, you can choose the Operations Management Suite for your Azure resource. Create a new one if you are new to Azure and creating resources for the first time.
  2. If everything goes well, then the verification process in the Summary tab will be successful and you can proceed to purchase the service.
  3. Read through the Terms and Conditions and click Create. This will start deploying your resources and can take a few minutes to finish.
  4. Once the deployment is finished, you can see your resources in the resource group that you created/selected. Select your resource group from the Resource groups tab in the left navigation bar and Deployments.
  5. This will display the set of deployments that has been created as part of Ethereum consortium's deployment. Select the deployment name that starts with microsoft-azure-blockchain-ethereum:
  1. Select output from the window, and now you can see the access credentials for the resources that you created:

These are some of the credentials you can use in the Azure blockchain service:

  • ADMIN-SITE: Admin portal that you can use to view the current node status and send Ether to newly created accounts
  • OMS-PORTAL-URL: Azure Operations Management Portal for your resources
  • ETHEREUM-RPC-ENDPOINT: Ethereum RPC port for you to interact with the blockchain you created
  • SSH-TO-FIRST-TX-NODE-REGION1: Credentials for connecting to a transaction node that is in the first region

How it works...

Steps 1 to 9 guide you through the process of creating a private Ethereum consortium using services offered by Azure. This will create and deploy multiple peers across various regions behind a load balancer for you to interact with. Steps 10 to 12 describe the process of using these services. This helps you understand various services and where to use them.


Using MetaMask and other wallets

You will need a wallet to send and receive the cryptocurrency used in Ethereum. In this recipe, you will learn to install and use MetaMask or another wallet, which can be used for managing accounts and transactions.

Getting ready

MetaMask is a browser-based wallet and it currently works with both Chrome and Firefox. Other wallets are either browser-based or need additional downloads.

How to do it...

MetaMask, Mist, and MyCrypto are some of the popular wallets in the Ethereum ecosystem. Let's look into these options in detail.


  1. Install MetaMask for Chrome or Firefox from the respective app store.
  2. Select MetaMask from the extensions tab and Accept both Privacy and Terms and Conditions after carefully reading them. Then, you will be asked to create a password to encrypt your wallet storage:
  1. MetaMask will generate a random 12-word mnemonic that you can use to restore your account at a later point in time. Save it somewhere safe and secret as this is the only way to regain access to your account:
  1. Your account has now been successfully created. You can now use MetaMask with all supported websites for signing transactions:
  1. You can connect to various Ethereum networks using MetaMask. This includes connecting to the main-net, test nets, or any other RPC ports you have access to. This can be configured from the network selector drop-down in the top-left corner.
  2. You also have the option to add additional accounts or to export the private key of the current account. These options let you configure MetaMask as per your requirements.


  1. Using MyCrypto is as simple as navigating to It offers an intuitive UI to interact with Ethereum:

  1. Either use an existing wallet or create a new one. The web interface of MyCrypto has limited support for creating/using wallets through PrivateKey, Mnemonic, or keyfile. This restriction is enabled to use a strong password while creating your wallet. Once your wallet is created, you can export your private key and KeyFile. Save it in a secure place and do not lose it. It cannot be recovered!
  2. To use MyCrypto, you can import the private Key/KeyFile you created in step 2 or use external wallets such as MetaMask/Mist/Hardware.
  3. MyCrypto also has options to deploy and interact with contracts, use Ethereum name service, or even swap your Ether for other cryptos.

Ethereum wallet–Mist

  1. Download and install the Mist or Ethereum wallet from Mist is a browser for decentralized web apps. The Ethereum wallet is a Mist implementation that can only access a single Decentralized Application (DApp), which is the wallet DApp.
  2. You can select the network from Network under the Develop menu of Mist. You can choose between the main network, test networks, or your own private network.

Using the Ethereum wallet DApp, you can send/receive transactions and deploy/interact with smart contracts.

Never send your account credentials to anyone or use them with unknown websites. Make sure that you are using a trusted wallet or exchange while using cryptocurrencies. Typos in addresses can make you lose your funds. Double-check the address before making any transactions.

Using block explorer

There are many ways to read data from a transaction or a block in Ethereum. Etherscan is one block explorer and analytics platform for Ethereum. In this recipe, you will learn about the platform and how you can make use of it.

How to do it...

  1. Go to to access the block explorer. You will see a dashboard that displays the network state:
  1. On the top left, you can see a card that displays the current Ethereum market share along with the exchange rate. You can also see a transaction history chart for the last 14 days.
  2. Search for a block number or select it from the recent blocks list to view the contents of the block. You can see details such as time, miner, hash, transactions, size, gas, and so on:
  1. By searching a transaction, you can view transaction details such as from address, to address, the value transferred, gas, and other details.
  2. Etherscan also offers a details page for both Externally Owned Addresses (EOA) and contract addresses. To see the balance, list of transactions, and even tokens owned by that address, navigate to the EOA details page.
  3. The contract page also shows the balance, transactions, and even a contract code if it is a verified contract. To interact with verified contracts through Etherscan, use this page.
  4. The platform also offers charts for analytics. Use the charts to get an idea about the currency, network, mining, blocks, transactions, and other general information.
  5. Click the MISC tab to use tools such as the mining calculator, bytecode converter, and transaction broadcaster.
  6. Etherscan also has a free to use API for reading data from Ethereum. Sign up to Etherscan to use the API and use the free API key that can be generated from the portal itself. Make sure that you are not making more than five requests per second. You will be blocked if this is exceeded.
  1. Signing up with Etherscan will allow you to watch specific addresses and create email alerts. You can even add a private note for each transaction.

There's more...

Eth-netstats is a visual interface for tracking an Ethereum network status. To access the public status page, go to Note that the portal does not represent the entire state of the Ethereum main net. This is because of the voluntary listing of nodes in the portal.

You can use netstats to visualize your private Ethereum network:

  1. Download the source code from the repository. Make sure to verify the license:
git clone
  1. Install the dependencies:
sudo npm install -g grunt-cli
cd eth-netstats
npm install
  1. Build the project using grunt and use npm to run it:
npm start

Understanding everything about accounts

Ethereum accounts are made up of 20-byte addresses, and you can exchange data and values between two accounts with state transitions. In general, there are two types of account in Ethereum: EOA and contract accounts. Depending on the type of account, there are four fields associated with each account: balance, contract code, storage, and nonce.

EOAs are controlled by a private key, and contract accounts are controlled by the contract code. A normal user can create an EOA by using a wallet such as MetaMask or MyCrypto. As a developer, you need to know more about these accounts and other ways to create them. In this recipe, you will learn how to create and maintain EOAs in Ethereum.

Getting ready

You will need a working installation of geth in your system to run web3 commands. Other prerequisites, if any, are listed along with each command.

How to do it...

  1. Create an account using the account command in the geth command-line tool. This will create an Ethereum account for you and will return the EOA address:
$ geth account new

If you are using the JavaScript console or Web3JS, use the following command to create an account:

> web3.personal.newAccount("<password>")
  1. Before you do any transaction from this account, unlock it using the password. Use the third parameter to control the duration of unlocking. To lock the account after the transaction, use the lockAccount function:
> personal.unlockAccount("<address>", "<password>")
> personal.lockAccount("<your_address>")
  1. Creating an account using this method also creates an encrypted KeyFile. The file is located in your key store with the format UTC--{year}-{month}--{account}. The contents of the file also includes an encrypted version of your private key:
"kdfparams {
  1. You can also create a private key externally and import it into other wallets. Ethereum follows the elliptical curve for private keys. You can either create one with OpenSSL or with wallets such as MyCrypto. Once a private key is created, you can import it using the following command. Make sure to give it a strong password to encrypt it:
$ geth account import <path to PrivateKey file>

You can also import the private key using the JavaScript console:

> web3.personal.importRawKey("<private key>", "<password>")
Please do not share your private keys with any website, business, or individual. You may need to provide your private keys to MetaMask and other similar wallets, which exist to manage accounts, in order to use them. Do this with caution and ensure that you can trust them.
  1. If you want to find the address from the private key, a series of steps have to be followed. Convert the private key to a 64-byte-long public key. Then, take the Keccak-256 hash of the public key, and the last 20 bytes will be the Ethereum address for that private key.
  2. You can also create an account securely by using the mnemonic phrase. This mnemonic is a 12-word phrase that can be used as a seed to create EOAs. This is easy to store and wallets such as MetaMask follow this pattern.

There's more...

If you need a safe and secure way to store your private key or account, then the recommended way is to use a hardware wallet. The only way someone can use the account is by physically interacting with the wallet. This reduces the potential security threat if someone gets into your system maliciously.


Installing a solidity compiler

You have multiple options when it comes to compiling smart contracts written in solidity. In this recipe, you will learn about installing a solidity compiler and using it to compile your smart contract.

Getting ready

If you are using macOS, you will need homebrew to install the binary compiler. There are other options, such as using npm or docker, which require Node.js and Docker, respectively, installed on your machine.

How to do it...

  1. If you are in Ubuntu, use ppa to install the compiler by running the following command:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
  1. If you are using macOS, install the compiler using brew:
brew update
brew tap ethereum/ethereum
brew install solidity
  1. Verify the installation with the following command:
solc --version
  1. Use this command to compile a contract and print the binary:
solc --bin SampleContract.sol
  1. You want to get some of the more advanced output from solc:
solc -o outDirectory --bin --ast --asm --abi --opcodes SampleContract.sol

We can configure it using these provided flags:

  • --ast: Abstracts the syntax trees of source files
  • --asm: EVM assembly of the contracts
  • --abi: ABI specification of the contracts
  • --opcodes: Opcodes of the contracts

You can get the complete list of operations supported by the solc compiler by running solc --help.

There's more...

There is also a JavaScript-based solidity compiler available for you to use. You can install SolcJS using npm. The solc-js project is derived from the C++ solc project and can be used in JavaScript projects directly:

npm install -g solc

To see all the supported features, run the following command:

solcjs --help
About the Author
  • Manoj P R

    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.

    Browse publications by this author
Latest Reviews (1 reviews total)
Good composition of content.
Ethereum Cookbook
Unlock this book and the full library FREE for 7 days
Start now