Note

If you are new to the blockchain technology, taking our Introduction to Blockchain Technology self-paced course is highly recommended. Also, for a comprehensive coverage of blockchain development in Ethereum or mastering Solidity programming, taking our below self paced courses is highly recommended:

Recap

In our previous series,

 

In this article series, we will move our focus to Ethereum private chains. For developers, private blockchains are set up for testing purposes. Private chains have advantages over public blockchains in testing. For example, there is no need

Note

If you are new to the blockchain technology, taking our Introduction to Blockchain Technology self-paced course is highly recommended. Also, for a comprehensive coverage of blockchain development in Ethereum or mastering Solidity programming, taking our below self paced courses is highly recommended:

Recap

In our previous article (How to Handle Ethereum Messages with Whisper), we discussed how to process Ethereum messages with Whisper.

In this article, we survey the most popular libraries for Ethereum smart contract development

Popular smart contract libraries

As we have learned so far, developing a secure, reusable, and efficient smart contract is not an easy task. It takes a lot of effort, experience, and testing. Once a smart contract has been deployed to a blockchain, anyone in the blockchain can access it. So, developing a top, secure, and quality smart contract becomes a crucial task for any smart contract developer. Well-tested, reusable, and secured libraries become very important. There are many popular open source Ethereum libraries available, as follows:

  • Modular Libraries: A library that’s used for utilizing EVMs
  • Aragon: A DAO protocol, including the aragonOS smart contract framework for upgradeability and governance
  • DateTime Library: A Solidity date and time library

OpenZeppelin is one of the most popular libraries, and we’ll discuss it in the next section. It provides many handy tokens and utility libraries.

 

Working with OpenZeppelin

OpenZeppelin is an open source framework for Solidity smart contracts. It is one of the most widely used Solidity libraries that provide reusable, secure, and modular smart contract code. All of this smart contract code is fully tested to follow the best practice security patterns. The framework is maintained by the Zeppelin company.

OpenZeppelin libraries provide many useful smart contracts, including access, crowdsale, cryptography, introspection, life cycle, math, ownership, payment, token, and utils. The following table shows all of the library project structures:

OpenZeppelin libraries Description
access Provides role-based access control.
crowdsale Provides token-based crowdsale contract libraries.
Cryptography Provides different cryptographic primitives libraries.
Introspection Provides a set of local and global interfaces.
Draft The contract is currently in testing status by OpenZeppelin.
Lifecycle Provides life cycle management for the contract, and supports pausing and unpausing smart contracts via the pauserRole user.
math Provides math-related utilities.
ownership Provides simple authorization and access control mechanisms.
payment Provides payment-related utilities.
token Provides the most popular ERC token utilities.
utils Provides miscellaneous smart contract utility functions.

Let’s explore some OpenZeppelin libraries to understand how we can use these utilities.

Setting up a dev environment

To understand more about OpenZeppelin, let’s set up a Truffle project and run a simple example to get started:

  • Set up a Truffle project, create a project folder, and navigate to the project root folder. Then, issue the following Truffle command:
npm install truffle npx truffle init
  • Install the OpenZeppelin library and, under the project root folder, run the following npm command:
npm install  openzeppelin-solidity

This should install the OpenZeppelin library under the node_modules directory. A Truffle project can read all of these Solidity classes by using an import-related class.

Access control

In Solidity smart contracts, role-based access control is used to restrict unauthorized users from accessing certain functions. With defined access control policies, the smart contract can build the security rule around roles and privileges.
To use the OpenZeppelin Roles function, you need to import Roles.sol from the OpenZeppelin access folder. Then, you have to define the roles you want to use. In our example, we define an admin and minter role. Here is an example of how we can create an admin role and a minter role:

pragma solidity >=0.4.22 <0.6.0;
  import  "openzeppelin-solidity/contracts/access/Roles.sol";  contract AclRole  {
  using Roles for Roles.Role; Roles.Role private admins; Roles.Role private  minters;
  function onlyAdminRole() view public {
  //only admin can use this function
  require(admins.has(msg.sender), "You must be admin");
  }
  function onlyMintersRole() view public {
  //only minters can  use this function require(minters.has(msg.sender), "You must be minter");
  }
  function anyone() public  {
  //anyone can use this function
  }
  }

In the preceding example, we created two role functions:

  • OnlyAdminRole(): Allows the admin role to access and perform functions
  • OnlyMinterRole(): Only allows the minter role to access and perform functions

Next, let’s take a look at math functions.

Math

OpenZeppelin libraries provide that SafeMath contract, which has the add, sub, mul, div, and mod methods so that developers can perform safe math operations. Here is the list of functions:

  • add(uint256 a, uint256 b)
  • sub(uint256 a, uint256 b)
  • mul(uint256 a, uint256 b)
  • div(uint256 a, uint256 b)
  •  mod(uint256 a, uint256 b)

The add function is equivalent to Solidity’s + operator. For example, we can add certain balance values:

balances[msg.sender] = balances[msg.sender].add(_value);

The sub function is equivalent to Solidity’s – operator. For example, we can subtract certain balance values:

balances[msg.sender] = balances[msg.sender].sub(_value);

The mul function is equivalent to Solidity’s * operator. For example, we can multiply a balance value by two:

balances[msg.sender] = balances[msg.sender].mul(2);

The div function is equivalent to Solidity’s / operator. For example, we can divide a balance value by 10:

balances[msg.sender] = balances[msg.sender].div(10);

The mod function is equivalent to Solidity’s % operator. For example, if we only charge a multiple of one ether (such as 1eth, 2eth, and so on), we can use the weiUnit mod. After the mod operation, we can find out how much of the remaining ether needs to be returned to the sender:

uint weiUnit = 1 * 10 ** 16;
uint returnAmt = msg.value.mod(weiUnit); uint payAmount = msg.value.sub(returnAmt);

 

Token

OpenZeppelin libraries provide a set of comprehensive token implementations for ERC20, ERC721, and ERC777. The following screenshot shows the ERC20 implemented by OpenZeppelin libraries. It makes token development much easier and safer:

 Ethereum blockchain development in Infura

 

Let’s review ERC20 token libraries.
An ERC20 token keeps track of user address and balance information. The IERC20 interface defines functions and events that all ERC20 tokens must implement:

  • ERC20: This provides basic implementation for IERC20.
  • ERC20Burable: This allows the token holder to burn a certain number of tokens.
  •  ERC20Mintable: This allows MonterRole to mint (create) a certain amount of new tokens when needed.
  • ERC20Capped: This adds caps for the token supply.
  • ERC20Detailed: This adds name, symbol, and decimal to the ERC20 token’s implementation.
  • ERC20Pausable: Users with pauseRole can pause and resume or freeze and resume the token transfer.
  • SafeERC20: This provides a wrapper around ERC20 token functions such as safeTransfer, safeTransferFrom, and safeApprove via the callOptionalReturn (IERC20 token and bytes memory data) function.
  • TokenTimeLock: This allows the token beneficiary to extract a certain amount of tokens after a specific release time.

Let’s utilize OpenZeppelin-developed token smart contract to implement our ERC20 token. We will use ERC20 for basic ERC20 implementation. ERC20Detailed is for token detail information such as symbol, name, and decimal.
Here is our SampleToken implementation. You can see how easy it is when we use the openzeppelin token libraries. Let’s take a look at the code implementation here:

import  "openzeppelin-solidity/contracts/ownership/Ownable.sol";  import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; 
  import  "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";  contract SampleToken is ERC20, ERC20Detailed, Ownable {
  uint256 public initialSupply       = 100000000000;
  constructor () public  ERC20Detailed("SampleToken",  "ST", 18) {
  _mint(msg.sender, initialSupply);
  }
  }

We can see that we just need to extend our smart contract from the openzeppelin ERC20 token implementation; you can immediately create your own token by doing this. It makes writing token smart contracts much more straightforward.

Utils

The OpenZeppelin util libraries provide address, arrays, and the ReentrancyGuard utility. Address has a function, isContract(address account), which will return true if the account is the contract. Arrays have a function, findUpperBound(uint256[] array, uint256 element), which is a sorted search array and returns the upperBound element (first index) that returns a value larger or equal to the element value. ReentrancyGuard prevents a reentrance call to a function.

 

Next Article
Now that we finished our forth article series, we move on to our next article series discussing how to create Ethereum private chains. Specifically, we cover the following 12 articles:

This article is written in collaboration with Brian Wu who is a leading author of “Learn Ethereum: Build your own decentralized applications with Ethereum and smart contracts” book. He has written 7 books on blockchain development.

Resources

Free Webinars on Blockchain

Here is the list of our free webinars that are highly recommended:

 

Free Courses

Here is the list of our 10 free self-paced courses that are highly recommended:

 

Self-Paced Blockchain Courses

If you like to learn more about Hyperledger Fabric, Hyperledger Sawtooth, Ethereum or Corda, taking the following self-paced classes is highly recommended:

  1. Intro to Blockchain Technology
  2. Blockchain Management in Hyperledger for System Admins
  3. Hyperledger Fabric for Developers
  4. Intro to Blockchain Cybersecurity
  5. Learn Solidity Programming by Examples
  6. Introduction to Ethereum Blockchain Development
  7. Learn Blockchain Dev with Corda R3
  8. Intro to Hyperledger Sawtooth for System Admins

 

Live Blockchain Courses

If you want to master Hyperledger Fabric, Ethereum or Corda, taking the following live classes is highly recommended:

 

Articles and Tutorials on Blockchain Technology

If you like to learn more about blockchain technology and how it works, reading the following articles is highly recommended:

 

Articles and Tutorials on Ethereum and Solidity

If you like to learn more about blockchain development in Ethereum with Solidity, reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on Hyperledger Family

If you like to learn more about blockchain development with Hyperledger, reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on R3 Corda

If you like to learn more about blockchain development on Corda , reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on Other Blockchain Platforms

If you like to learn more about blockchain development in other platforms, reading the following articles and tutorials is highly recommended:

for nodes syncing or obtaining test ether, as you are the only user, and there are no other smart contracts. But the disadvantage is that the testing won’t be as good as real scenarios in a public blockchain, in the absence of other nodes, users, and contracts.
As blockchain technology has matured, enterprises have started to adopt the technology for their own use cases. It’s important for you to understand not only the public blockchains but also the private and permissioned ones. Developers should know how to set up their own blockchains.

We will have a look at the difference between public and private blockchains, and take you through the steps for setting up a private blockchain using Ethereum. We will also look at the options flags that we can use with new chains. At the end of this article series, we will provide a brief overview of popular private blockchains, including R3 CordaHyperledger Sawtooth, and Quorum, and their usages in the industry. The series will also explain private blockchains in production usages.

We will cover the following topics in this series:

  • Understanding private and permissioned blockchains
  • Setting up a local private blockchain
  • Using optional flags with new chains
  • Introducing the popular private blockchains in the industry
  • Private blockchains in production usages

Technical requirements

To set up a local blockchain network, you will need one or more local computers connected through the local network. The steps demonstrated in this series have been implemented with a Mac machine. It will work almost the same on the Ubuntu server. You will also need to decide which Ethereum client to use. We will use Go-ethereum, the popular Ethereum client from the Ethereum foundation. If you choose a different Ethereum client implementation, follow the detailed instructions on its website, even if it appears to be very similar to Go-ethereum.
There are multiple options available for you to install Go-ethereum or Geth. The simplest way is to complete the following three steps:

  • Download Geth directly from the Geth site: https://geth.ethereum.org/downloads.
  • Extract the tar file and store the executable file in your local directory.
  • Add the directory to your system path.

 

If you intend to build Go-ethereum from source, the following applications will be required. For detailed instructions, you should check the geth site: https://geth.ethereum.org/install-and-build/Installing-Geth#build-it-from-source-code:

  • Git Xcode
  • Homebrew

If you plan to create any miner nodes, make sure you have enough RAM set aside for mining. Now that we understand the concept of private and permissioned blockchains, we will introduce how to create a local private blockchain without mining and then with mining.

Understanding a private and permissioned blockchain

So far, we have extensively discussed Bitcoin and Ethereum as public blockchains. With a public blockchain, anyone can become a node of the network and access all the activities inside it. The key challenges for enterprise adoption are privacy and confidentiality.

Enterprises need both of them for legitimate reasons:

  • One is that privacy will be enforced by laws and regulations. In Europe, the General Data Protection Regulation (GDPR) is the core of digital privacy legislation. In the US, HIPAA in healthcare and KYC/AML in finance require the business to protect consumer privacy. More importantly, privacy and security in general are competitive advantages for enterprises to gain the trust of and retain their customers.
  • The second reason is that all businesses and large enterprises deal with crucial product and services information, which make them competitive on the global market. For this reason, enterprises are more likely to join the private and consortium blockchains to avoid exposing sensitive data and transactions to the public.

A private blockchain is sometimes called a permissioned blockchain, similar to the way that a public blockchain is sometimes categorized as a permissionless blockchain. It can have all the key features we discussed in the public blockchain, including a decentralized peer-to-peer network, distributed ledger, and security through cryptography. The difference between the public and private blockchain lies in who can join the network, and what rights you can get. You can think of a public blockchain as a public park. Anyone can get into the public park. And once in, you can do all kinds of activities, such as jogging or playing, as long as the policies or rules allow them. Joining a private blockchain is like going to someone’s birthday party: you can only join if you’ve been invited.

In a public blockchain, anyone can join the network and access all transactions. Anyone can be the validator to verify the transactions and create the blocks, and the system relies on the economic perspectives (incentives in the Proof-of-Work(PoW) consensus mechanism, and the disincentives in the Proof-of-Stake(PoS) mechanism) to secure the network. On the contrary, in the private blockchain, only selected nodes can participate in the peer-to-peer network and process the transactions. The system relies on the identity of the entities, whether it is a user or a node, to secure the network.

The difference between permissionless and permissioned blockchain lies in the trust of validators. Permissionless blockchains allow everyone to validate transactions, but only selected users can do so in a permissioned blockchain. In other words, a permissioned blockchain doesn’t put its trust in validators.

To help you get a clear picture of the different categories of blockchains, we can summarize the features of blockchains in the following table:

blockchain Public permissionless Public permissioned Private permissionless Private permissioned
Read/create transactions Anyone Anyone Restricted Restricted
Validate/write transactions Anyone Restricted Anyone Restricted
Validator identity Highly Anonymous Moderate Anonymous Identified Identified
Trust in validators Yes No Yes No
 

Consensus

 

PoW

 

PoS
PoA (Goerli Testnet)

 

Federated Byzantine agreement

Practical Byzantine Fault Tolerance Algorithm
/Multisignature
Require Token Yes Yes No No
Speed Slower Faster Faster Faster
Energy consumption Higher Lower Lower Lower
 

Projects

Bitcoin Ethereum Waves Ethereum after Casper
Ripple
 

LTO Network MONET

Hyperledger Fabric
R3 Corda
Quorum

Also, as mainstream blockchain categories, blockchain networks are either permissioned or permissionless. The concept of it being private or public is application specific, and not at the network level. It is based on someone’s ability to access the network and also what identification requirements there are. Within those networks, transactions and interactions may be private or public. Whether or not you need privacy or confidentiality is depending on use case. For example, Quorum has tessera nodes for private transactions, Hyperledger has channels for private interactions, and E&Y has nightfall for public Ethereum.

Although Ethereum is launched as a public permissionless blockchain, you can build a local private blockchain with Ethereum too.

In the next article, we will walk you through how to set up a private Ethereum blockchain network.

 

Next Article

In our next article (How to Set up a Local Private Ethereum Blockchain), we discuss how to set up a local private Ethereum network.

This article is written in collaboration with Brian Wu who is a leading author of “Learn Ethereum: Build your own decentralized applications with Ethereum and smart contracts” book. He has written 7 books on blockchain development.

Resources

Free Webinars on Blockchain

Here is the list of our free webinars that are highly recommended:

 

Free Courses

Here is the list of our 10 free self-paced courses that are highly recommended:

 

Self-Paced Blockchain Courses

If you like to learn more about Hyperledger Fabric, Hyperledger Sawtooth, Ethereum or Corda, taking the following self-paced classes is highly recommended:

  1. Intro to Blockchain Technology
  2. Blockchain Management in Hyperledger for System Admins
  3. Hyperledger Fabric for Developers
  4. Intro to Blockchain Cybersecurity
  5. Learn Solidity Programming by Examples
  6. Introduction to Ethereum Blockchain Development
  7. Learn Blockchain Dev with Corda R3
  8. Intro to Hyperledger Sawtooth for System Admins

 

Live Blockchain Courses

If you want to master Hyperledger Fabric, Ethereum or Corda, taking the following live classes is highly recommended:

 

Articles and Tutorials on Blockchain Technology

If you like to learn more about blockchain technology and how it works, reading the following articles is highly recommended:

 

Articles and Tutorials on Ethereum and Solidity

If you like to learn more about blockchain development in Ethereum with Solidity, reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on Hyperledger Family

If you like to learn more about blockchain development with Hyperledger, reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on R3 Corda

If you like to learn more about blockchain development on Corda , reading the following articles and tutorials is highly recommended:

 

Articles and Tutorials on Other Blockchain Platforms

If you like to learn more about blockchain development in other platforms, reading the following articles and tutorials is highly recommended: