दुर्गा बेरागी Durga Beragi, homeEnter the study →

Library › Cryptography, blockchain and crypto › Mastering Ethereum › Full text

Mastering Ethereum

Andreas M. Antonopoulos and Gavin Wood, 2018 · part 17 of 17 · 111,220 words

Openly licensed edition · source: GitHub (ethereumbook/ethereumbook, openedition branch) · CC-BY-SA-4.0

ZeppelinOS

GitHhub: https://github.com/zeppelinos

Website: https://zeppelinos.org

Blog: https://blog.zeppelinos.org

ZeppelinOS is “an open source, distributed platform of tools and services on top of the EVM to develop and manage smart contract applications securely.”

Unlike OpenZeppelin's code, which needs to be redeployed with each application every time it's used, ZeppelinOS's code lives on-chain. Applications that need a given functionality—say, an ERC20 token—not only do not have to redesign and reaudit its implementation (something that OpenZeppelin solved) but do not even need to deploy it. With ZeppelinOS, an application interacts with the token's on-chain implementation directly, in much the same way as a desktop application interacts with the components of its underlying OS.

At the core of ZeppelinOS sits a very clever contract known as a proxy. A proxy is a contract that is capable of wrapping any other contract, exposing its interface without having to manually implement setters and getters for it, and can upgrade it without losing state. In Solidity terms, it can be seen as a normal contract whose business logic is contained within a library, which can be swapped for a new library at any time without losing its state. The way in which the proxy links to its implementation is completely automated and encapsulated for the developer. Practically any contract can be made upgradeable with little to no change in its code. More about ZeppelinOS's proxy mechanism can be found in the blog, and an example of how to use it can be found on GitHub.

Developing applications using ZeppelinOS is similar to developing JavaScript applications using npm. An AppManager handles an application package for each version of the application. A package is simply a directory of contracts, each of which can have one or more upgradeable proxies. The AppManager not only provides proxies for application-specific contracts, but also does so for ZeppelinOS implementations, in the form of a standard library. To see a full example of this, please visit examples/complex.

Although currently in development, ZeppelinOS aims to provide a wide set of additional features, such as developer tools, a scheduler that automates background operations within contracts, development bounties, a marketplace that facilitates communication and exchange of value between applications, and much more. All of this is described in ZeppelinOS's whitepaper.

Utilities

EthereumJS helpeth: A Command-Line Utility

GitHub: https://github.com/ethereumjs/helpeth

helpeth is a command-line tool for key and transaction manipulation that makes a developer's job a lot easier.

It is part of the EthereumJS collection of JavaScript-based libraries and tools:

Usage: helpeth [command] Commands: signMessage <message> Sign a message verifySig <hash> <sig> Verify signature verifySigParams <hash> <r> <s> <v> Verify signature parameters createTx <nonce> <to> <value> <data> Sign a transaction <gasLimit> <gasPrice> assembleTx <nonce> <to> <value> <data> Assemble a transaction from its <gasLimit> <gasPrice> <v> <r> <s> components parseTx <tx> Parse raw transaction keyGenerate [format] [icapdirect] Generate new key keyConvert Convert a key to V3 keystore format keyDetails Print key details bip32Details <path> Print key details for a given path addressDetails <address> Print details about an address unitConvert <value> <from> <to> Convert between Ethereum units Options: -p, --private Private key as a hex string [string] --password Password for the private key [string] --password-prompt Prompt for the private key password [boolean] -k, --keyfile Encoded key file [string] --show-private Show private key details [boolean] --mnemonic Mnemonic for HD key derivation [string] --version Show version number [boolean] --help Show help [boolean]

dapp.tools

Website: https://dapp.tools/

dapp.tools is a comprehensive suite of blockchain-oriented developer tools created in the spirit of the Unix philosophy. The tools included are:

  • Dapp: Dapp is the basic user-facing tool, for creating new DApps, running Solidity unit tests, debugging and deploying contracts, launching testnets, and more.
  • Seth: Seth is used for composing transactions, querying the blockchain, converting between data formats, performing remote calls, and similar everyday tasks.
  • Hevm: Hevm is a Haskell EVM implementation with a nimble terminal-based Solidity debugger. It’s used to test and debug DApps.
  • evmdis: evmdis is an EVM disassembler; it performs static analysis on the bytecode to provide a higher level of abstraction than raw EVM operations.

SputnikVM

SputnikVM is a standalone pluggable virtual machine for different Ethereum-based blockchains. It's written in Rust and can be used as a binary, cargo crate, or shared library, or integrated through FFI, Protobuf, and JSON interfaces. It has a separate binary, sputnikvm-dev, intended for testing purposes, which emulates most of the JSON-RPC API and block mining.

Libraries

web3.js

web3.js is the Ethereum-compatible JavaScript API for communicating with clients via JSON-RPC, developed by the Ethereum Foundation.

GitHub: https://github.com/ethereum/web3.js

npm package repository: https://www.npmjs.com/package/web3

Documentation for web3.js API 0.2x.x: http://bit.ly/2Qcyq1C

Documentation for web3.js API 1.0.0-beta.xx: http://bit.ly/2CT33p0

web3.py

web3.py is a Python library for interacting with the Ethereum blockchain, maintained by the Ethereum Foundation.

GitHub: https://github.com/ethereum/web3.py

PyPi: https://pypi.python.org/pypi/web3/4.0.0b9

Documentation: https://web3py.readthedocs.io/

EthereumJS

EthereumJS is collection of libraries and utilities for Ethereum.

GitHub: https://github.com/ethereumjs

Website: https://ethereumjs.github.io/

web3j

web3j is a Java and Android library for integrating with Ethereum clients and working with smart contracts.

GitHub: https://github.com/web3j/web3j

Website: https://web3j.io

Documentation: https://docs.web3j.io

EtherJar

EtherJar is another Java library for integrating with Ethereum and working with smart contracts. It's designed for server-side projects based on Java 8+ and provides low-level access and a high-level wrapper around RPC, Ethereum data structures, and smart contract access.

GitHub: https://github.com/infinitape/etherjar

Nethereum

Nethereum is the .Net integration library for Ethereum.

GitHub: https://github.com/Nethereum/Nethereum

Website: http://nethereum.com/

Documentation: https://nethereum.readthedocs.io/en/latest/

ethers.js

The ethers.js library is a compact, complete, full-featured, extensively tested MIT-licensed Ethereum library, which has received a DevEx grant from the Ethereum Foundation toward its extension and maintenance.

GitHub link: https://github.com/ethers-io/ethers.js

Documentation: https://docs.ethers.io

Emerald Platform

Emerald Platform provides libraries and UI components to build DApps on top of Ethereum. Emerald JS and Emerald JS UI provide sets of modules and React components to build JavaScript applications and websites; Emerald SVG Icons is a set of blockchain-related icons. In addition to JavaScript libraries Emerald has a Rust library to operate private keys and transaction signatures. All Emerald libraries and components are licensed under the Apache License, version 2.0.

GitHub: https://github.com/etcdevteam/emerald-platform

Documentation: https://docs.etcdevteam.com

Testing Smart Contracts

There are several commonly used test frameworks for smart contract development, summarized in Smart contract test frameworks summary:

Smart contract test frameworks summary

  • Framework — Test language(s) — Testing framework — Chain emulator — Website — Truffle — JavaScript/Solidity — Mocha — TestRPC/Ganache — https://trufflesuite.com/ — Embark — JavaScript — Mocha — TestRPC/Ganache — https://embark.status.im/docs/ — Dapp — Solidity — ds-test (custom) — ethrun (Parity) — https://dapp.tools/dapp/ — Populus — Python — pytest — Python chain emulator — https://populus.readthedocs.io
  • Truffle: Truffle allows for unit tests to be written in JavaScript (Mocha-based) or Solidity. These tests are run against Ganache.
  • Embark: Embark integrates with Mocha to run unit tests written in JavaScript. The tests are in turn run against contracts deployed on Ganache (formerly called TestRPC). The Embark framework automatically deploys smart contracts, and will automatically redeploy the contracts when they are changed. It also keeps track of deployed contracts and deploys contracts only when truly needed. Embark includes a testing library to rapidly run and test your contracts in an EVM, with functions like assert.equal. The command embark test will run any test files under the directory test.
  • Dapp: Dapp uses native Solidity code (a library called ds-test) and a Parity-built Rust library called ethrun to execute Ethereum bytecode and then assert correctness. The ds-test library provides assertion functions for validating correctness and events for logging data in the console. + The assertion functions include: + ---- assert(bool condition) assertEq(address a, address b) assertEq(bytes32 a, bytes32 b) assertEq(int a, int b) assertEq(uint a, uint b) assertEq0(bytes a, bytes b) expectEventsExact(address target) ---- + The logging commands will log information to the console, making them useful for debugging: + ---- logs(bytes) log_bytes32(bytes32) log_named_bytes32(bytes32 key, bytes32 val) log_named_address(bytes32 key, address val) log_named_int(bytes32 key, int val) log_named_uint(bytes32 key, uint val) log_named_decimal_int(bytes32 key, int val, uint decimals) log_named_decimal_uint(bytes32 key, uint val, uint decimals) ----
  • Populus: Populus uses Python and its own chain emulator to run contracts written in Solidity. Unit tests are written in Python with the pytest library. Populus supports writing contracts specifically for testing. These contract filenames should match the glob pattern Test*.sol and be located anywhere under the project tests directory, tests.

On-Blockchain Testing

Although most testing shouldn't occur on deployed contracts, a contract's behavior can be checked via Ethereum clients. The following commands can be used to assess a smart contract's state. These commands should be typed at the geth terminal, although any web3 console will also support them.

To get the address of a contract at txhash, use:

web3.eth.getTransactionReceipt(txhash);

This command gets the code of a contract deployed at contractaddress; this can be used to verify proper deployment:

web3.eth.getCode(contractaddress)

This gets the full logs of the contract located at the address specified in options, which is helpful for viewing the history of a contract's calls:

web3.eth.getPastLogs(options)

Finally, this command gets the storage located at address with an offset of position:

web3.eth.getStorageAt(address, position)

Ganache: A Local Test Blockchain

Ganache is a local test blockchain that you can use to deploy contracts, develop your applications, and run tests. It is available as a desktop application (with a graphical user interface) for Windows, macOS, and Linux. It is also available as a command-line utility called ganache-cli. For more details and installation instructions for the Ganache desktop application, see https://trufflesuite.com/ganache.

The ganache-cli code can be found at https://github.com/trufflesuite/ganache-cli/.

To install the command line ganache-cli, use npm:

$ npm install -g ganache-cli

You can use ganache-cli to start a local blockchain for testing as follows:

$ ganache-cli \ --networkId=3 \ --port="8545" \ --verbose \ --gasLimit=8000000 \ --gasPrice=4000000000;

A few notes on this command line:

  • [ ] Check the --networkId and --port flag values match your configuration in truffle-config.js.
  • [ ] Check the --gasLimit flag value matches the latest mainnet gas limit (e.g., 8,000,000 gas) shown at https://ethstats.net to avoid encountering “out of gas” exceptions unnecessarily. Note that a --gasPrice of 4000000000 represents a gas price of 4 gwei.
  • [ ] You can optionally enter a --mnemonic flag value to restore a previous HD wallet and associated addresses.

web3.js Tutorial

Description

This tutorial is based on [email protected] web3.js. It is intended as an introduction to web3.js.

The web3.js JavaScript library is a collection of modules that contain specific functionality for the Ethereum ecosystem, together with an Ethereum-compatible JavaScript API that implements the Generic JSON RPC spec.

To run this script you don’t need to run your own local node, because it uses the Infura services.

web3.js Contract Basic Interaction in a Nonblocked (Async) Fashion

Check you have a valid npm version:

$ npm -v 5.6.0

If you haven't, initialize npm:

$ npm init

Install basic dependencies:

$ npm i command-line-args $ npm i web3 $ npm i node-rest-client-promise

This will update your package.json configuration file with your new dependencies.

Node.js Script Execution

Basic execution:

$ node code/web3js/web3-contract-basic-interaction.js

Use your own Infura token (register at https://infura.io/ and store the api-key in a local file called __infura_token__):

$ node code/web3js/web3-contract-basic-interaction.js \ --infuraFileToken /path/to/file/with/infura_token

or:

$ node code/web3js/web3-contract-basic-interaction.js \ /path/to/file/with/infura_token

This will read the file with your own token and pass it in as a command-line argument to the actual command.

Reviewing the Demo Script

Next, let's review our demo script, web3-contract-basic-interaction.

We use the Web3 object to obtain a basic web3 provider:

var web3 = new Web3(infura_host);

We can then interact with web3 and try some basic functions. Let's see the protocol version:

web3.eth.getProtocolVersion().then(function(protocolVersion) { console.log(`Protocol Version: ${protocolVersion}`); })

Now let's look at the current gas price:

web3.eth.getGasPrice().then(function(gasPrice) { console.log(`Gas Price: ${gasPrice}`); })

What's the last mined block in the current chain?

web3.eth.getBlockNumber().then(function(blockNumber) { console.log(`Block Number: ${blockNumber}`); })

Contract Interaction

Now let's try some basic interactions with a contract. For these examples, we'll use the WETH9_ contract on the Kovan testnet.

First, let's initialize our contract address:

var our_contract_address = "0xd0A1E359811322d97991E03f863a0C30C2cF029C";

We can then look at its balance:

web3.eth.getBalance(our_contract_address).then(function(balance) { console.log(`Balance of ${our_contract_address}: ${balance}`); })

and see its bytecode:

web3.eth.getCode(our_contract_address).then(function(code) { console.log(code); })

Next, we'll prepare our environment to interact with the Etherscan explorer API.

Let's initialize our contract URL in the Etherscan explorer API for the Kovan chain:

var etherscan_url = "https://kovan.etherscan.io/api?module=contract&action=getabi& address=${our_contract_address}"

And let's initialize a REST client to interact with the Etherscan API:

var client = require('node-rest-client-promise').Client();

and get a client promise:

client.getPromise(etherscan_url)

Once we've got a valid client promise, we can get our contract ABI from the Etherscan API:

.then((client_promise) => { our_contract_abi = JSON.parse(client_promise.data.result);

And now we can create our contract object as a promise to consume later:

return new Promise((resolve, reject) => { var our_contract = new web3.eth.Contract(our_contract_abi, our_contract_address); try { // If all goes well resolve(our_contract); } catch (ex) { // If something goes wrong reject(ex); } }); })

If our contract promise returns successfully, we can start interacting with it:

.then((our_contract) => {

Let's see our contract address:

console.log(`Our Contract address: ${our_contract._address}`);

or alternatively:

console.log(`Our Contract address in another way: ${our_contract.options.address}`);

Now let's query our contract ABI:

console.log("Our contract abi: " + JSON.stringify(our_contract.options.jsonInterface));

We can see our contract's total supply using a callback:

our_contract.methods.totalSupply().call(function(err, totalSupply) { if (!err) { console.log(`Total Supply with a callback: ${totalSupply}`); } else { console.log(err); } });

Or we can use the returned promise instead of passing in the callback:

our_contract.methods.totalSupply().call().then(function(totalSupply){ console.log(`Total Supply with a promise: ${totalSupply}`); }).catch(function(err) { console.log(err); });

Asynchronous Operation with Await

Now that you've seen the basic tutorial, you can try the same interactions using an asynchronous await construct. Review the web3-contract-basic-interaction-async-await.js script in code/web3js and compare it to this tutorial to see how they differ. Async-await is easier to read, as it makes the asynchronous interaction behave more like a sequence of blocking calls.

Short Links Reference

Throughout this book we have used short links. These short links take up less space on the page and make it easier for readers of the print edition to transcribe them into a browser. However, short links can break and the companies providing these services may cease to exist or block certain links. The complete links are shown here in the order they are found in the text.

Smart Contract Security

  • Short Link — Expanded Link — 2Ogvnng — https://solidity.readthedocs.io/en/latest/units-and-global-variables.html#address-related — 2EVo70v — https://solidity.readthedocs.io/en/latest/security-considerations.html#use-the-checks-effects-interactions-pattern — 2EQaLCI — http://hackingdistributed.com/2016/06/18/analysis-of-the-dao-exploit/ — 2MOfBPv — https://consensys.github.io/smart-contract-best-practices/known_attacks/#integer-overflow-and-underflow — 2xvbx1M — https://randomoracle.wordpress.com/2018/04/27/ethereum-solidity-and-integer-overflows-programming-blockchains-like-1970/ — 2CUf7WG — https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md — 2RovrDf — https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html — 2AAElb8 — https://ethereum.stackexchange.com/questions/3667/difference-between-call-callcode-and-delegatecall — 2Oi7UlH — https://solidity.readthedocs.io/en/latest/introduction-to-smart-contracts.html#delegatecall-callcode-and-libraries — 2RmueMP — https://solidity.readthedocs.io/en/latest/abi-spec.html#function-selector — 2Dg7GtW — https://medium.com/chain-cloud-company-blog/parity-multisig-hack-again-b46771eaa838 — 2CUh2KS — https://ethereum.stackexchange.com/questions/191/how-can-i-securely-generate-a-random-number-in-my-smart-contract — 2Q589lx — https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620 — 2JtdqRi — https://etherscan.io/address/0x95d34980095380851902ccd9a1fb4c813c2cb639#code — 2Q58VyX — https://www.reddit.com/r/ethdev/comments/7x5rwr/tricked_by_a_honeypot_contract_or_beaten_by/ — 2yKme14 — https://vessenes.com/the-erc20-short-address-attack-explained/ — 2yFOGRQ — https://medium.com/huzzle/ico-smart-contract-vulnerability-short-address-attack-31ac9177eb6b — 2CQjBhc — https://www.reddit.com/r/ethereum/comments/6r9nhj/cant_understand_the_erc20_short_address_attack/ — 2Q5VIG9 — https://solidity.readthedocs.io/en/latest/abi-spec.html — 2Q1ybpQ — https://vessenes.com/the-erc20-short-address-attack-explained/ — 2RnS1vA — http://hackingdistributed.com/2016/06/16/scanning-live-ethereum-contracts-for-bugs/ — 2CSdF7y — https://solidity.readthedocs.io/en/latest/common-patterns.html — 2OfHalK — https://github.com/etherpot/contract/blob/master/app/contracts/lotto.sol — 2Jpzf4x — http://aakilfernandes.github.io/blockhashes-are-only-good-for-256-blocks — 2ACsfi1 — https://www.kingoftheether.com/thrones/kingoftheether/index.html — 2ESoaub — https://www.kingoftheether.com/postmortem.html — 2Q6E4lP — https://consensys.github.io/smart-contract-best-practices/known_attacks/#race-conditions — 2yI5Dv7 — https://github.com/ethereum/wiki/wiki/Ethash — 2SygqQx — http://hackingdistributed.com/2017/08/28/submarine-sends/ — 2EUlLzb — https://hackernoon.com/front-running-bancor-in-150-lines-of-python-with-ethereum-api-d5e2bfd0d798 — 2Oh8j7R — https://etherscan.io/address/0xf45717552f12ef7cb65e95476f217ea008167ae3 — 2OdUC9C — https://solidity.readthedocs.io/en/latest/units-and-global-variables.html — 2AAebFr — https://etherscan.io/address/0x0d8775f648430679a709e98d2b0cb6250d2887ef#code — 2Q1AMA6 — https://applicature.com/blog/history-of-ethereum-security-vulnerabilities-hacks-and-their-fixes — 2ESWG7t — https://etherscan.io/address/0xe82719202e5965Cf5D9B6673B7503a3b92DE20be#code — 2ERI0pb — https://medium.com/cryptronics/storage-allocation-exploits-in-ethereum-smart-contracts-16c2aa312743 — 2OgxPtG — https://www.reddit.com/r/ethdev/comments/7wp363/how_does_this_honeypot_work_it_seems_like_a/ — 2OVkSL4 — https://medium.com/coinmonks/an-analysis-of-a-couple-ethereum-honeypot-contracts-5c07c95b0a8d — 2Ogp2Ia — https://github.com/ethereum/wiki/wiki/Safety#beware-rounding-with-integer-division — 2SwDnE0 — https://vessenes.com/ethereum-contracts-are-going-to-be-candy-for-hackers/ — 2qm7ocJ — https://vessenes.com/tx-origin-and-ethereum-oh-my/ — 2P3KVA4 — https://medium.com/coinmonks/solidity-tx-origin-attacks-58211ad95514

Tokens

  • Short Link — Expanded Link — 2CUf7WG — https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md — 2EUYCMR — https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol — 2xPYck6 — https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v1.12.0/contracts/token/ERC20/StandardToken.sol