Ethereum and HelloWorld

In this post i just describes Ethereum basics and how to develop a simple Hello-World-Blockchain project in your local machine.

Intro to Ethereum platform

Traditional intro:
"Ethereum is the largest and most well-established, open-ended decentralized software platform that enables SmartContracts and Distributed Applications (ĐApps) to be built and run without any downtime, fraud, control or interference from a third party." 😎
My intro:
Ethereum is a kind of decentralized Blockchain platform (there are some other Blockchain platforms : BigChainDB, Chain Core, Corda and so on). The good news is, Ethereum is open source platform. So you can use Ethereum platform to build and deploy your Blockchain apps called DAPPS. Actually Ethereum is not only a platform but also a programming language running on Blockchain. Ethereum's crypto currency is Ether. Ether is also called Digital Oil because you have to pay form Ether for running your program in Ethereum. And in Ethereum each action costs an amount of Gas.

Microsoft Azure provides a Online Ethereum platform for developers. It is configurable in few clicks very easily. But in  this post i will show you how to establish quick Ethereum environment on your machine using node package manager.

Big Picture Of Ethereum Platform

Ethereum holds set of accounts. Each and every account has a Owner and  Balance(Ether). If one account can prove it's identity then the particular account can transfer money from this account to another account. That operation called a Transaction.
So Ethereum platform is a transaction processing system.

But some of these accounts are different from other. They do not have owners and they own themselves (Robot Accounts). These accounts are created by the Developers and when creation time we give them a memory and a piece of code and Ether. These special accounts are called Smart Contracts.


So these are the two types of accounts,


1.Externally owned accounts (EOAs) - There is a owner
  • has an ether balance,
  • can send transactions (ether transfer or trigger contract code),
  • is controlled by private keys,
  • has no associated code.

2.Contract accounts - There is no owner

  • has an ether balance,
  • has associated code,
  • code execution is triggered by transactions or messages (calls) received from other contracts.
  • when executed - perform operations of arbitrary complexity (Turing completeness) - manipulate its own persistent storage, i.e., can have its own permanent state - can call other contract
Also we can categorize externally owned accounts into two parties. They are,
  • Full Nodes - Nodes which are directly participating for mining in the network
  • Light Nodes - Nodes which are not participating the mining process but they are connected to the network as normal user accounts. Those accounts can be used to send transactions into the Network.
Commonly Ethereum Account has following attributes, 
  • Nonce - counter for the outgoing transaction
  • Balance - amount of Ether in the account 
  • Storage Root - hash associated with the storage of the account 
  • Code Hash - hash related to the code of the account and if there is no hash then it is a normal account, else it is a Smart Contract

Externally Owned Accounts Properties 

Actually Ethereum key generation is based on public key cryptography, Elliptic Curve Digital Signature Algorithm. Ethereum uses public key cryptography for authentication.

Address of Account : Account address is derived from the public key. Actually we generate the hash value of public key and we take only the last 160 bits of the hash string as the address. It uses SHA3 Hash Function for this.

Public Key : public key is generated using the private key. 

var publicKey = util.bufferToHex(util.privateToPublic(privateKey));
(result : 0x4643bb6b393ac20a6175c713175734a72517c63d6f73a3ca90a15356f2e967da03d16431441c61ac69aeabb7937d333829d9da50431ff6af38536aa262497b27)

private Key : private key is a 256 bit long string. Keep in your mind it is possible to have multiple private keys for a specific address. 

var privateKey = '0xc0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0dec0de';

What is a transaction in Ethereum ?

Under this topic i explain both on Transaction and Message Call.
There are two types of transferring activities in Ethereum. One of them is actual transaction happening between two externally owned nodes. In this scenario one account sends the signed data to another account and we called it Transaction.
At that time data content is:
  1. Message to recipient (address of the recipient).
  2. Signature that determine sender is a valid sender.
  3. Value that represents the amount in "Wei", is transferred from sender to   receiver .
  4.  Start Gas that limits the maximum number of computational steps the particular transaction can execute. Also we called this Gas Limit and it determines the maximum number of gas you suppose to burn for the transaction. Gas Limit terminates unintended behaviors can occur during the transaction(Of course let's imagine your transaction starts unexpected computation but you have specified the Gas Limit matching to your expected executions in the transaction. So this particular situation the  transaction is terminated and rollback once it exceeds the Gas Limit).
  5. Gas Price that says the amount(Wei), transaction sender willing to pay  the Miner per unit of Gas. I'll explain about Gas later in this post.
Actually Calling a Smart Contract also a transaction in Ethereum (only write data to Smart Contract and create new instance of a Smart Contract. Not reading from Smart Contract). We send Smart Contract related calls  combining to a Transaction to the network. Reading from a Contract is not a transaction because there is no mining process happened when reading the data from a Contract. I will explain this in future as well. 

The other transferring activity type is Message Calls. Those message calls are related to Smart Contracts. One Smart Contract can send Message to other contract. They never survive in the Ethereum Context and they are considered as virtual objects. Also we can called it a function call. Message Call also have some properties. They are,
  1. The sender (address of the sender)
  2. The recipient (address of the recipient)
  3. Value which indicate the amount to transfer 
  4. Optional Data Filed which includes the actual input data for the function call 
  5. Start Gas / Gas Limit (explained above)

What is "Ether" (ETH) and how does it differ from Bitcoin ? 

 As i said Ether is kind of a digital Oil. In Ethereum platform you have to pay to computational resources in order to run your application.

Bitcoin is also a digital currency but it is originally developed as a medium of payment transaction and store of value in 2008-2009 by Sathoshi Nakamoto. He used Blockchain as a decentralized open database for Bitcoin. While Bitcoin focus to track ownership of digital currency, Ether and Ethereum can be used to run decentralized applications. In Ethereum instead of mining for Bitcoin, miners works to earn Ether and  you should use Ether to pay transaction and service fee in Ethereum. But In Ethereum you can not get a profit as a mining node because the whole purpose of Ethereum is to provide wold wide computer with an ultimate storage and a super computational power. So as mining node(Full Node) you only get the cost taken for computational power(for burned Gases).
(I think now you got an idea about the difference between ETH and Bitcoin.)

What is a Smart Contract in Ethereum (Robot Account)?

Piece of code that lives in the Blockchain as a special account which executes commands how they were told to by the shared logic. Actually this is the place where we put our business logic. Once Nodes get a transaction if it is for a DAPP(Smart Contract / Robot Account) then that particular Node will awake the Smart Contract and its code is executed as instructed by the input parameters sent with the transaction. Actually Ethereum Virtual Machine is responsible for executing the Smart Contract Code on each an every node participating in the Blockchain Network, when they verify the new Blocks that going to be stored in Blockchain. So every time a transaction going to be saved inside  a block, that particular node will execute the Contract code again. Even though the Smart Contract is also a part of the Blockchain we can imagine it is a separate account with storage and ether.


What is Ethereum Virtual Machine ?

Is a compete software package that runs on Ethereum. It ennable you to run your program in Ethereum. Instead of creating entire Blockchain for each and every application you build, Ethereum VM let us to create our programs on Ethereum much easier and efficient than ever before. So it means EVM's duty is to create a run time environment for DAPPS.

It's very similar to any other high level languages like Java, Solidity is abstracted from the normal machine language. EVM uses Stack based architecture because this is a decentralized systems and if it uses Registry  based architecture then there can be some collisions among nodes in the system. Because there are many implementations available for Registry Based architecture. But keep in your mind Contracts are using its own Storage(permanent) and Memory(volatile).

And if we talk about the storage mechanism of the EVM(Stack) it is a volatile memory. And it can keep 256 Bits values and can store maximum of 1024 items. So you can see it has been designed to accept 256 Bits lengthy byte code. It also has a key value storage mechanism. The reason behind the key value storage, it helps you to easily look up for the variables. And EVM stores program code in a separate ROM. When we talk about the Memory it is volatile.

The Journey of a Smart Contract Byte Code in EVM - 
It begins with validating the relevant transaction by the Ethereum Network nodes. Once they got the Nonce from the miner they starts validating the relevant transaction before it add to the Blockchain. At the same time if there is a Contract function call in the transaction then the node awakes the relevant Robot Account(Contract Instance ). Robot account loads its instruction to the EVM ROM. Then relevant instructions are loaded from  the EVM ROM to the Stack  by special calls in sequential manner. Then program counter is incremented one by one and send that byte code instruction to the Stack. Let's say instructions in the Stack right now, are written for the data persist. Then data is persisted into the Contract Memory. Let's say there is a temporary memory requirement like saving function local variable values for future instruction (You have to use memory keyword against the variable to do so. But Structs and Arrays are only allowed to use memory). Then those values are written into the Memory. At the end of the function call data is cleared from the Memory. Normally local variables are stored in the Stack itself temporary.

Normally there are two types of functions are handled by the EVM. They are EVM functions and user defined functions in Smart Contracts.

Some functions of EVM,
  • Arithmetic Operations
  • Comparison & Bitwise Logic Operations
  • SHA3
  • Environmental Information
  • Block Information
  • Stack, Memory, Storage and Flow Operations
  • Push/Duplication/Pop/Exchange Operations
  • Logging Operations
  • System Operations
Now you know EVM doesn't have registers. Normally in computers, registers are responsible for handling invocation of instructions. But in EVM it is done by the EVM Stack. For an example adding two numbers is happen in Stack as bellow,

PUSH1 0x1 ==> {stack[0x0] = 0x1}
PUSH2 0x2 ==> {stack[0x0] = 0x2, stack[0x1] = 0x1}
ADD       ==> {stack[0x0] = 0x3}


What is "Gas" in Ethereum ?

Actually Gas is just like a unit in Metric System. We use units of Metric System for measurements (Length, Mass, Volume). In Ethereum Gas is the unit that measures the cost(processing power) of running a process using a smart contract. Other thing is Gas is defined to protect the Ethereum from malicious attacks. But how?. Let me explain.
I mentioned you have to pay for the platform usages by the  currency called  Ether, measured in Gas. If you use the platform as intended it will be a very fair price. But if you do malicious things it will be very expensive. Also there is a fixed Gas Limit for transactions and your transaction not performed if that particular transaction exceeds the Gas Limit.

Besides that Gas behave like the internal price for running transactions. Actually what Gas does is it separates the system from Ether. Always you have to pay fixed Gas amount for a particular transaction process because Gas has fixed value in the Ethereum platform. But Ether value can be changed.

Cost of a transaction is decided by the following criteria,



Ethereum Average Gas Price Chart (not the latest. just for getting an idea):


I will explain how Gas is used inside the Ethereum Virtual Machine for computational tasks and for storage in my very next blog post.
Now you have the basic idea about Ethereum and you are ready to establish your own Blockchain platform on your local machine.


More info related to Gas,

Lets imagine you want to spend less on a transaction. Then you can simply reduce the amount in front of Gas Price. But keep in your mind this filed value is directly affects for the decision of how quickly your transaction will be mined. During normal times Gas Price affects on your Transaction as follows
 - 40GWEI ensures your transaction will be in the next block
 - 20GWEI determine your transaction will be in one of next few blocks
 - 2GEW normally get into your transaction next few minutes

The other question is will increasing the Gas Price get it mined you transaction faster?. Yes of course there is a high priority for higher amount of Gas Price. Naturally miners will encourage by high Gas Price. If you are hurry you can include high Gas Price. Then your transaction will jump to the highest priority of Miners' lists.
But the good practice is always put a normal Gas Price for non-urgent transactions. Otherwise system will get used to execute transactions for higher prices.
The other important factor you should know is to put the exact Gas Limit when taking a token what Token Seller told. I will explain this in one of my future tutorial.

Ethereum Block Merkle Proof 

Actually in my previous tutorial i discussed the Merkle Tree in common way for Blockchain. But this time i am going to discuss the Merkle tree very specifically to the Ethereum.
If you take Ethereum Block it contains three Merkle Trees. They are,
  • Transaction Root
  • Receipt Root
  • State Root
 It maintains those three Merkle Roots to accomplish the following incidents,
  1. To determine the particular Transaction is stored in the specific Block.
  2. To determine the relevant Contract related transactions were emitted by a particular address in last 30 days.
  3. To get the current balance of my account
  4. To validate whether particular account exist or not
  5. Pretend to run this transaction on this Contract. What would the output be?
First point will be handled by the Transaction Merkle tree. It simply ensure the particular transaction is stored in the relevant address.
Receipt Root will take care on the second point. So it ensures that the relevant Transactions are emitted by the particular address in last 30 days.
State Root will ensure both third and forth points which mean it verify that the particular Account exists and what is the current balance of the account. Also fifth point will be taken care by the State Root.

Major types of Blocks.

In my previous Article i just introduced the Block in Blockchain. Under this topic i am going to introduce some major Block Types in a Blockchain Platform.
  • Genesis Block - Very first Block in any Blockchain Platform. In main Bit Coin Network the Genesis Block is created by the creator of Bit Coin. The message on that block :  “The Times 03/Jan/2009 Chancellor on brink of second bailout for banks”.
  • Orphan / Detached Block - Valid Block that meets all the necessary requirements to be added to the Blockchain at one point of time but which is not a part of the main chain. This type of Blocks can be generated if two miners produce the Block at similar times. This affects to split the network into two paths and nodes attempt to decide which Block to continue building on. Finally the Block with the greatest Proof of Work will be selected to be added to the Blockchain and the Block with miner proof of work will be the Orphan Block. Orphan Block doesn't have a parent and BitCoin has the concept called Orphan Block.
  •  Stale Block - Valid Block but not added to the Best Chain of Blocks. This block is inactive. But this Block has a parent. Having a parent and not having a parent is the main difference between Orphan Block and Stale Block.
  •  Uncle / Ommer Block - Commonly associated with Ethereum. This Block is very similar to the Stale Block because this type of blocks also have a parent block but there are some differences. This type of blocks are valid and mined in a genuine manner but once they are produced there is a valid block attached to the main chain instead of this. Anyhow Ethereum encourage miners to produce Uncles and includes them in the Blockchain because it increase the security.

Steps To establish your own Blockchain Platform.

Tools that you have to have:
  • VS Code
  • Node JS & NPM
After you installed Node and NPM on your machine successfully you can install these packages through Node Package Manager.
  1. Truffle Tool Set (npm install -g truffle)
  2. TestRPC (npm install -g ethereumjs-testrpc)
 Truffle Tool Set :
Truffle tool set helps us to create project structurecompile and deploy our smart contract to local  Blockchain.

TestRPC :
This is our local Ethereum Test Server (fast and customizable Blockchain emulator). This test server initiate a in-memory Ethereum Blockchain for testing our Smart Contracts. 

Time to create Hello World Ethereum Blockchain project

Make sure now you have installed above mentioned tools and packages correctly. Here we write codes using the language called solidity. But if you do not know Solidity don't be afraid because my next tutorial will be about Solidity Basics. If you know basic programming concepts in JavaScript this exercise will be nothing to you 🙌

First Step : initiate your project structure using Truffle,

Sometimes it will give some errors if you are using windows power shell. In that situation you can use these commands to generate your project.
     > npm init #then will make a new npm project particularly package.json
     > npm i truffle #then will download node modules
     > ./node_modules/.bin/truffle init #then will create a truffle project

Second step : open up your project in VS Code,
 

so 'code .' command will start VS Code and load your project(make your you are inside the HelloWorld file when you hit this command)

Third step : create your own smart contract called 'helloworld',
command : truffle create contract helloWorld 

if you noticed, a new file called 'helloworld' will be added to your project(contracts -> helloworld),

Forth Step : create getMessage() function,
go to newly created helloWorld.sol smart contract and write your function.
you can compile your Contract using command : truffle compile helloWorld.sol


Create a new file called deploy_hello_world.js inside migrations folder using command : 
truffle create migration deploy_hello_world


add the following export to it.
finally save your files.


Fifth Step : start testRPC test server and deploy our contract,
so open a separate terminal window and hit : testrpc
Here you can see by default server provides some accounts with Genesis Account and their private keys. In my future tutorials i will teach you how to connect these accounts to Ethereum wallet called Metamask.

Before the final command just go to the truffle.js file and add the following code lines to configure network.
Actually this truffle.js file contain details for deploying our Smart Contracts to Ethereum Blockchain Network. Currently this configuration is matched to deploy for Local Network which is created by TestRPC. In future tutorial i will reach you how to use this file to deploy our Contracts to Microsoft Azure Consortium Block Chain Network.

go to the previous terminal window(not the testrpc) and hit :
command : truffle migrate --reset
Now if you go to your testrpc console window, you will see your contract was successfully deployed in logs.
If you want to test our function just type these commands in HelloWorld Terminal Window (or new Terminal Window):
command : truffle console

>truffle console
     >var hw
     >helloWorld.deployed().then(function(deployed){hw=deployed;});
     >hw.GetMessage.call()

output : Hello World !!!

If you want to change the default settings (number of accounts, port and gas price etc.) of truffle server just type truffle --help and get help menu. There you can find relevant commands 😌.

Cheers !!!
My Next Post : Microsoft Azure Consortium Blockchain and do Deployments

Comments

  1. In Windows sometimes 'truffle init' command may not work. In that case you can go through following approach. But guarantee that on Linux 'truffle init' and all above codes will work for you.

    on windows power shell :-

    run npm init #then will make a new npm project particularly package.json
    run npm i truffle #then will download node modules
    run ./node_modules/.bin/truffle init #then will create a truffle project

    ReplyDelete
  2. If you are using Windows Power Shell you have to bypass the Execution Policies to run some scripts. To do that run this command :-
    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

    ReplyDelete

Post a Comment

Most Popular

Introduction to Blockchain