📜 ⬆️ ⬇️

Dive into Ethereum development. Part 1

The blockchain technology has captured the minds. Farms are bought , ICO collect millions of dollars. Our company also wanted to join. We decided to start small. In a series of articles we will describe our way from newbies in the blockchain field to generally recognized gurus. At the time of writing these words, we are still at the novice stage, we offer to monitor our development and develop with us.


What good is the blockchain?


Judging from the name, the blockchain is a chain of blocks. And there is. But what does this chain give? In essence, this is a decentralized data storage technology with a special structure that allows you to be sure that data manipulations took place within the framework of clearly defined rules. This confidence is ensured by the fact that the data array is stored at once for all who have connected to the blockchain's network - this means that it will not be enough just to replace the entire array in one place. And each subsequent piece of data, the so-called block, contains the hash of the previous block, this gives two advantages:



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

Work on adding blocks provide themselves network members. Who will be given the right to add the next block is determined by a special mechanism. The most common of these mechanisms is Proof-of-Work and Proof-of-Stake. In the first block, miners are added - network participants solving computationally complex problems, competing with each other for the right to create a block based on their decision, and as a reward for successfully creating a block receiving a certain amount of currency of this network. In Proof-of-Stake, blocks are added by validators that are participants in the network, competing not at the expense of performance, but on the basis of the amount of the local 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 the attacker to add a fake block will have to spend more than it can earn. In the first case - on the equipment for mining, comparable in power with the other miners together. In the second case - the purchase of 50% of the network currency.
')

Ethereum


There are different implementations of blockchains, among which the most popular now 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 tasks using smart contracts. Therefore, it is logical to start the first acquaintance with Ethereum

Smart contracts


The manipulation of data in the blockchain is provided by so-called smart contracts. They describe what data to store on the blockchain and a set of functions for operations on them. Functions and access to data are performed through the interface provided by each contract. This interface is generated from the source code separately from the compilation and allows the binary code to be executed. The data for the network participants are open, and reading them is worth nothing, because, as has already been said, the data is stored with all network participants. Data change occurs through transactions. Each transaction can be represented by the following structure:

  1. Transaction recipient
  2. Digital signature of the sender
  3. Amount of the sent currency
  4. Arbitrary data (optional)
  5. Gas limit per transaction
  6. Price per unit of gas

What is gas from points 5 and 6 will be discussed in the following points and even more fully described in a separate article.

Transaction execution requires local currency costs and waiting for the next miner’s block with your transaction to join the common 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 written as App, but we will use simplified spelling. The application can be built on different technologies, but among them there is a blockchain with smart contracts. We can say that at the moment DApp is the logic on smart contracts plus a certain user interface. Storing more or less voluminous data and messaging in an ideal DApp should also be decentralized, but these technologies are just beginning to appear and deserve a separate article. Blockchain, on the other hand, provides storage of the current state and implements business logic through smart contracts.
image

The ideal to which the development of decentralized applications. Picture borrowed 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 familiar mobile and web applications. The choice depends on the specific task. A simplified version of DApp can be represented in this form:


The picture was taken and transferred 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 can access the standard features of the virtual machine — such as sending a transaction or viewing the account balance — as well as the features described in smart contracts, for example, in the solidity language. Access to this virtual machine is provided through the RPC interface.

The creation of distributed applications should, in our opinion, become quite a sought-after area, as they allow to solve many problems: lack of confidence in the data keeper, servers in centralized systems that are vulnerable to attack, closure of systems.

The first connection to the blockchain


In order to somehow see what it means to be a member of the network, we downloaded Mist (at the time of this writing, the latest version numbered 0.9.0) is an Ethereum wallet. The Mist wallet is called because it allows you to manage your accounts and their balance. 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 Ethereum-blockchain. It allows you to upload and use smart contracts, as well as use DApp-applications.

For clarity of work with the blockchain, we recommend using a couple of clients on different computers: you can see that the created data is not only available 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. You will need to run the command line before running Mist.
geth --rinkeby
(instead of the --rinkeby flag, you can use --testnet if you need a Ropsten network, or omit the flag altogether, if you need a main network). From the user interface, it is no longer 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 run
miner.setEtherbase("< >")
then run
miner.start(4)
(4 - the number of threads, you can set as you want). Keep in mind that it is better to wait until the end of synchronization before starting mining


1. During startup, Mist prompts you to select a network — the 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 the broadcast costs real money, but in the Test network it costs nothing and is easier to receive. In addition, before launching, all network data is downloaded to your computer, at the time of writing this article is less than 7 GB for testnet Ropsten, 800 MB for testnet Rinkeby, and more than 40 GB for a real network. Therefore, to start, choose Testnet. In a real network, you can get broadcast by buying it on the stock exchange for real money (at the time of this writing, it is about $ 300), or it can be fixed, but this requires quite a lot of power and time. In test networks, sources vary: this is either mining for Ropsten (getting Ropsten from other sources did not work for us), or receiving through such sources 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 airs, depending on luck, in a couple of hours. The mining speed in this case was about 50 KH / s (50 KH - 50 kiloeshes, or 50,000 hashes per second), you can see it in yourself and estimate how long it will take you personally. By the way, by naming several ethers on one client, it will be possible to transfer part to another without problems, for example, if that mine is slower. It is worth mentioning that in the future we will use only Ropsten, which is the Proof-of-Work network, therefore mining is used in it. In Mist versions 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 select the required network in the menu item Develop-> Network. In general, it should be noted that Rinkeby is more convenient, as it does not require mining, it is 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, running Mist, offers to set a password for your account. Login is not needed, as the private key file is used for identification.


The private key is stored on Linux in the ~ / .ethereum / testnet / keystore / folder for Ropsten, ~ / .ethereum / rinkeby / keystore / - for Rinkeby. Please note that for different networks separate keys are created and if you are going to use Ropsten, as we do, then you will need to create another account. The name consists of the date and time of creation and 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 in the blockchain, you can send ether to it from other accounts.

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 need to wait for the process to complete. Otherwise, there is a chance to get a desynchronized database.



At least in our case there was a situation that when the mining was started, the ether began to gain too fast, but it was impossible to use it - all operations were not visible to other participants of the network. The problem was clarified as follows - the number of the last block is displayed in Mist in the lower left corner (or how many blocks remain until the end of synchronization, in this case everything is fine and you just need to wait for the process to finish). The number of the last block in the local copy can be compared with the actual value for this blockchain. For example, on ropsten.etherscan.io you can find out the latest block numbers for the Ropsten network. If your value is much different downwards - perhaps your base is not synchronized. So, what to do if the synchronization in mist reached the end, but the block number is wrong? 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, and the removal of everything from the chaindata subfolder helped us. After that, they started mist and already 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 only relevant 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 broadcast is needed for any operations to change data, they are paid for the so-called gas - an abstract unit of measure, which serves to assess the work required to complete the transaction. It is necessary for the independence of this assessment from the current market value of the air. When sending a transaction, you can specify how much air you pay for each unit of gas and the maximum amount of gas you are willing to pay. The more you allocate - the more priority your transaction is for potential miners. After all, in essence, the payment for gas is the payment for the work of 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 airs - the miner also receives payment for transactions, usually it is a few hundredths of aired. The amount of gas per transaction depends on the computational complexity of operations on data. We will give an example of how gas is consumed and estimated in the next article.

Simplest Smart Contract


As soon as you have some amount of air on your account, you can start experimenting with smart contracts. The language in which contracts are written — Solidity — recalls 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.10 means that the minimum required compiler for this contract is 0.4.10, and the ^ character prohibits the use of a compiler starting from 0.5.0. This is relevant, since Solidity is a developing language and despite the desire of developers to maintain compatibility - it is not always possible.

The contract name is given after the keyword contract . The body of the contract describes all the stored data, in this case, the savedString field of type string . Data manipulations are carried out through setters and getters. In this case, the setString( string newString ) function setString( string newString ) assigns a new value for the string to the contract variable. The getString() constant returns( string ) function getString() constant returns( string ) returns the string value (the return value type is specified as returns(<>) ). Of particular note is the constant keyword - it guarantees that none of the data will be altered when the function is executed. If the data does not change - then you do not need to pay for gas. Therefore, getters are executed instantly and for free. Setters require payment and are not instantly executed (only as a result of the inclusion of a transaction in the next blockchain block).

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



Getters (getString) are marked with blue, setters (setString) are marked with red. Shows how much gas is consumed.

To set a string in the setString field, do not forget to put quotes, otherwise you will get an error

Checking that get and set work as it should be possible to deploy a contract to a real blockchain. To do this, switch back to Mist, go to Contracts and click Deploy New Contract. We copy the code in the Solidity Contract Source Code field and on the right we see the drop-down list Pick a contract. Select StringHolder, the only item in this case. Select the amount of payment on which the deployment time will depend, click Deploy, the approximate cost will appear in the window, enter the password for the account and click Send Transaction. A new transaction will appear in the wallet with the progress of “x of 12 Confirmations” (x out 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 is 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 contract interface: the left getters (Read from contract), the right setters (Write to contract) in the form of a drop-down list. It works the same way as in Remix IDE, only setting the string is a real transaction, which, like creating a contract, will require confirmation with a password and will wait for 12 confirmations from miners.

How do other users see this contract? The contract is defined by two components: the address and the 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 be changed after the deployment, the contract address is returned after the deployment and points to the binary contract code. Mist saves this data and provides an interface for obtaining it only if it was deployed through it. By the way, the list of executed / executed transactions Mist also stores locally and only if they were performed through its interface.

A client who wants to use a contract must receive this data, and in the case of Mist, select Contracts-> Watch Contract. You can choose any name, it is necessary only for convenience. Clicked OK - the contract appeared in the list, you can go into it and change the line already from another client. In this case, after completing the transaction (receiving at least one confirmation), 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, though reliable). In reality, you have to make a compromise: for example, the blockchain node is deployed by a third party, the user is provided with a web interface. Or, a special plugin (such as Metamask) is installed in the browser, which uses the user's key to sign transactions. In any case, there is the problem of trust in the intermediary. We hope in the future this problem will be solved either by implementing the light client protocol, which does not require the data as a whole, or in some other way. For now it is necessary to work with what is.

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

Source: https://habr.com/ru/post/336132/


All Articles