Keywords

1 Blockchain—The Future Is Here

How we should protect our data? Why blockchain is considered most secured way to store data? What is blockchain? How to deploy our own blockchain? These types of questions are always keeping our mind occupied. The chapter is all about to answer these queries along with the complete practical idea of how one can deploy a smart contract using Solidity in Ethereum.

Blockchain transactions occur in real-time, used for any application or any business

1.1 Background

Blockchain uses the concept of distributed ledger. Though block chain is still in budding stage but distributed ledger concept was introduced around the 1990s for the first time [1].

Blockchain technology was introduced for the first time in 1991 when two of the research scientists, named as Stuart Haber and W. Scott Stornetta, comes up with a computation phenomenon which assures that no one can temper the Digital Document, or changes to the document cannot be made. This was the cryptography-based secured chain of blocks [2].

In the year 2004, computer scientists introduced a system called as “RPOW,” which stands for Reusable Proof of Work. The was designed to accept hashcash-based proof of work (PoW) token and as a result, which produced RSA Signed token. This was transferred from person to person.

By the year 2008, bitcoin was introduced which was a new decentralized peer-to-peer Electronic Cash System. On Jan 3, 2009, Digital gold termed as bitcoin was born due to the mining performed by Satoshi Nakamoto (pseudoname) [3]. Satoshi Nakamoto introduced the concept of blockchain, which demolished the concept of centralization by focusing upon decentralized ledger, being maintained by anonymous consensus. The first vendors in terms of cryptocurrency implementation were bitcoin (record priced at $19,843.1094), ripple (represented by XRP symbol), and Litecoin (targeted number of tokens to be circulated is $84 million) [4]. Litecoin is said to be the little sister of bitcoin.

On August 2014, the bitcoin blockchain file which was keeping records of all transactions reached 20 GB. Later attention shifted toward blockchain by which hundreds of new cryptocurrencies were issued [5].

In the year 2015, a blockchain project named “Hyperledger” was funded after the Linux Foundation announced the creation of the Hyperledger project [6].

Blockchain 1.0 was transactions based, which included the deployment of cryptocurrency in those applications, which are related or operate on cash, which is furthermore seen into currency transfer and digital payment systems. Early vendors operated using blockchain 1.0 were OneName, Open Bazar, Streamium, and Factorn.

In 2018 the power of blockchain became evident and it was called blockchain2.0. It was contracts based which included financial markets and applications, which operates on blockchain beyond cash transaction. All the transaction on this version of blockchain was smart contract-based transaction [7]. The goal shifted from digital currency mining to applications, which can be used in any business. This started the use of blockchain-based solutions into health care, supply chain, and finance.

Why Blockchain?

Say, for an example, if all the records lie on a centralized computer, in the case of failure, no one will be able to access the records [8]. To ensure the availability of data at any point of time, we have to opt for distributed storage instead of keeping all the data at one single place.

The decentralization ensures the availability of data at any point of time, resulting into reducing the centralized databases dependency. But decentralization itself has a shortcoming of security of data. We can protect data loss but we cannot say that data is fully secured. Using the concept of decentralization blockchain was introduced which made it secure, tamperproof, reliable, and transparent [9].

Blockchain promises to record or keeping a record of everything whenever a transaction occurs [10]. Now a transaction can be a financial transaction as well as storing data in the database can be termed as a transaction as well. Everything in the blockchain is transparent in terms of records keeping.

Blockchain protects us from all the defects related to security. Below are the key attributes of blockchain technology which derives its more capability by describing that blockchain is not just a technology, using this we can drive almost everything in information technology and digital world:

Accessibility—It’s an open network. Accessible to everyone who wants to access the digital ledger. Anyone can add a new block to the chain by mining, upon which a transaction is recorded and the entire blockchain will have a record of it. Blockchain maintains the distributed ledger in a back end database.

Disruptive—Blockchain is said to be a Disruptive technology when we compare it to the Internet, as blockchain promises innovation in financial and commercial aspects when compared with the impact of web on communication [11]. Blockchain has revolutionized the transaction processing and its storage in the database, using below concepts:

Track data and its storage—Blockchain is a decentralized and distributed ledger whose transactions are recorded on each and every computer locked on the blockchain network, making the transaction data safer by tracking its data changes over time.

Trust—Trust is the key concept when we talk about blockchain. The data is accessible in real time and all the computers verify the transaction-related changes, this results in building up trust in data. Blockchain maintains the trust between individuals and businesses so that they can transfer information to each other using the uniquely identified address.

Peer-to-peer transaction approach—There are no third-party involvements when it comes to transaction processing using blockchain. Unlike regular transaction processing where we require our banks to verify and validate transaction, using blockchain no such dependencies exist on the third parties’ institutions. It is a new way to authenticate and access transaction systems.

Protects Identity—All the transactions are anonymous by securing the identity of all the parties. There will be no name displayed in the transaction, unlike a banking transaction system. Instead, it uses a hexadecimal address which is a unique address and hard to remember.

Decentralization—The records kept on blockchain all recorded on each node over the network. This eliminates further dependency on a central authority.

Secure—All the transactions on the blockchain are secured as it uses cryptography algorithms that are based on private or public key encryption mechanisms. Blockchain maintains the repository of contracts and assets without containing them physically.

Real-time Operations—Blocks in blockchain are verified and added in real-time, which reduces the risks associated with data synchronization.

It is the trust and reliability feature of blockchain, which has made it so popular for all applications.

What is Blockchain?

As we have already learnt why it is required, how fast it is growing. Let us now learn what is it?

To understand it in simple terms let us assume blockchain as link list that you must have learned in Data Structures. Just like linked list, blockchain have blocks in place of nodes of linked list. These blocks are joined with each other in somewhat similar manner as nodes of linked list. It is similar to the concept of data storage in a linked list. Like linked list nodes have two fields data and address, blocks in blockchain have namely three fields data, hash(address), and nonce. A node is connected with previous node using cryptography function called SHA-256 which makes it secure [12]. Nonce is a unique random number used to generate the hash (address) of previous block. Genesis is the name given to the first block created on blockchain. The two blocks on blockchain are linked to each other using hash. Blockchain system generates a unique number, typically termed as “Hash” [12]. If anything went wrong, as a result, a new block is created and added ensuring that no one is able to delete the previous block. Figure 1 explains the working of blockchain.

Fig. 1
figure 1

Blockchain flow

Blockchain is a ledger that contains all the transactions capable of transmitting any information securely. To ensure the authenticity in blockchain, it uses cryptography and digital signatures along with proof of identity ensuring read or write access rights are imposed. A blockchain is a moving network on which transactions take place without the involvement of any third-party institutions [13].

The structure of the block consists of three attributes, which are block header, block identifier, and Merkle trees. A block header contains hash of the previous block, mining details, i.e., timestamp, and binary hash tree root. Block Identifier contains a cryptographic hash. Merkle trees are the transaction in a block.

The blockchain-based ledger permanently holds the transaction records along with interactions that occurred between participants who have accessed the blockchain network. Each block on blockchain holds the transaction details and the currency type [14].

In the implementation of blockchain, peer-to-peer network is adopted. Peer-to-peer ensures that every entity or a person or user contains some records or data. Mutual consent is required before the execution of any transaction [15].

In blockchain, every user should contain the data along with the ownership of the data, which they store with them, ensuring data is distributed across the network and synced

In a permission-based database for blockchain, data and records are stored inside the database with applied permissions granted to some specific set of users [16].

Blockchain ensures that no one should be able to delete or modify a data or transaction in the database. The number of operations performed on a blockchain is termed as transaction. A transaction can be adding a record or retrieval of an existing record.

Blockchain build trust, integrity, and security [17]. Data is decentralized, meaning it is shared and secured inside log files. Cryptography is used to encrypt a number of records inside a block. This technology is completely dependent on the Internet in order to maintain the distributed ledger. Blockchain mining nodes perform three operations for a block which are executed, verify, and store the data in the block [18].

Consensus algorithms are used in blockchain in order to ensure if and when something in terms of record is added up in the chain. Everyone before proceeding with addition of blocks on chain should sign off a common agreement.

Suppose nick wants to send some money to jack, below are the transaction steps performed before the completion of actual transaction:

Unconfirmed transaction—Transaction request will be sent to peer-to-peer network from the node to MEMPOOL.

Validation of transaction—The network of nodes will validate the transaction using an algorithm.

Proof of work 1—When the transaction is validated, it will be grouped into a single block and sent to the miner.

Proof of work 2—Miners starts to unravel difficult math problem supported Merkle root and nounce.

Transaction confirmation—A new block will be added to blockchain and transactions inside the block will be marked as confirmed.

Types of platform in blockchain (Fig. 2)?

Fig. 2
figure 2

Platforms in blockchain

Public—Accessible to everyone. Permission less blockchain, which is accessible to the public, allows any users to access at any point of time. A completely public blockchain allows anyone to view and access the data.

Private—Permission-based blockchain is accessible to users who have been granted permission to access a private network on a private blockchain. This could be considered as a group of selected users of an institution or organization who has access to view and edit the data.

Consortium—Combination of Public and private platform.

Blockchain transaction takes place in real-time, to drive an application or business.

Consensus Mechanism in Blockchain

The consensus is a way to reach agreement in a group dynamically [18]. This mechanism ensures that an agreement reaches which should benefit the entire group itself. When a consensus decision making is obtained it is termed as “consensus mechanism.”

Objectives of consensus mechanism:

Agreement seeking—A consensus mechanism should cause the maximum amount agreement from the group as possible.

Collaborative—All the participants should put the group interest at the first place with aim to work together.

Cooperative—All the participants should work, as a team rather than putting own interests at first place.

Equal rights to everyone—This means that everyone’s vote in the group has equal importance and weightage.

Inclusive—Maximum number of people’s participation should be there is consensus process. It should not be as a normal voting where people feel like their vote will not have much weightage in terms of long run.

Participation—Consensus mechanism ensures that everyone should participate in overall process.

Each blockchain protocol is programmed with a consensus mechanism that is responsible for the verification and updating of transactions on the distributed network-based ledger. It is used to monitor records or transaction. Different type of consensus mechanism exists, out of which some are explained below:

POW (Proof of Work)

POW in simple words termed as “Proof-Of-Work” aims to solve mathematical problems which are complex and harder to solve. A block is added to the chain because of voting. POW validates the nodes in larger quantity, later these nodes mine the block upon solving complex mathematical problems and hash code is divided to read those transaction exists on the blockchain. New block is added into the chain after the blocks are mined, for which the miners are rewarded. When 51% of the nodes are able to solve the mathematical problem on the network, then new transaction and its associated data is added to the blockchain. Miners to mine the block, because of which a new block is added, solve the cryptographic puzzles. This process intakes a huge amount of energy with computational usages. The puzzles are formed to ensure, it becomes really hard on the system. A block is shared on the network for its verification when miner successfully solves the puzzle. Verification of block, if it belongs to chain or not is a quite simple process, for example bitcoin uses proof of work Protocol.

POS (Proof of Stake)

The system chooses the miner randomly. Here miners are called validators. This is how POS works:

As a stake, the validators will lockup some of their coins.

Validators will start the validation of the blocks, if they think that a particular block can be a fit on the chain in terms of adding a block, a bet will be placed to validate it.

Validators will be rewarded based upon their proportion of their bets, only if the block is appended.

POS is more resource friendly when compared to POW. In POW we have to waste lots of resources.

BFT (Byzantine Fault Tolerance)

BFT termed as “Byzantine Fault Tolerance” aims to obtain consensus even if some nodes are unable to respond in a network. BFT focuses on the prevention, which leads to the failure of system or systems. In order to obtain BFT, we have to ensure that all the working nodes in the network should reach the agreement. In certain amount of time, if no message is received, we can conclude that the message from a specific node is said to be faulty. If most of the nodes are able to respond with a correct value there on, we can proceed with assigning a default response. There are two types of Byzantine Failures:

Fail—Stop Failure

Arbitrary node Failure

POAC (Proof of activity)

POAC is a one among various blockchain consensus algorithm to make sure that blockchain-based transactions are genuine and every one user reaches a consensus of the general public ledger [19].

POAC may be a mixed approach which uses two opposite commonly used algorithms—named as proof of work and proof of stake. The mining process in POAC begins as typical proof of work process alongside various miners attempting to outpace each other using high computation power to hunt out replacement blocks. Whenever a replacement block is mined or discovered, the system switch back to POS, along with new discovered block, which contains a header and thus the reward address of the miner.

Based upon provided header details, replacement random group of validators from blockchain network is chosen. The larger crypto coins a validator owns, the greater chances they have to be selected as signer. When all validators have signed for the newly discovered block, it is identified and results into addition to the blockchain network, because of which transactions are recorded.

POB (Proof of Burn)

It focuses on addressing the POW problems related to energy consumption. In order to mine the blocks, miners have to buy a virtual mining rig. To achieve that miners, have to burn their coins. POB is an alternative consensus algorithm introduced to overcome or address POW system issues in terms of high-energy consumption. POB works on the principle, which allows miners to burn virtual currency tokens. The miners give rights for writing the blocks based upon the coins burnt. The miners burn their coins to purchase virtual mining rig, allowing them to mine the blocks. The bigger will be virtual rig, if the miner burns more and more coins.

POET (Proof of Elapsed Time)

The POET focuses to follow a lottery system, in order to prevent higher resources and energy utilization. In other words, we can say that POET is a consensus algorithm which forestalls highest utilization of resource and consumption of high energy. The method becomes more efficient by following a fair lottery system [20].

This is how the POET algorithm works:

Every participating node within the network is required to attend for a randomly chosen period of time; therefore, the first one to finish the designated waiting time wins the new block. Each node within the blockchain network generates a random wait time and goes to sleep for that specified duration. The one to awaken first—that is, the one with the shortest wait time—wakes up and commits a replacement block to the blockchain, broadcasting the required information to the entire peer network an equivalent process then repeats for the invention of subsequent block.

POC (Proof of Capacity)

The algorithm focuses to use the space available on miner’s hard drive so that mining rights can be decided [21]. Proof of capacity (POC) is consensus mechanism utilized in blockchains which permits the mining devices within the network to use their available disk drive space in order to make a decision on mining rights, rather than using the mining device’s computing power (as within the proof of labor algorithm) or the miner’s stake within the crypto coins.

POA (Proof of Authority)

The POA algorithm uses “authorities” which are the nodes who have access to create new block and to secure blockchain. They should have the required permission in order to delete a record. In other words, this consensus algorithm provides the efficient and practical solution for a private blockchain network. In 2017, Gavin Wood introduced this [22].

Proof of authority is a highly scalable system as the model itself is dependent on a limited number of block validators. Pre-approved participants verify the transaction and blocks, which act as mediators to the system.

2 Smart Contracts

Smart contracts are program which are event driven executed on blockchain with enforcing some business rules, which is capable to take the control over an asset which exist on the ledger.

Blockchain consist of smart contracts, which are computer protocols, who serves as facilitator and verifies transaction beyond the purchase and selling of currencies. Smart contract is an agreement between one or more entity when they want to complete a transaction. Therefore, both the parties have to agree upon a mutual consent before any transaction. This contract contains “code of law.”

Let us take a look at the example of land registry system. Registry of land proves the authenticity that Mr. XYZ holds the property legally which proves the ownership. Now the government can implement the blockchain to maintain the records of land registry data. Therefore, this can be the combination of hybrid system, where there is a public network, on which any person can see the property and find out about its boundaries and expansions. The other network, which contains all the private information to which only government official has access.

In case of purchase and sell of the property, the operations are carried out with the help of smart contract, which are simple, fast, and cheaper. This eliminates the need of intermediary authority to register a property. When a seller has received the full payment for the property by agreeing upon a smart contract, ownership rights and property get transferred to the new owner. This will add a new block of property information on the blockchain with containing the previous details and history of property.

3 Blockchain Implementation—Browser Based

After studying the basics of blockchain and what is smart contract, we will learn how we can deploy our smart contract in Ethereum blockchain.

Before proceeding with any transactions on blockchain, we must have an account or a wallet, which should have some cryptocurrencies [23]. So, first step is to have an account to hold cryptocurrencies. These are called wallets. These types of accounts are called Externally Owned Accounts (EOA). There are many types of wallets, in this chapter we will use MetaMask which is a browser-based wallet, i.e., its extension is embedded in our browser and we can use it from our browser directly [24]. Let us learn the complete process step by step:

Step 1: Install Metamask (Browser-based wallet)

  • Using chrome web store, query for MetaMask in search option, and get it installed in your browsers extension (Fig. 3).

    Fig. 3
    figure 3

    MetaMask

Step 2: Once the MetaMask Extension is added and installed in the web browser. Click on GET STARTED Button and then Click on Create a Wallet button in order to start using MetaMask (Fig. 4).

Fig. 4
figure 4

Steps in MetaMask

Step 3: The user is required to create a password as per the password specific rules (Fig. 5).

Fig. 5
figure 5

Password

Once user has successfully created a password, the user will be navigated to a page where a user is required to arrange the phrase in order to form a sentence; this is termed as secret phrase. The user is required to remember the phrase, so that if a user has lost the password, the account can be unlocked with help of secret phrase. Once user has obtained the content of secret phrase, click on Next button.

User is required to confirm the secret phrase to get finished with account creation. Once phrases of word are arranged in correct sequence, click on Confirm Button.

Once a user has finished all the steps as stated in above steps, user would navigate to the web page as shown in Fig. 6. The address 0x406A73c2A92D50ac8d43Ac4E1636c7804E0B1d3B uniquely identifies the created account; it is unique for every account. You will see a different address, which represents your address in EOA. It can be considered as your account number.

Fig. 6
figure 6

Account creation

Step 4: Rinkeby Authenticated Faucet (To get Ether in your wallet).

Now we have a wallet, but we do not have any cryptocurrency added in the wallet. We use Rinkeby Authenticated Faucet to add the cryptocurrency to wallet. This website helps us to obtain Ether based on request. In order to request Ether, we are required to have a Twitter or Facebook account. We will use Twitter in our chapter.

Login to your Twitter account. If you do not have one create it.

Step 5: A user should be logged into Twitter account, once a user is logged into Twitter account, the user is required to navigate into Rinkeby Authenticated Faucet using URL—https://faucet.rinkeby.io/ [25]. A user can request the Ether funds with the help of Twitter account by clicking on tweet Hyperlink given on page shown in Fig. 7.

Fig. 7
figure 7

Authentication

Step 6: User must navigate back to MetaMask wallet. The user is required to copy his unique address which can be found listed under Details button on the Dashboard. As in our case unique address is 0x406A73c2A92D50ac8d43Ac4E1636c7804E0B1d3B. Then paste the address, replacing the highlighted string in your Twitter account as shown in Fig. 8 [24].

Fig. 8
figure 8

Twitter account

Just to connect with all readers we request to follow @mayankcloud on Twitter [26]

Step 7: The user is required to navigate back to the home page of Twitter account. Under your tweets section, click on “Copy link to Tweet.” This is the one in which a user has requested ether in order to get real-time fund (Fig. 9).

Fig. 9
figure 9

Navigation

Step 8: Once user has completed the step 7, User must navigate back to Rinkeby Authenticated Faucet web page, and on the same web page, user is required to paste the URL as demonstrated in Fig. 10 and user has to select an option from Give me ether dropdown.

Fig. 10
figure 10

Demonstration

Step 9: User must navigate back to MetaMask wallet and refresh the page to validate the funds availability in the wallet. Strange! A user may not see any changes to the wallet because by default Main Ethereum Network is selected, from network options choose Rinkeby test network as shown in Figs. 11 and 12. Rinkeby Test Network is an Ethereum blockchain test network, which is used by developers to test their application by taking testing ethers. There are other test networks also but, in this chapter, we have used Rinkeby test network.

Fig. 11
figure 11

Step 9(a)

Fig. 12
figure 12

Step 9(b)

Step 10: Once done account will be funded and ethers will be seen in the account as shown in Fig. 13.

Fig. 13
figure 13

Step 10

Step 11: Now as ethers are added, we need to deploy and compile our smart contract. We are assuming that you know how to write a Smart Contract using solidity and we will cover easiest way to deploy your smart contract on Ethereum test network [27]. Online compiler remix is used to compile and deploy the contract finally. Open https://remix.ethereum.org/:

Step 12: Choose solidity in Environments (Fig. 14).

Fig. 14
figure 14

Step 12

Step 13: Click on Create new File button, which is located in the Browser storage explorer button as shown in Fig. 15.

Fig. 15
figure 15

Step 13

Step 14: Assign some name to the File by default it will take Untitled. Sol.

Step 15: Write your mart contract here. Or for testing you can copy paste from www.mayankagr.in. [28].

figure a

Step 16: Go to compiler and choose compiler version as per your smart contract for copied smart contract, version is 0.4.25. Click on compile and if no error smart contract is compiled and bytecode is generated as shown in Figs. 16 and 17.

Fig. 16
figure 16

Step 15

Fig. 17
figure 17

Step 16

Step 17: After compiling deploy the smart contract. Select deploy and run transaction icon. At environment there are three options to deploy on Rinkeby test network select Inject web3 option as shown in Fig. 18.

Fig. 18
figure 18

Step 17

Step 18: Then deploy by clicking on Deploy button and contract will be shown under deployed contracts as shown in Fig. 19.

Fig. 19
figure 19

Step 18

Step 19: One can see the deployed contract in metamask also as shown in Fig. 20.

Fig. 20
figure 20

Step 19

The smart contract is successfully deployed in Rinkeby test network of Ethereum which can also be viewed on etherscan [29]. To make an application for the deployed contract below section describes how to use Oneclickdapp an easy way to make a decentralized application for your deployed contract.

Step 20: Navigate to Oneclickdap by using URL as mentioned below [30]—https://oneclickdapp.com/

Step 21: Click over a button “Create a dApp for free” as shown in Fig. 21.

Fig. 21
figure 21

Step 20

Step 22: Provide an application name of your choice (Fig. 22).

Fig. 22
figure 22

Step 22

Step 23: Open the remix Ethereum page then open the contract written choose compile option. From the previously compiled code copy ABI and paste on Oneclickdapp window as shown in Fig. 23.

Fig. 23
figure 23

Step 23

Step 24: Put metamask address in Address field and choose Rinkeby in Network field.

Step 25: Then click on Next button. Thereafter user must Click on Createdapp Button (Fig. 24).

Fig. 24
figure 24

Step 25

The app is created successfully as shown in Fig. 25. On clicking set age one can input age.

Fig. 25
figure 25

Final Step

4 Conclusion

In this chapter, we discussed the smart contract, which is required to drive the business based upon some business rules. Alongside, blockchain implementation with its types is also explained with their brief steps followed. Blockchain implementation is explained with the help of Ethereum in-depth with dedicated steps with deeply explained.