Immersion in development on Ethereum. Part 1

Blockchain technology has taken over minds. Farms are being bought , ICOs are raising millions of dollars. Our company also wanted to join. We decided to start small. A series of articles will describe our path from beginners in the blockchain field to universally recognized gurus. At the time of writing these words, we are still at the beginners' stage, we propose to monitor our development and develop with us.


What is blockchain good for?


Judging from the name of the blockchain, it is a chain of blocks. And there is. But what does this chain give? In fact, this is a decentralized data storage technology with a special structure that allows you to be sure that data is manipulated within clearly defined rules. This assurance is ensured that the data array is stored immediately by everyone who is connected to the blockchain network - this means that it will not be enough just to replace the entire array in one place. And each next piece of data, the so-called block, contains a hash of the previous block, this gives two pluses:

  • it’s impossible to substitute the intermediate block in the finished chain,
  • the block itself cannot be changed without changing its hash; therefore, this cannot be done without violating the integrity of the chain.


Merkle tree is a hash tree, in this case it is used to independently confirm the validity of individual transactions. Transactions - this is the data in the blockchain

The work of adding blocks is provided by the network participants themselves. Who will be given the right to add the next block is determined by a special mechanism. The most common of these mechanisms are Proof-of-Work and Proof-of-Stake. In the first, blocks are added by miners - network participants who solve computationally complex problems, competing with each other for the right to create a block based on their solution, and as a reward for successful block creation, they receive a certain amount of currency from this network. In Proof-of-Stake blocks are added by validators - network members competing not on the basis of performance, but on the basis of the amount of internal currency of this network on their account. At the same time, they get less, but less work is required from them. In both cases, the logic is that an attacker will have to spend more to add a fake block, how to make money. In the first case - for mining equipment, comparable in power with other miners combined. In the second case - to buy 50% of the network’s currency.

Ethereum


There are various blockchain implementations, among which the most popular are Bitcoin and Ethereum. While Bitcoin is a blockchain-based cryptocurrency implementation, Ethereum's goal is to create a platform that allows you to solve a variety of problems using smart contracts. Therefore, it is logical to start your first acquaintance with Ethereum

Smart contracts


The manipulation of data in the blockchain is provided by the so-called smart contracts. They describe what data to store on the blockchain and a set of functions for operations on them. The performance of functions and access to data is carried out through the interface provided by each contract. This interface is generated from the source code separately from compilation and allows binary code to be executed. Data for network participants is open, and reading them costs nothing, because, as already mentioned, the data is stored by all network participants. Data changes occur through transactions. Each transaction can be represented by a structure of the following form:

  1. Transaction Recipient
  2. Digital Sender Signature
  3. Amount of currency sent
  4. Custom data (optional)
  5. Gas limit per transaction
  6. Unit price of gas

What is gas from paragraphs 5 and 6 will be described in the following paragraphs and will be described in more detail in a separate article.

Transaction execution requires internal currency costs and waiting for the next block created by the miner with your transaction to be included in the general chain. The contract code is executed on the miner's computer, in the EVM virtual machine , and the miner receives a commission as a reward.

DApp


DApp - Decentralized Application or decentralized application. Ideally spelled ĐApp, but we will use simplified spelling. The application can be built on different technologies, but among them there is also a blockchain with smart contracts. We can say that at the moment DApp is the logic on smart contracts plus a certain user interface. Storage of more or less voluminous data and messaging in an ideal DApp should also be decentralized, however, these technologies are just beginning to appear and deserve a separate article. The blockchain provides storage of the current state and implements business logic through smart contracts.
image

The ideal that decentralized applications are striving for. The picture is taken from here

Using DApp, the user can access the blockchain directly on his computer by installing special software. The blockchain can also be used for some separate operations on the server side of the usual mobile and web applications. The choice depends on the specific task. A simplified version of DApp can be represented as follows:


The picture was taken and translated from the presentation of Igor Barinov.

The frontend and backend in this case are the classic elements of the application, and the functionality using the blockchain is performed on the EVM virtual machine. The user has access to the standard functions of the virtual machine - such as sending a transaction or viewing the account balance - as well as the functions described in smart contracts, for example, in solidity language. Access to this virtual machine is provided through the RPC interface.

The creation of distributed applications should, in our opinion, become a rather demanded direction, since they allow solving many problems: a lack of trust in the data keeper, servers vulnerable to attacks in centralized systems, and closed systems.

First blockchain connection


In order to at least somehow see what it means to be a member of the network, we downloaded Mist (at the time of writing, the latest version at 0.9.0) - Ethereum wallet. Mist wallet is called because it is possible to manage your accounts and the balance on them. The main currency is ether (ether), but you can issue your own tokens, they will also be displayed in the wallet. But Mist is not only a wallet, but also a DApp browser for the Ethereum blockchain. It allows you to lay out and use smart contracts, as well as use DApp applications.

For clarity, working with the blockchain we recommend using a couple of clients on different computers: it will be possible to see that the data being created is available not only locally - but this is not necessary.

UPD for Windows: For Windows users, the following points are somewhat complicated. You also need to install Geth , the command line client. Before starting Mist, you will need to run it on the command line
geth --rinkeby
(instead of the --rinkeby flag, you can use --testnet if you need a Ropsten network, or you can generally omit the flag if you need a main network). From the user interface it will not be possible to change the network or start mining. If you are going to connect and try to mine on Ropsten - run geth with this command.
geth --testnet console 2>nul
In the geth console, you can execute it
miner.setEtherbase("<адрес вашего кошелька>")
and then start it
miner.start(4)
(4 - the number of threads, you can set as many as you like). Keep in mind that it is better to wait for the end of synchronization before you start mining


1. During startup, Mist offers to select a network - Main network or Test network. Select Test network.


To perform any operations on the blockchain, the currency of this network is required, in this case ether. In the Main network, air costs real money, but in the Test network it costs nothing and is easier to get. In addition, before starting all the network data is downloaded to your computer, for testnet Ropsten at the time of writing this article is less than 7 GB, for testnet Rinkeby - 800 MB, for a real network - more than 40 GB. Therefore, for starters, select Testnet. In a real network, you can get ether by buying it on the exchange for real money (at the time of writing this article it is about $ 300), or mine, but this requires quite a lot of power and time. In test networks, the sources vary: this is either mining for Ropsten (receiving from other sources of Ropsten did not work for us), or receiving through sources such as www.rinkeby.io-> Crypto_Faucet for Rinkeby. Mining in Testnet takes significantly less time than in a real network, for example, on an i5 6200u laptop processor we received 5 ethers depending on luck for a couple of hours. The mining speed in this case was about 50 KH / s (50 KH - 50 kiloheshes, or 50,000 hashes per second), you can see it at home and figure out how much time it will take you personally. By the way, having mined several ethers on one client, it will be possible to transfer a part to another without problems, for example, if that miner is slower. It is worth mentioning that in the future we will only use Ropsten, which is a Proof-of-Work network, which is why mining is used in it. In versions of Mist after 0.9, this network is no longer the default network, so if you want to use it, first start Mist by clicking Launch Application. then in the menu item Develop-> Network select the desired network. In general, it should be noted that Rinkeby is more convenient, since it does not require mining, faster and easier, so you will not lose much using it. However, Ropsten is closer to the real network and allows you to feel its features.

2. So, Mist is launched, offers to set a password for your account. A login is not needed, since the private key file is used for identification.


The private key is stored on Linux in the folder ~ / .ethereum / testnet / keystore / for Ropsten, ~ / .ethereum / rinkeby / keystore / for Rinkeby. Please note that separate keys are created for different networks and if you are going to use Ropsten, like us, you will need to create another account. The name consists of the date and time of creation and the address. An address is a hexadecimal string of 20 bytes of the form 0xe03269461f7672494fb0dbbe89c00614601b5d24. In the file name, the initial 0x is omitted. The address is used to identify your account on the blockchain, you can send ether from other accounts to it.

3. As already mentioned, synchronization of the local database is required, it may take a couple of hours or more for testnet Ropsten, but you must wait for the process to complete. Otherwise, there is a chance of getting a desynchronized database.



At least in our case, there was a situation that when mining started, the ether began to gather too fast, but at the same time it was impossible to use it - all operations were not visible to other network participants. The problem was clarified as follows - in the Mist, in the lower left corner, the number of the last block is displayed (or how many blocks remain until the end of synchronization, in this case everything is fine and you just have to wait until the process ends). The number of the last block in the local copy can be compared with the real value for this blockchain, for example, on ropsten.etherscan.ioYou can find out the latest block numbers for the Ropsten network. If your value is much different in the smaller direction - perhaps your database is not synchronized. So what to do if the synchronization in mist has reached the end, but the block number is incorrect? We solved this problem by deleting the data and downloading it again. The data on Linux for the Ropsten network is in the ~ / .ethereum / testnet folder; deleting everything from the chaindata subfolder helped us. After that they started mist and this time patiently waited for the end of synchronization.

4. After synchronization is complete, you can select the menu item Develop-> Start mining. This is necessary in order to get at least a little ether. This is relevant only for the Ropsten network. If you want to use the Rinkeby network, go to www.rinkeby.io, the Crypto Faucet tab, and follow the instructions.


The ether is needed for any data modification operations, it pays for the so-called gas - an abstract unit of measurement that serves to evaluate the required work to complete the transaction. It is needed for the independence of this assessment from the current market value of the ether. When sending a transaction, you can specify how much ether you pay for each unit of gas and the maximum amount of gas that you are willing to pay. The more you allocate, the more priority your transaction is for potential miners. Indeed, in essence, the gas fee is the payment of the work of the miners to complete your transaction and include it in the next block. Therefore, when mining, in addition to a fixed fee for the block found - at the time of writing it is 5 ethers - the miner also receives a transaction fee, usually a few hundredths of the ether. The amount of gas per transaction depends on the computational complexity of data operations. An example of how gas is consumed and estimated is given in the next article.

The simplest Smart Contract


As soon as you have some airtime on your account, you can begin experimenting with smart contracts. The language in which contracts are written - Solidity - resembles C ++ and JavaScript. There are other languages, but Solidity is the most popular, actively supported and well-documented, so we recommend using it. Consider a simple contract whose sole purpose is to store and provide the ability to change a single line.

Contract Code:

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

The string pragma solidity ^0.4.10means that the minimum required compiler for this contract is 0.4.10, and the ^ symbol prohibits the use of the compiler starting from 0.5.0. This is relevant, since Solidity is a developing language and despite the desire of developers to maintain compatibility - this is not always possible.

The name of the contract is specified after the keyword contract. The body of the contract describes all the stored data, in this case this is a savedStringtype field string. Manipulating data is done through setters and getters. In this case, the function setString( string newString )assigns a new value for the string to the contract variable. The function getString() constant returns( string )returns the value of the string (the type of the return value is specified as returns(<тип>)). It is worth noting the keywordconstant- it guarantees that none of the data will be changed during the execution of the function. If the data does not change, then there is no need to pay for gas. Therefore getters are executed instantly and free of charge. Setters require payment and are not executed immediately (only as a result of including the transaction in the next block of the blockchain).

For initial experiments with contracts, the Remix IDE is very convenient . It is enough to copy the given code of the contract and paste it into the window for the code. In the right pane, click Create - a contract will be created without publishing to the blockchain. See the following.



Getters (getString) are marked in blue, setters (setString) are marked in red. It shows how much gas is consumed.

To specify a string in the setString field, do not forget to put quotation marks, otherwise you will get an error

After verifying that get and set are working properly, you can deploy the contract to a real blockchain. To do this, switch back to Mist, go to Contracts and click Deploy New Contract. Copy the code into the Solidity Contract Source Code field and on the right we see the Pick a contract drop-down list. Select StringHolder, the only item in this case. We select the amount of payment on which the deployment time will depend, click Deploy, the approximate cost will be displayed in the window, enter the password for the account and click Send Transaction. A new transaction will appear in the wallet with the progress “x of 12 Confirmations” (x of 12 confirmations). The first confirmation will mean that the transaction is included by the miner in the block, the subsequent ones - that the corresponding number of blocks has been created after the block with our transaction. This gives a great guarantee that the block with our transaction will not be canceled. But in order for the contract to become active, one confirmation is enough. After confirmation, go to Contracts → String Holder. The mist displays the interface of the contract: on the left getters (Read from contract), on the right setters (Write to contract) in the form of a drop-down list. It works the same as in the Remix IDE, only setting the line is a real transaction, which, like creating a contract, will require password confirmation and will wait for 12 confirmations from miners.

How can other users see this contract? The contract is defined by two components: address and ABI interface . All this can be found on the contract page in Mist, using the “Copy address” and “Show Interface” buttons. The address is the same 20-byte hexadecimal number, for example, in our case it is 0x65cA73D13a2cc1dB6B92fd04eb4EBE4cEB70c5eC. And the interface is JSON text, for our smart contract it looks 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" 
} ]

The interface is generated automatically from the contract code and should not change after the deployment, the address of the contract is returned after the deployment and indicates the binary code of the contract. Mist stores this data and provides an interface for retrieving it only if the deploy was performed through it. By the way, the list of completed / executed transactions Mist also stores locally and only if they were committed through its interface.

The client who wants to use the contract should receive this data, and in the case of Mist, select Contracts-> Watch Contract. You can choose any name, it is only for convenience. Clicked OK - the contract appeared in the list, you can go into it and change the line from another client. In this case, after the transaction is completed (at least one confirmation is received), the line will change for all clients.

This example describes a real distributed application where each client downloads the entire blockchain to a computer, which is not very convenient in reality, although it ensures the absence of intermediaries (in fact, Mist is also an intermediary, albeit a reliable one). In reality, you have to compromise: for example, the blockchain node is deployed at a third party, the user is provided with a web interface. Or a special plug-in (such as Metamask) is installed in the browser that uses the user key to sign transactions. In any case, there is a problem of trust in the intermediary. We hope this problem will be solved in the future either through the implementation of a light client protocol that does not require the entire data, or in some other way. In the meantime, you have to work with what is.

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

Also popular now: