Dive into Ethereum Development. Part 1

RubyRuby
13 min readSep 1, 2017

--

Blockchain technology is dominating people’s minds. They are buying mining farms, ICOs are collecting millions of dollars. We also want to get involved. We decided to start small. In the series of articles we will describe our entire way from blockchain rookies to universally acknowledged gurus. At the time of this writing we are still rookies, so we suggest that you follow our development and develop yourselves.

What is good about blockchain?

Based on the term, blockchain is a chain of blocks. Exactly. What advantages does this chain provide? Generally speaking, it’s a technology of decentralized data storage with a special structure that makes sure that data is manipulated within the framework of strictly defined rules. One can be sure of that because the dataset is stored on every device connected to the blockchain network, which means that it’s not possible to just replace the entire dataset in one place. Another thing is that every consecutive chunk of data, a so-called block, has a hash of the previous block, which gives us two advantages:

  • you can’t insert an intermediary block into a chain;
  • you can’t change a block itself without changing its hash, so you can’t do it and keep the integrity of the chain.
Merkle tree is used here for independent confirmation of any single transaction

New blocks are added by the participants of the chain. A special mechanism determines who gets to add the next block. The most well-spread of such mechanisms are Proof-of-Work and Proof-of-Stake. In Proof-of-Work new blocks are added by miners — network participants doing computationally intensive tasks, competing against each other for the right to create a new block based on their solution, getting a certain amount of currency of this network as a reward for a successful block creation. In Proof-of-Stake blocks are added by validators — network participants, competing not through performance, but through the amount of currency of the network in their accounts. They earn less, but it takes less work, too. The thing is, that in both cases an intruder would have to spend more than he could possibly earn to add a false block. In the first case — he’d have to spend money on mining equipment as powerful as all miners combined. In the second — he’d have to buy 50% of all the network’s currency.

Ethereum

There are different kinds of blockchains, most popular now being Bitcoin and Ethereum. Whereas Bitcoin is an implementation of cryptocurrency based on blockchain, the point of Ethereum is creating a platform that can solve very different tasks through Smart Contracts. That’s why we think it’s better to get started with Ethereum.

Smart contracts

Manipulating data in blockchain is ensured by so-called smart contracts. They describe what data should be stored on blockchain and determine the set of functions for operating it. Performing the functions and accessing the data is done through an interface provided by every contract. This interface is generated separately from compilation stage and allows to execute the binary code. The data is open for all the participants of the network, its reading costs nothing as, like we’ve already said before, all the participants do have the data. Data is changed through transactions. Every transaction can be described as follows:

  1. Transaction recipient
  2. Digital signature of the sender
  3. Amount of the sent currency
  4. Any data (optional)
  5. Limit of gas for transaction
  6. Gas price

You will find out what gas in points 5 and 6 is from the following paragraphs of this article and more detailed in our next article.

The transaction execution requires spending internal currency and waiting for a newly created block to include your transaction into the chain. The contract code is executed on a miner’s computer, in an EVM, and he gets a fee as a reward.

DApp

DApp — decentralized application. The application can be built based on different technologies, and blockchain with smart contracts is one of them. It’s safe to say that at the moment DApp is a logic on smart contracts plus some user interface. Storing more or less big amounts of data in an ideal DApp should also be decentralized, but it’s been a very short time since such kind of technology appeared and it requires another article. Blockchain ensures storage of current state and implements business-logic through smart contracts.

The bright future of DApps. Picture is borrowed from here

Through DApp a user can get access directly to blockchain on his computer after installing specific software. Blockchain can also be used for some individual operations on the server side of mobile and web applications we’re used to. The choice depends on the specific task. A simplified version of DApp looks like this:

Picture is taken from the presentation of Igor Barinov

Frontend and backend in this case are classic elements of an application, and functionality with using blockchain is performed on an EVM. Users have access to standard functions of an EVM such as sending transactions and checking the account balance, and also the functions, described in smart contracts, in Solidity language, for example. The access to an EVM is given through an RPC interface.

We think that designing decentralized applications is going to become a very demanded field, as they solve many problems: lack of trust to the data keeper; servers, vulnerable to attacks in centralized systems; closed systems.

First connection to blockchain

In order to be able to see what it’s like to be a blockchain participant we downloaded Mist — an Ethereum wallet. It’s called a wallet because it allows you to manage your accounts and your balance. The main currency is ether, but you can also emit your own tokens, that will be displayed in your wallet. However, Mist is not just a wallet, but also a DApp browser for an Ethereum blockchain: you can deploy and use contracts and access DApp applications.

To make working with blockchain clear we recommend you to use a pair of clients on different computers: you will be able to see that created data is accessible not only locally. But it’s not a necessary thing to do.

Windows users have to do a little bit more to get Mist to work. You’ll also need to install Geth as well — a command line Ethereum client. Before running Mist execute the following command in Windows command line:
geth --rinkeby
(you might want to replace --rinkeby with --testnet to use Ropsten, or omit the flag altogether to use the main network). Now, you won’t be able to change the network and start mining using UI. If you want to mine — run geth with the following command:
geth --testnet console 2>nul
Then, from the geth-console:
miner.setEtherbase(“<you wallet address>”)
And run:
miner.start(4)
(4 is the number of threads, you can put whatever you like). Keep in mind, that before mining it’s a good idea to wait until the synchronization is finished.

  1. During launch Mist asks you to choose a network — Main network or Test network. Choose Test network.

In order to perform any operations on blockchain, you need internal currency, ether in this case. Ether costs real money in the Main network. In the Test network it’s free easier to get. Besides, before launch all the network’s data is downloaded to your computer, at the moment of this writing for testnet Ropsten it’s around 12 GB, for testnet Rinkeby it’s 1.5 GB, for the real network it’s more than 50 GB. That’s why we choose Testnet for starters. In the real network ether can be bought in the stock market for real money (at the moment of this writing it’s almost $400), or mined which takes quite powerful hardware and a lot of time. In test networks sources vary: it can be mining for Ropsten (getting from other Ropsten sources didn’t work for us), or receiving from such sources as https://www.rinkeby.io/->Crypto_Faucet for Rinkeby. Mining in Testnet takes a significantly smaller amount of time than in a real network. For example, depending on luck with a laptop processor i5 6200u we managed to get 5 ethers in about 2–3 hours. Mining speed in that case was around 50 KH (50 KH — 50 Kilohashes or 50 000 hashes per second). You can see it in your system and get a rough estimate of how much time you will need. By the way, after you have mined a few ethers on one client, you can easily transfer some of them to another one, if it mines slower, for example. It’s worth noting that in further work we will use only Ropsten, which is a Proof-of-Work network, that’s why mining is used in it. In versions of Mist later than 0.9 it is not a default network anymore. If you want to use it, first launch Mist by pressing Launch Application, then in the menu Develop>Network and select the necessary network. We should note that in general Rynkeby is more convenient, as it doesn’t require mining, faster and lighter, so you won’t miss much using it. However, Ropsten is much more like the real network and it allows to experience all its strengths and shortcomings.

2. Now, Mist is launched, it suggests to make a password for your account. You don’t need a login as the private key file is the only thing necessary for identification.

The private key is stored in linux in folder ~/.ethereum/testnet/keystore/ for Ropsten , and ~/.ethereum/rynkeby/keystore/ for Rynkeby. Note that different keys are created for different networks, so, if you are going to use Ropsten like us, you will need to create another account. The name consists of date and time of creation and the address. Address is a hexadecimal line of 20 bytes like 0xe03269461f7672494fb0dbbe89c00614601b5d24. The initial 0x is omitted in the file name. The address is used for identifying your account in blockchain. You can send ether to it from different accounts.

3. Like we said before, local database needs to be synchronized. For testnet Ropsten it might take a few hours. You have to wait till the process is finished, otherwise there’s a risk of getting a desynchronised database.

At least in our case we had a situation when during mining the ether amount was increasing incredibly fast, but it couldn’t be used — none of the operations were visible to other network participants. The problem was discovered as follows: in Mist in the left lower corner a number of the last block is displayed (or how many block are left before the end of the synchronization process, in this case it’s OK and you just need to wait for the process to end). The number of the last block in the local copy can be compared to the real value for the blockchain, for example, here you can find out the latest block numbers for Ropsten network. If your value is a lot smaller, it’s possible that your database is not synchronized right. So, what should you do if the synchronizations in Mist is finished, but the block number is still wrong? We solved this problem by deleting all data and downloading it again. The data in Linux for Ropsten network is in folder ~/.ethereum/testnet . Deleting everything from subfolder chaindata helped. After that we launched Mist and this time patiently waited for the synchronization to finish.

4. After synchronization you can select Develop->Start mining in the menu. This is necessary to receive at least a little ether. This is true only for Ropsten network. If you want to use Rynkeby network, go to https://www.rinkeby.io/, tab Crypto Faucet and follow the instructions.

Ether is necessary for any operations involving data change, because you can buy gas with is. Gas is an abstract unit of measurement necessary for estimation of work for transaction. Gas doesn’t depend on the current cost of ether, so the estimation is independent. When making a transaction you can set how much ether you pay for every unit of gas and the maximum amount of gas you are ready to buy. The more you pay, the higher priority your transaction gets for potential miners. Because paying for gas is paying for miners’ work of making your transaction and including it into the next block. That’s why a miner not only gets a fixed pay for every created block (at the moment of this writing it’s 5 ethers), but also a pay for transactions, usually a few hundredths of ether. The amount of gas for a transaction depends on computational intensity of data operations. In the next article we will provide an example of how gas is spent and estimated.

A Basic Smart Contract

As soon as you have some amount of ether in your account you can start experimenting with smart contracts. The language that is used to write contracts, Solidity, is similar to C++ and JavaScript. There are other languages, too, but Solidity is the most popular, well-supported and well-documented, so we advise you to use it. Let’s take a look at a simple contract, the only purpose of which is to store a string and allow to change it.

The code of the contract:

pragma solidity ^0.4.10;contract StringHolder {    string savedString;    function setString( string newString ) {        savedString = newString;    }    function getString() constant returns( string ) {        return savedString;    }}

Line pragma solidity ^0.4.10 means that the minimally necessary compiler for this contract is 0.4.10, and symbol ^ prohibits using the compiler starting with 0.5.0. It’s useful because Solidity is a developing language and despite the developers’ desire to maintain compatibility, it’s not always possible. The name of the contract is set after keyword contract.

All the stored data is described in the body of the contract, in this case it’s the field savedString of type string. Manipulations with data are made through setters and getters. In our case the function setString( string newString) assigns to a contract variable a new value. Function getString() const returns( string ) returns a string value (type of the returned value is set as returns(<type>)). We want to draw your attention to the key word constant — it guarantees that no data will be changed when performing the function. If the data isn’t changed, there is no need to pay for gas. That’s why getters are immediate and free. Setters aren’t immediate (they finish only when the transaction is added into a blockchain block) and they require payment.

Remix IDE is very convenient for initial contracts experiments. You only need to copy the given contract code and paste it into the code window. Press Create in the right panel to create a contract without its publication to the blockchain. You’ll see the following:

Getters (getString) are blue, setters (setString) are red. You can see how much gas is spent.

Don’t forget to put quotes when setting a value in the setString field, otherwise you’ll get an error.

After you’ve checked that get and set work correctly, you can deploy the contract into a real blockhain. To do this switch back to Mist, go to Contracts and press Deploy New Contract. Copy code into field Solidity Contract Source Code and on the right you’ll see a drop-down list Pick a contract. Select StringHolder, the only option in this case. Set a payment amount which will influence the deploy time, press deploy, an approximate cost will appear in the window. Enter the account passwords and press Send Transaction. A new transaction with progress “x of 12 Confirmations” will appear in the wallet. The first confirmation means that this transaction was included into a block by a miner, all the next ones mean that a corresponding number of block have been created after the block with our transaction. It makes sure that the block with our transaction won’t be canceled. But in order for the contract to become active a single confirmation is enough. After confirmation go to Contracts -> String Holder. The interface of the contract is displayed in Mist like this: getters are on the left (Read from contract), setters are on the right in the drop-down menu. It works just like in Remix IDE, but setting a new value for the string field is a real transaction, which requires a password confirmation (just like the creation of a contract) and expects 12 confirmations from miners.

How can others see this contract? A contract is defined by two things: its address and its interface (ABI — Application Binary Interface). All this information can be found on the contract page in Mist, just press Copy Address and Show Interface buttons. Address is a 20-byte Hexadecimal number, for example in our case it is 0x65cA73D13a2cc1dB6B92fd04eb4EBE4cEB70c5eC. Interface is JSON-text, in our smart contract looking like this:

[ {
“constant”: false,
“inputs”: [ { “name”: “newString”, “type”: “string” } ], “name”: “setString”, “outputs”: [], “payable”: false, “type”: “function” }, { “constant”: true, “inputs”: [], “name”: “getString”, “outputs”: [ { “name”: “”, “type”: “string”, “value”: “Hello World!” } ], “payable”: false, “type”: “function”} ]

Interface is generated automatically from the contract code and it mustn’t be changed after deployment, the contract address is returned after deployment and points at the binary code of the contract. Mist saves this data and grants the interface for getting it only if the deployment was made through it. By the way Mist stores a list of all performed/performing transactions locally and only if they were made through its interface.

A client, who wants to use a contract, must receive this data, and in case of Mist he needs to choose Contracts>Watch Contract. You can choose any name, it’s only used for convenience. After you press OK, the contract will appear in the list, so you can access it and change the line from a different client. After the transaction is performed (at least one confirmation is received) all the clients will see a change in the line.

This example describes a real distributed application, where every client downloads the entire blockchain to their computer, which is not very convenient but it assures the absence of facilitators (actually Mist IS a facilitator, but a very reliable one). In reality compromises are necessary: for example, the blockchain node is deployed on the third party’s side, while a user gets a web-interface. Or a special plugin is installed into the browser (such as MetaMask) which uses a user key to sign transactions. In any case a facilitator trust issue arises. Hopefully, this problem will be resolved either through implementation of a simple client protocol, which doesn’t require the entire database, or somehow else. So far we have to work with what we have.

In our next article we’ll take a closer look at how all this works.

--

--

RubyRuby

We’ve been building web applications for years. Now we make our first steps in the world of blockchain and we want to share this journey with you.