Discover Ethereum, a Blockchain Based Computing Platform

0
4735

Dive into the world of blockchains, and use Ethereum to host a private network and deploy a smart contract.

Blockchain, as you might already know, is a tamper-resistant, append-only, distributed ledger. It is expected to be the next disruptive technology, although some argue that it is more of a foundational technology than something disruptive. Bitcoin was the first large scale adoption of a blockchain based platform, but the blockchain technology is capable of supporting much more than just cryptocurrencies. Ethereum provides an open source blockchain based distributed computing platform on which we can deploy apps to do much more than just financial transactions or money exchange. I’ve chosen Ethereum because it is very popular, and currently ranks second behind bitcoin, in terms of market capitalisation. Besides, it is open source, provides a Turing complete virtual machine – the Ethereum Virtual Machine (EVM) — to deploy the applications, and has an active community to support it.

In this article, we will discuss how to set up a private network that will host the Ethereum platform, including the blockchain. We will also learn to deploy a very basic application and interact with it. First, let us discuss some key terms that will help us understand the later sections.

Smart contract: This is a piece of code that is deployed in a distributed manner across the nodes hosting the network. It administers laws and rules, determines penalties and enforces them across the network. It contains states that are stored on the blockchain.

Consensus: This is the process by which all the different nodes agree about a state change. It ensures that even if malicious parties behave arbitrarily, the honest parties would still be able to reach an agreement.

Transactions: Any change of state is proposed as a transaction. The transactions (individually or collectively) are consented upon and then written into the blockchain.

Queries: Reading states from a current blockchain is known as a query. It does not require consensus, and any node can perform a query by just reading the latest states on the blockchain.

Mining (in Proof of Work systems): A hard cryptographic puzzle needs to be solved before a node can take multiple transactions and form a block. This process is called mining and the nodes which perform this are called miners. Because this is a tough job, to incentivise miners, a mining reward is given to the winner who successfully writes on the blockchain.

Genesis: Every blockchain starts with a genesis block containing the basic rules of that chain. It mainly contains the system parameters.

Prerequisites for installation

We first need a few tools to help us through the installation and deployment. Let’s assume you have Ubuntu 16.04 running on your system, although the tools and methods are quite generic and can be easily ported to other distributions or operating systems too.

Installing Git and Go: There are a few official implementations of the Ethereum protocol. We will build the Golang implementation from source and to check out the latest build, we will need Git. Also, the Go version present in the Ubuntu repositories is old and hence we will use the gophers PPA for the latest version.

$ sudo add-apt-repository ppa:gophers/archive

$ sudo apt-get update

$ sudo apt-get install golang-1.10-go git

Setting up the environment variables: We need to set up some environment variables for Go to function correctly. So let us first create a folder which we will use as our workspace, and set up a GOPATH to that folder. Next, we will update our PATH variable so that the system recognises our compiled binaries and also the previously installed Golang.

$ cd ~

$ mkdir workspace

$ echo “export GOPATH=$HOME/workspace” >> ~/.bashrc

$ echo “export PATH=$PATH:$HOME/workspace/bin:/usr/local/go/bin:/usr/lib/go-1.10/bin” >> ~/.bashrc

$ source ~/.bashrc
Figure 1: Using Remix to deploy a contract and interact

Installing and running Ethereum

Let us first check out the latest version of geth (go-ethereum) with Git, and then build it from the source.

$ cd ~/workspace

$ git clone https://github.com/ethereum/go-ethereum.git

$ cd go-ethereum/

$ make geth

Upon successful completion of the last command, it will display a path to the geth binary. We don’t want to write the entire path again and again, so let’s add that to the PATH variable:

$ echo “export PATH=$PATH:$HOME/workspace/go-ethereum/build/bin” >> ~/.bashrc

$ source ~/.bashrc

Next, we need to create a genesis.json file that will contain the blockchain parameters. It will be used to initialise the nodes. All the nodes need to have the same genesis.json file. Here is a sample of a genesis.json file that we will use. It is saved in our workspace directory.

$ cd ~/workspace/

$ cat genesis.json

{

“config”: {

“chainId”: 1907,

“homesteadBlock”: 0,

“eip155Block”: 0,

“eip158Block”: 0,

“ByzantiumBlock”: 0

},

“difficulty”: “10”,

“gasLimit”: “900000000000”,

“alloc”: {}

}

Now, open a new terminal (say Terminal 1) and run our first Ethereum node on it. To enable that, first create a work folder for the node and a new account. Make sure you don’t forget the passphrase because that can be fatal on the main Ethereum network. In our case, because we are just creating our own private network, this is not such a serious concern. Then we supply a network ID:

cd ~/workspace/

$ mkdir node1

$ geth account new --datadir node1

$ geth init genesis.json --datadir node1

$ geth console --datadir node1 --networkid 1729

We should now be inside the Geth console. You can play around before proceeding but for our purpose, let us head on to creating a second node. To do that, look at the enode details of our current node. On the Geth console, execute the following commands:

> admin.nodeInfo

{

enode: “enode://c2b8714eca73d7a5a4264fa60641a8791ff8d33e47 dbb51f8b590594eb48e2aba9f360f340f358700e41e9d8415d7ca f70c67d12a66096053989c3824f7f64c3@[::]:30303”,

………

We just need the enode details and have to replace the [::] with the localhost IP 127.0.0.1.

Let’s fire up a new terminal, say Terminal 2, to host the second node. We proceed like, before and then supply the previous network ID, bootnode details and a port number for the node to bind to. We will also enable RPC from a particular domain, which we will use later to connect to this node.

$ cd ~/workspace/

$ mkdir node2

$ geth account new --datadir node2

$ geth init genesis.json --datadir node2

$ geth console --datadir node2 --networkid 1729 --port 30304 --bootnodes “enode://c2b8714eca73d7a5a4264fa60641a8791ff8d33e47 dbb51f8b590594eb48e2aba9f360f340f358700e41e9d8415d7c af70c67d12a66096053989c3824f7f64c3@[127.0.0.1]:30303” --rpc --rpccorsdomain “http://remix.ethereum.org”

If everything goes well, you will have two nodes connected to each other, hosting the same blockchain. To confirm, you can use ‘admin.peers’ inside the Geth consoles.

Until now, we just hosted the blockchain. We did not perform any transaction, mine blocks or transfer ether. In fact, all our accounts are empty. Let us now check our account balance and start mining on one of the nodes, say Terminal 1.

> eth.getBalance(eth.accounts[0])

0

> miner.start(1)

We see that our account balance is zero. Starting the mining process may take some time. If you want a break, now is the time, because generating the DAG may take a considerable amount of time. Once the mining starts, you can recheck the account balance to see it increasing. This is because you are getting the mining reward. You can see logs on the console such as ‘mined potential block’ and ‘commit new mining work’ that tell you that a new block has been mined. The other node will also sync the newly created blocks.

To transfer ether from one account to another, we have to unlock the account and transfer funds. For example:

> personal.unlockAccount(eth.accounts[0], "pass", 24*7*360)

true

> eth.sendTransaction({from:eth.accounts[0],

to:"0xba993910008b3940626c83135fa2412b4a91b3b1", value: web3.toWei(6, "ether")})

In the first command, the passphrase needs to be supplied in place of ‘pass’. The last argument is the time duration for unlocking, which is optional. But we don’t want this to bother us again and again.

In the second command, the ‘to’ field should contain the address of the account you want to send to. You can execute ‘eth.accounts[0]’ on Terminal 2 and supply the string here. Once done and once a new block is mined, you can see the change of funds reflected in your account balances. If it says insufficient funds, wait for some new blocks to be mined or decrease the amount. We have sent six ethers in the example shown.

Writing your first solidity contract

Now that we have set up the network to host the blockchain, let us deploy a smart contract and interact with it.

Fire up the browser and head to http://remix.ethereum.org/. We will use the online compiler to compile our code and with it, connect to our localhost and deploy on the private network. Close the default code (Ballot.sol) that is open on Remix, delete the sol file from under the browser dropdown on the left and create a new file named Basic.sol on the browser. Then write the following piece of code inside the contract.

pragma solidity ^0.4.19;

contract Basic {

//declaring an unsigned interger. Let’s make it private

uint private variable;

//this function returns the value of the stored variable

function get() constant public returns (uint retVal) {

return variable;

}

//this functions sets the value of the stored variable to the passed argument value

function set (uint x) public {

variable = x;

}

}

Now, compile to see if it successfully compiles without errors. Next, go to the ‘Run’ tab and select ‘Web3 Provider’ from the ‘Environment’ drop down menu. Choose the default endpoint, if asked.

On clicking ‘Create’ , the contract will be deployed. But on the browser console, you’ll probably see an authentication error. This is because to deploy, your account needs to be unlocked. Head over to the Terminal 2 Geth console and unlock the account as you did while transferring funds. Now, once done, try creating the contract from your browser again. (If you see an error message saying ‘Insufficient funds’, try sending more ethers from your node1 account to your node2 account.) Once deployed and mined, you will see the address and function names on your browser, as seen on the lower right of Figure 1.

Use the ‘get’ button to fetch the current value of the variable. Use ‘set’ to put some value into the variable which you can check by using ‘get’ again. You will notice that ‘get’ gives the value instantaneously, whereas ‘set’ takes time. Also, on using ‘set’, a new transaction is seen on the Geth console on Terminal2. This is because ‘get’ is a query which just returns the current state recorded on the blockchain, whereas ‘set’ attempts to change the state. Any state changes must go through consensus, and hence we need to wait till the transaction is mined before we can see the changes across the nodes.

The final steps

This article was meant to initiate you into the world of Ethereum. There are a lot of things which you can try, and make complex blockchain based projects. I would encourage those interested to try out the following.

  • Exploring the Geth console and expanding the private network to multiple nodes: You can try to make a node malicious or shut down abruptly, and see if and how it impacts the transactions.
  • Writing more elaborate smart contracts: You can send and receive funds to and from smart contracts. Try some of the projects at https://www.ethereum.org/.
  • Using the online compiler was one of the ways to deploy and interact. You can manually compile and deploy using ABI (https://github.com/ethereum/go-ethereum/wiki/Contract-Tutorial) or use a framework like Truffle (http://truffleframework.com/).
  • Geth is one of the flavours implemented in Go. You can use other language implementations like C++ and Python, look into the code and contribute. They are all open source (https://github.com/ethereum). You can even use GUI clients like Mist (https://github.com/ethereum/mist).
  • Use the testnet and main Ethereum network to test and deploy contracts: Warning: The main network involves real money. So be sure about what you are doing. Writing secure contracts is a tough job (https://medium.com/new-alchemy/a-short-history-of-smart-contract-hacks-on-ethereum-1a30020b5fd)!
  • Take a look at other smart contract based projects and learn from them (https://www.stateofthedapps.com/dapps/tab/most-viewed).

Ethereum has a very active community. In case you face issues, a quick Web search should fetch most answers. If not, try their Gitter, Reddit and Stack Exchange platforms. I hope this article helped demystify some of the blockchain buzzwords and gave readers a feel of what blockchain is about. It is still a developing technology, and you can contribute both in terms of theory and implementation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here