Ethereum Tutorial: Building an environment, compiling a smart contract

Source: Internet
Author: User
Tags install homebrew install openssl linux shell commands install node
This Ethereum tutorial mainly introduces: setting up a development environment, writing and compiling a smart contract.

What is Ethereum
Ethereum is an open source public blockchain platform with smart contract functions. Provides a decentralized virtual machine ("Ethereum Virtual Machine"), through its dedicated cryptocurrency Ether, to handle peer-to-peer contracts.

The concept of Ethereum was first proposed by programmer Vitalik Buterin between 2013 and 2014, inspired by Bitcoin, and it was intended to be the "next generation cryptocurrency and decentralized application platform", which began to develop through ICO crowdfunding in 2014. Ethereum is currently the second highest cryptocurrency by market capitalization, after Bitcoin.

What is the Ethereum blockchain?
The Ethereum blockchain has two main components:

Data storage: Every transaction in the network is stored on the blockchain. When you deploy a contract, it is a transaction. When you perform a contract function, it is another transaction. All these transactions are public and can be seen and verified by everyone. This data can never be tampered with. In order to ensure that all nodes in the network have the same copy of data and have not written any invalid data to the blockchain, Ethereum uses an algorithm called proof of work to ensure network security.

Code: As far as data is concerned, the blockchain is storage transactions. In the Ethereum world, you can write logic / application code (aka smart contracts) in a language called Solidity. Then use the solidity compiler to compile the code into Ethereum bytecode and deploy the bytecode to the blockchain (There are also some other languages that can write contracts, but solidity is by far the most used and relatively easy select). Therefore, Ethereum will not only store transaction data, it will also store and execute smart contract code.

It can be simply understood that the role of the Ethereum blockchain is to store data and code, and execute the code in the EVM (Ethereum Virtual Machine, Ethereum Virtual Machine).

The basics to prepare
For Ethereum development, you should have a basic understanding of the following languages / techniques:

Familiar with some object-oriented languages (such as Python, Java, go)
HTML / CSS / Javascript
Basic command line interactions such as Linux shell commands
Understand the basic concepts of databases
In order to build a decentralized application (Dapp) for Ethereum, Ethereum has a very convenient JavaScript library, web3.js. You can also directly introduce this library in some js frameworks to build applications, such as react, angular, and vue Wait.

Example: An Ethereum voting application
In the Ethereum tutorial example, we will build a simple decentralized voting application. The so-called decentralized application is an application that does not exist only on a centralized server. On hundreds or thousands of computers on the network, there will be a lot of application copies running, which makes it almost impossible for it to go down. You will build a voting application. In this application, you can initialize the candidates participating in the election and vote on the candidates, and these votes will be recorded on the blockchain. You will go through the process of writing a voting contract, deploying it to the blockchain and interacting with it. You will learn what a contract is and what it means to deploy and interact with the blockchain.

In essence, the blockchain is like a distributed database that maintains a growing list of records. If you are familiar with relational databases, you should know that there are many rows of data in a table. Now batch the data (for example, 100 rows per batch) and connect each processed batch. You can form a blockchain! In the blockchain, each batch of data is called a block, and each row in the block is called a transaction.

Now that you have a basic understanding of Ethereum, we can start building voting dapps. This will strengthen your understanding of Ethereum and give you a brief understanding of the features of Ethereum.

Ethereum development environment setup
Linux
The example is a learning environment setup under Ubuntu 16.04. You only need to successfully install nodejs and npm to continue the next step of the project.

We install ganache and web3 packages via npm to support the Ethereum tutorial. We also need to install solc to compile the contract.

Here is the installation process:

$ sudo apt-get update
$ curl -sL https://deb.nodesource.com/setup_7.x -o nodesource_setup.sh
$ sudo bash nodesource_setup.sh
$ sudo apt-get install nodejs
$ node --version
v7.4.0
$ npm --version
4.0.5
$ mkdir -p ethereum_voting_dapp / chapter1
$ cd ethereum_voting_dapp / chapter1
$ npm install ganache-cli web3@0.20.1 solc
$ node_modules / .bin / ganache-cli
If the installation is successful, run the command node_modules / .bin / ganache-cli and you should see the following output.

Ganache CLI v6.0.3 (ganache-core: 2.0.2)

Available Accounts
===================
(0) 0x5c252a0c0475f9711b56ab160a1999729eccce97
(1) 0x353d310bed379b2d1df3b727645e200997016ba3
(2) 0xa3ddc09b5e49d654a43e161cae3f865261cabd23
(3) 0xa8a188c6d97ec8cf905cc1dd1cd318e887249ec5
(4) 0xc0aa5f8b79db71335dacc7cd116f357d7ecd2798
(5) 0xda695959ff85f0581ca924e549567390a0034058
(6) 0xd4ee63452555a87048dcfe2a039208d113323790
(7) 0xc60c8a7b752d38e35e0359e25a2e0f6692b10d14
(8) 0xba7ec95286334e8634e89760fab8d2ec1226bf42
(9) 0x208e02303fe29be3698732e92ca32b88d80a2d36

Private Keys
===================
(0) a6de9563d3db157ed9926a993559dc177be74a23fd88ff5776ff0505d21fed2b
(1) 17f71d31360fbafbc90cad906723430e9694daed3c24e1e9e186b4e3ccf4d603
(2) ad2b90ce116945c11eaf081f60976d5d1d52f721e659887fcebce5c81ee6ce99
(3) 68e2288df55cbc3a13a2953508c8e0457e1e71cd8ae62f0c78c3a5c929f35430
(4) 9753b05bd606e2ffc65a190420524f2efc8b16edb8489e734a607f589f0b67a8
(5) 6e8e8c468cf75fd4de0406a1a32819036b9fa64163e8be5bb6f7914ac71251cc
(6) c287c82e2040d271b9a4e071190715d40c0b861eb248d5a671874f3ca6d978a9
(7) cec41ef9ccf6cb3007c759bf3fce8ca485239af1092065aa52b703fd04803c9d
(8) c890580206f0bbea67542246d09ab4bef7eeaa22c3448dcb7253ac2414a5362a
(9) eb8841a5ae34ff3f4248586e73fcb274a7f5dd2dc07b352d2c4b71132b3c73f0

HD Wallet
===================
Mnemonic: cancel better shock lady capable main crunch alcohol derive alarm duck umbrella
Base HD Path: m / 44 '/ 60' / 0 '/ 0 / {account_index}

Listening on localhost: 8545
For testing purposes, ganache creates 10 accounts by default, each account has 100 ether. If you don't know what an account is, just think of it as a bank account for saving money (Ether (ETH) is money / currency in the Ethereum ecosystem). You need to use this account to create transactions and send / receive ether.

MacOS
If you haven't installed homebrew, follow the instructions at https://brew.sh/ to install homebrew. homebrew is a package manager that helps us install all the other software we need for development. Follow the instructions below to install all other required packages.

$ brew update
$ brew install nodejs
$ node --version
v7.10.0
$ npm --version
4.2.0
$ mkdir -p ethereum_voting_dapp / chapter1
$ cd ethereum_voting_dapp / chapter1
$ npm install ganache-cli web3@0.20.1 solc
$ node_modules / .bin / ganache-cli
We install ganache and web3 packages via npm. We also need to install solc to compile the contract.

If the installation is successful, run the command node_modules / .bin / ganache-cli and you should be able to see the output shown on the right.

Ganache CLI v6.0.3 (ganache-core: 2.0.2)
Available Accounts
===================
(0) 0x5c252a0c0475f9711b56ab160a1999729eccce97
(1) 0x353d310bed379b2d1df3b727645e200997016ba3
(2) 0xa3ddc09b5e49d654a43e161cae3f865261cabd23
(3) 0xa8a188c6d97ec8cf905cc1dd1cd318e887249ec5
(4) 0xc0aa5f8b79db71335dacc7cd116f357d7ecd2798
(5) 0xda695959ff85f0581ca924e549567390a0034058
(6) 0xd4ee63452555a87048dcfe2a039208d113323790
(7) 0xc60c8a7b752d38e35e0359e25a2e0f6692b10d14
(8) 0xba7ec95286334e8634e89760fab8d2ec1226bf42
(9) 0x208e02303fe29be3698732e92ca32b88d80a2d36

Private Keys
===================
(0) a6de9563d3db157ed9926a993559dc177be74a23fd88ff5776ff0505d21fed2b
(1) 17f71d31360fbafbc90cad906723430e9694daed3c24e1e9e186b4e3ccf4d603
(2) ad2b90ce116945c11eaf081f60976d5d1d52f721e659887fcebce5c81ee6ce99
(3) 68e2288df55cbc3a13a2953508c8e0457e1e71cd8ae62f0c78c3a5c929f35430
(4) 9753b05bd606e2ffc65a190420524f2efc8b16edb8489e734a607f589f0b67a8
(5)
6e8e8c468cf75fd4de0406a1a32819036b9fa64163e8be5bb6f7914ac71251cc
(6) c287c82e2040d271b9a4e071190715d40c0b861eb248d5a671874f3ca6d978a9
(7) cec41ef9ccf6cb3007c759bf3fce8ca485239af1092065aa52b703fd04803c9d
(8) c890580206f0bbea67542246d09ab4bef7eeaa22c3448dcb7253ac2414a5362a
(9) eb8841a5ae34ff3f4248586e73fcb274a7f5dd2dc07b352d2c4b71132b3c73f0

HD Wallet
===================
Mnemonic: cancel better shock lady capable main crunch alcohol derive alarm duck umbrella
Base HD Path: m / 44 '/ 60' / 0 '/ 0 / {account_index}

Listening on localhost: 8545
For testing purposes, ganache creates 10 accounts by default, each account has 100 ether. If you don't know what an Ethereum account is, just think of it as a bank account for saving money (Ether (ETH) is money / currency in the Ethereum ecosystem). You need to use this account to create transactions and send / receive ether.

Windows
Install Visual Studio Community Edition. If you choose a custom installation, then at least Visual C ++ should be installed (current version is VS 2017)
Install the Windows SDK for Windows
Install Python 2.7 if you haven't already, and make sure to add it to the environment variable PATH
Install git if you haven't already installed and added to your PATH
Install OpenSSL. Make sure you select the correct installation package and only install the full version (not the light version). You must install OpenSSL to the recommended installation location-do not change the installation path
Download and install node v8.1.2. Deprecated version v6.11.0 with VS2017
Execute the command npm install ganache-cli web3@0.20.1 solc
Solidity Contracts
Now that ganache is installed and running, we will start writing the first Ethereum smart contract.

We write contracts using the solidity programming language. If you are familiar with object-oriented programming, learning to write contracts in solidity should be very simple. We will write a contract called Voting (you can think of a contract as a class of object-oriented programming language). This contract has the following contents:

A constructor to initialize some candidates.
A method for voting (plus 1 to the number of votes)
A method that returns the total votes received by the candidate
When you deploy a contract to the blockchain, the constructor is called and called only once. Unlike the old code that is overwritten every time code is deployed in the web world, contracts deployed on the blockchain are immutable, that is, if you update the contract and deploy it again, the old contract will still exist on the blockchain And the data is still there. The new deployment will create a new instance of the contract.

pragma solidity ^ 0.4.18;

contract Voting {

  mapping (bytes32 => uint8) public votesReceived;
  bytes32 [] public candidateList;

  function Voting (bytes32 [] candidateNames) public {
    candidateList = candidateNames;
  }

  function totalVotesFor (bytes32 candidate) view public returns (uint8) {
    require (validCandidate (candidate));
    return votesReceived [candidate];
  }

  function voteForCandidate (bytes32 candidate) public {
    require (validCandidate (candidate));
    votesReceived [candidate] + = 1;
  }

  function validCandidate (bytes32 candidate) view public returns (bool) {
    for (uint i = 0; i <candidateList.length; i ++) {
      if (candidateList [i] == candidate) {
        return true;
      }
    }
    return false;
   }
}
Copy the code on the right into a file called Voting.sol and save it under the chapter1 directory.

Code and explanation

Line 1. We must specify which version of the compiler the code will compile
Line 3. mapping is equivalent to an associative array or dictionary, a key-value pair. The keys of the mapping votesReceived are the names of the candidates, of type bytes32. The value of mapping is an unassigned integer and stores the number of votes.
Line 4. In many programming languages, you can get all candidate names with votesReceived.keys. However, there is no such method in solidity, so we must manage a candidate array candidateList separately.
Line 14. Notice that votesReceived [key] has a default value of 0, so you don't need to initialize it to 0, just add 1 to it.
You will also notice that each function has a visibility specifier (such as public in this example). This means that functions can be called from outside the contract. If you don't want anyone else to call this function, you can set it to a private function. If you don't specify visibility, the compiler will throw a warning. Recently, the solidity compiler has made some improvements. If the user forgets to mark the private function and the private function can be called externally, the compiler will catch this problem. Here you can see all the visibility specifiers.

You will also see a modifier view on some functions. It is usually used to tell the compiler that a function is read-only (that is, the state of the blockchain is not updated when the function is called). All modifiers can be seen here.

Compile smart contract
We will use the solc library installed in the previous section to compile the code. If you remember, we mentioned earlier that web3js is a library that allows you to interact with the blockchain via RPC. We will use this library to deploy contracts in the node console and interact with the blockchain.

First, run node in the terminal to enter the node console, initialize the web3 object, and query the blockchain to obtain all accounts.

Make sure at the same time ganache is already running in another window

To compile the contract, first load the code from Voting.sol and bind it to a variable of type string, and then compile the contract like this.

$ node

In the node console
Web3 = require ('web3')
web3 = new Web3 (new Web3.providers.HttpProvider ("http: // localhost: 8545"));
web3.eth.accounts
['0x5c252a0c0475f9711b56ab160a1999729eccce97'
'0x353d310bed379b2d1df3b727645e200997016ba3'
'0xa3ddc09b5e49d654a43e161cae3f865261cabd23'
'0xa8a188c6d97ec8cf905cc1dd1cd318e887249ec5'
'0xc0aa5f8b79db71335dacc7cd116f357d7ecd2798'
'0xda695959ff85f0581ca924e549567390a0034058'
'0xd4ee63452555a87048dcfe2a039208d113323790'
'0xc60c8a7b752d38e35e0359e25a2e0f6692b10d14'
'0xba7ec95286334e8634e89760fab8d2ec1226bf42'
'0x208e02303fe29be3698732e92ca32b88d80a2d36']


code = fs.readFileSync ('Voting.sol'). toString ()
solc = require ('solc')
compiledCode = solc.compile (code)
When you successfully compile the contract and print the compiledCode object (you can see the content by typing compiledCode directly in the node console), you will notice that there are two important fields. They are important. You must understand:

1.compiledCode.contracts [': Voting']. Bytecode: This is the bytecode compiled by Voting.sol. It is also the code to be deployed on the blockchain.
2.compiledCode.contracts [': Voting']. Interface: This is a contract interface or template (called an abi definition) that tells the user what methods are in this contract. In the future, whenever you want to interact with any contract, you will need this abi definition. You can see more of the ABI here.
For the tutorial, refer to the DAPP development introductory tutorial of Huizhi. If you can't wait for the blog to update, you can also directly access this Ethereum tutorial. 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.