Link to this book: https://github.com/oldnicke/MasteringEthereum
Ethereum is a deterministic but actually unbounded state machine with two basic functions: a globally accessible singleton state and a virtual machine for changing the state.
To further explain, Ethereum is an open-source, decentralized computing architecture globally, executing programs known as smart contracts, using blockchain to synchronize and store the state of the system, and using a cryptocurrency called ether to measure and constrain the cost of execution resources.
State machine
The state machine is an abbreviation for the finite state automaton, which is a mathematical model abstracted from the operation rules of real-world things.
Contains four major concepts: state, event, action, transformation
Components of the blockchain
A peer-to-peer network that links participants, propagates transactions, and contains blocks with verified transactions (based on the gossip protocol)
A series of consensus rules implemented in the state machine
Messages, represented as transactions
A state machine that processes transactions based on consensus rules
Distributed database, blockchain, records the logs of all state transitions
Consensus algorithms, by forcing participants to compete and using consensus rules to constrain them, decentralize the control of the blockchain
Open-source software implementation of the above content
Gossip
Gossip is a parallel graph breadth-first search algorithm. Assuming A receives some information, updates its own information, A needs to tell B, C, etc., and then B, C tell D, E, F, G, and so on. If node B receives a message from A and finds out that it has already known this message, it will ignore it directly, thus preventing the repeated traversal of the graph. Similar to the routing table synchronization algorithm used by routers, except that routers also maintain the cost of each path. Gossip is often used to maintain the topology of clusters (routers are also), and is used by Redis, Consul.
Gas
Ethereum cannot predict whether a contract will terminate, so it limits the resources used by smart contracts through gas.
Each instruction costs gas, and if the actual computation exceeds the gas limit, the EVM will terminate execution.
Gas is the mechanism used by Ethereum to allow Turing-complete computation
From blockchain to DApps
Ethereum started as a general-purpose blockchain that could be used for various purposes, and its vision has expanded from programming DApps to platforms.
DApp represents a broader perspective than smart contracts.
A DApp is at least a smart contract and a web user interface.
To further explain, a DApp is a web application based on open, decentralized, and peer-to-peer infrastructure services
In addition, DApps often include other decentralized components:
Decentralized P2P storage protocol and platform
Decentralized P2P messaging and platform
DApp is often written as ÐApps, Ð is the Latin letter, pronounced as ETH
web3
Currently, web2
The concept of DApp aims to bring web3 into the web, with decentralized peer-to-peer protocols entering all aspects of web applications.
web3 represents a new vision and focus for web applications: from applications owned and managed centrally, to applications based on decentralized protocols.
Ethereum+web3js+JS library connects JavaScript applications running in the browser with the Ethereum blockchain. In addition, the web3.js library provides an interface for a P2P storage network called Swarm and a written Whisper P2P messaging service. Based on these components, developers can use a complete application development suite to build web3 DApps.
Ethereum: ethereum
Ethereum currency: Ether: ether: Ξ
Accounts
External accounts (EOA): Accounts that own private keys can control funds or access to contracts
Contract accounts: Contract accounts are recorded by Ethereum and are controlled by the logic of software programs executed by EVM
Ethereum clients are mainly written in six languages
Go: Geth
Rust: parity
C++: cpp-ethereum
Python: pyethereum
Scala: mantis
Java: harmony
Lightweight clients can connect to existing networks, such as their own full nodes, public blockchains, open or licensed testnets, or local private blockchains.
In fact, the commonly used lightweight client (metamask) switches between all different node options.
In addition, lightweight clients are often used interchangeably with wallets, as lightweight clients not only provide wallet transaction functions but also provide APIs.
mainnet&testnet
Cryptography is the foundation of Ethereum technology
Encryption can be used to prove secret knowledge without leaking (digital signature) or verify the authenticity of data (digital fingerprint)
Encryption is not an important part of Ethereum, as communication and transaction data do not need to be encrypted and do not require encryption
Introduction
In EOA, the ownership of Ether is established through digital keys, Ethereum addresses, and digital signatures
Public key + private key (digital key)
Digital keys are not stored on the blockchain or transmitted on the blockchain, but stored in a simple database called a wallet
The digital keys in the wallet are completely independent of the Ethereum protocol and can be generated and controlled by wallet software without connecting to the blockchain or the internet
Digital keys can realize decentralized trust and control, proof of ownership, and other functions of blockchain
✨In Ethereum transactions, a valid digital signature must be included, which can only be generated by a private key. Therefore, possession of a digital key means becoming the owner of the funds at that address
✨Digital keys are paired, consisting of public and private keys. The public key is similar to an account, and the private key is similar to a password. The private key is usually stored in a wallet. In transaction payments, the recipient is represented by an Ethereum address, which often represents the public key. However, not all Ethereum addresses represent public keys; they can also represent contracts.
✨Public keys are derived from private keys, public keys are used to receive funds, and private keys are used to create digital signatures to sign transactions and make payments. Digital signatures can be used to verify the owner or user of a contract.
✨The characteristic of public key cryptosystems is that they are easy to compute in one direction but difficult to compute in the opposite direction. Therefore, the security of digital key and the non-forgery of signatures are guaranteed.
Mathematical part
Ethereum public key
An Ethereum public key is a point on an elliptic curve, representing a set of XY coordinates that satisfy the elliptic curve equation
In simple terms, a public key is a combination of two numbers, which are generated from a one-way computation from the private key, but you cannot calculate the private key from the public key
Detailed explanation
The public key is calculated using elliptic curve multiplication and the private key:
Where k is the private key, G is a constant point, and the result K is the public key
Elliptic curve multiplication is called a one-way function by cryptographers
An elliptic curve
It will be defined on the prime order, but it is the same as the real number order elliptic curve in mathematics
And the elliptic curve encryption algorithm used by Ethereum and Bitcoin are both secp256k1 curves
Curve visualization: https://www.desmos.com/calculator/ialhd71we3?lang=zh-CN
The function is:
It is defined on the prime order p,
The constant point G is a point on the elliptic curve, known as the base point, and it is very large
Parameter n is the smallest positive integer that satisfies (here 0 refers to the point at infinity), the specific value is
Calculate
Define addition:
P1, P2 are on the elliptic curve, P3=P1+P2, and P3 is also on the elliptic curve.
Geometrically, connect P1, P2, and intersect with the elliptic curve at P3’=(x,y). And P3=(x,-y).
Point at infinity:
Approximately equal to the zero point, commonly represented as (0,0), although (0,0) is not on the elliptic curve
P1, P2 are the same point, the line connecting P1, P2 is the tangent; sometimes, the tangent is perpendicular, and in this case, P3 is the point at infinity
If P1 is the point at infinity, P1+P2=P2; here the point at infinity is similar to the zero point
Define multiplication:
Generate the public key
Given that the wallet has generated a large integer k (the private key) and a point G on the elliptic curve (the generating point for all Ethereum users is the same)
Then the public key (equivalent to k times tangent + reverse, the last point obtained can be a point)
The crypto library (OpenSSL, libsecp256k1) can help calculate this point K=(x,y)
Connect the X and Y coordinates of the public key:
online casino secrets,We need you
Because Ethereum uses uncompressed public keys, 04 is added in front
Thus obtaining the serialized public key
To calculate the Ethereum address
The public key used to calculate the Ethereum address is the one without the 04 prefix
Processed using Ethereum’s hash encryption function: Keccak-256
Keep the last 20 bytes (40 bits) (the lowest valid byte in big-endian order)
With 0x indicating hexadecimal
Thus, the Ethereum address can be obtained
Public Key: 64 bytes //046e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b83b5c38e5e2b0c8529d7fa3f64d46daa1ece2d9ac14cab9477d042c84c32ccd0
Private Key: 32 bytes //f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315
Address: 20 bytes //0x001d3f1ef827552ae1114027bd3ecf1f086ba0f9
How to judge which hash encryption function (FIPS-202 or Keccak-256) is being used
Give a predetermined input, and judge the output
Common empty input
The Interchangeable Client Address Protocol (ICAP) provides multi-functional, checksum interoperation encoding (wallet detects whether the input address is incorrect) for Ethereum addresses
Due to the slow deployment of the ICAP active name server, only a few wallets currently support ICAP.
New Ethereum Improvement Proposal 55 (EIP-55)
https://github.com/Ethereum/EIPs/blob/master/EIPS/eip-55.md
By modifying the case of the hexadecimal address, EIP-55 provides a backward-compatible checksum for Ethereum addresses
By modifying the case of the letter characters in the address, we can convey a checksum to protect the integrity of the address, prevent input or reading errors. If the wallet does not support EIP-55 checksum, the fact of uppercase will be ignored. However, if the wallet supports EIP-55 checksum, it can be verified and detected with an accuracy of 99.986% to detect errors.
EIP-55 calculation method
In simple terms, first calculate the hash of the lowercase address (without 0x)
If the corresponding number of the hash is greater than or equal to 0x8, the letters of the address must be uppercase
When entering the address, if one digit is wrong, the calculated hash will change, resulting in the complete mismatch of the case positions
The wallet only contains keys, token records are in the blockchain, and users control the tokens on the network by signing transactions with the keys in the wallet.
Currently, there are two main types of wallets, which can be distinguished by whether the keys contained in them are related to each other
One is the non-deterministic wallet JBOK, where keys are independently generated from random numbers, and keys are not related to each other (not encouraged to use,麻烦, generally only used for simple tests)
One is the deterministic wallet HD, where all keys come from a single master key (the seed). In this wallet, all segment keys are interrelated, and they can be regenerated as long as the seed is still there. Deterministic wallets use many different key derivation methods, the most common of which is the tree structure.
The HD wallet is a powerful mechanism for managing many keys and addresses, and can combine them with a series of English words (mnemonic), making it easier to transcribe and import/export across wallets. This standard is determined by BIP-39.
The mnemonic is different from the brain wallet, the difference lies in that the brain wallet is selected by the user, while the mnemonic is created and presented to the user by the randomness of the wallet
Seed 512 bits (64-bit hexadecimal)
Seed to mnemonic
The seed is not the private key; the seed can generate private keys. The mnemonic is the backup of the wallet.
The mnemonic is a sequence of words that represents the random number of the HD seed. The sequence is sufficient to reconstruct the seed and derive all keys.
Create a random sequence of 128 to 256 bits (entropy).✨Different lengths of random sequences result in a different number of mnemonics generated.
Create the checksum of the random sequence by taking the first part (entropy length/32) of the SHA256 hash.
Add the checksum to the end of the random sequence.
Divide the sequence into segments of 11 bits.
Map each 11-bit value to one of the 2048 words in the predefined dictionary.
A mnemonic is a sequence of words.
Mnemonic to Seed
PBKDF2 is a key expansion function that can convert entropy into a longer seed, and then use the seed to build HD and generate keys.
The key expansion function has two parameters: mnemonic and salt
The first parameter of the PBKDF2 key expansion function is the mnemonic generated in step 6.
The second parameter of the PBKDF2 key expansion function is the salt. The salt is a combination of the password string provided by the user (specified when generating the seed, which will change the mnemonic) and the string “mnemonic”.
PBKDF2 uses the HMAC-SHA512 hash algorithm with 2048 rounds to expand the mnemonic and salt, generating a 512-bit seed.
128-bit entropy mnemonic code, with passphrase, resulting seed
Entropy input (128 bits): 0c1e24e5917779d297e14d45f14e1a1a
Mnemonic (12 words): army van defense carry jealous true garbage claim echo media make crunch
Passphrase: SuperDuperSecret
Seed (512 bits): 3b5df16df2157104cfdd22830162a5e170c0161653e3afe6c88defeefb0818c793dbb28ab3ab091897d0715861dc8a18358f80b79d49acf64142ae57037d1d54
The BIP-39 standard allows the use of optional passphrase when deriving seeds. If no passphrase is used, the mnemonic phrase is extended with a salt composed of the constant string “mnemonic” to produce a specific 512-bit seed from any given mnemonic.
This page shows the independent web pages for generating mnemonic phrases, seeds, and extended private keys.
A feature of the HD wallet is its ability to derive child private keys from a public parent public key.
A transaction is a signed message initiated by an EOA (external owned account), transmitted by the Ethereum network, and recorded on the Ethereum blockchain.
It is the only thing that can trigger a state change or cause a contract to be executed in the EVM.
Ethereum is a global single-instance state machine, and transactions are the only thing that can make the state machine move, change the state. That is, contracts will not run automatically, Ethereum will not run automatically, everything starts with a transaction
The basic structure of a transaction
The network serialization of a transaction is the only universal standard for the transaction structure
A transaction is a serialized binary message that contains the following data:
nonce: The sequence number issued by the originating EOA (external owned account), used to prevent message replay.
gas price: The gas price the sender is willing to pay (in wei).
start gas: The maximum gas the sender is willing to pay.
to: The target Ethereum address.
value: The amount of ether sent to the target address.
data: Variable-length binary data.
v, r, s: The three components of the ECDSA signature of the originating EOA (external owned account).
The transaction message does not contain the from field because the public key of the transaction sender can be calculated from the ECDSA signature.
Transaction random number nonce
This is the most important and least understood part of the transaction.
Nonce: A scalar value equal to the number of transactions sent from this address, or, for accounts with associated code, it represents the number of contracts created by this account.
Strictly speaking, nonce is an attribute of the originating address (it only has meaning in the context of the sending address). However, this nonce is not explicitly stored as part of the account state in the blockchain. Instead, it is dynamically calculated based on the number of confirmed transactions originating from this address.
Nonce can also be used to prevent double spending and so on.
Track nonce
Query the latest count of confirmed transactions for the account
The latest count is 40, meaning the nonce for the next transaction will be 40.
Nonce has a confirmation mechanism, meaning that after creating multiple transactions in order, if one transaction is not mined, then all subsequent transactions will be blocked. If two transactions with the same nonce occur (due to concurrency errors), the one with the earlier nonce will be processed, and the one with the later nonce will be rejected.
Concurrency, transactions, nonce
In a decentralized/distributed real-time system like Ethereum, concurrency may suddenly emerge.
Simply put, concurrency is multiple independent systems calculating simultaneously, which can be in the same program (multithreading), the same CPU (multiprocessing), or different computers (distributed computing). Ethereum, however, allows (nodes, clients, DApps) concurrent multiple systems but enforces a single state.
Transaction gas
gasPrice & startPrice
gasPrice: The exchange rate per unit of gas, 1 gas = ? wei, 1 ether = 10^18 wei
startPrice: the gas willing to pay for this transaction
Gas is the fuel of Ethereum. Gas is not ether; it is independent and has a relative exchange rate to ether. Gas is separated from ether to protect the system from fluctuations caused by the rapid change in the value of ether.
The web3 interface provides gasPrice suggestions by calculating the average price of several blocks
Recipient of the transaction ‘to’
The recipient of the transaction is specified by ‘to’, which includes a 20-byte Ethereum address, which can be an EOA or a contract.
Ethereum does not verify whether there is such an address; any 20-byte value is a valid value.sports betting help and Latest Address
Verifying whether an address is valid should be completed at the user interface level.
If sent to a non-existent address, ether will be burned.
In fact, there are also some contracts specifically used for burning ether.
Transaction value and data
Value & data
Value and data can both exist, both not exist, or only one of them
Transactions with only value are payments
Transactions with only data are calls
Transactions without value and data are a waste of gas
Send value to EOA or contract
For EOA, the sent balance will be added to the address’s balance. If the address has not been observed before, a new address will be created and the balance will be initialized.
For contract addresses, it will attempt to call the function specified in the data. If there is no data, EVM will call the fallback function of the target contract; if the function is payable, it will execute the function to determine the next step.
The contract can refuse to receive payment by immediately throwing an exception when calling the payment function or by conditions. If the payment is successful, the contract state will be updated, and the ether balance will increase.
Send data to EOA or contract
Generally, if a transaction contains data, it is likely to be sent to a contract.
If sent to an EOA, most wallets will ignore the data
If sent to a contract, the data will be considered as a function call by EVM, calling the specified function and passing any encoded parameters to the function.
The data sent to the contract is a hexadecimal encoding
Function selector: the first four bytes of the Keccak256 hash of the function prototype. This allows EVM to clearly identify the function you wish to call.
Function parameters: encoded according to the rules of various basic types defined by EVM.
✨ Example of data format in a transaction
In Faucet.sol, we have defined a function for withdrawal:
The function name is withdraw, and it has only one parameter which is uint (it is an alias for uint256). Therefore, the prototype of withdraw will be:
Let’s calculate the Keccak256 hash of this string (we can do this using the truffle console or any JavaScript web3 console: in most cases keccak256 and sha3 are synonyms):
The first four bytes of the hash are 0x2e1a7d4d (one byte is 8 bits, representing 0-255, which is represented by two hexadecimal digits).
This is the value of our ‘function selector’ that will tell the EVM which function we want to call.
Next, let’s calculate a value as the parameter withdraw_amount to pass. We want to withdraw 0.01 ether. We encode it as a hexadecimal serialized big-endian unsigned 256-bit integer in wei units:
Now, we will add the function selector to this parameter (padded to 32 bytes):
This is the data of our transaction, calling the withdraw function and requesting 0.01 ether as withdraw_amount.
Special transaction: Registering a contract
A transaction sent to the zero address with data but without value indicates the registration of a new contract.
The to field of the contract registration transaction includes the address 0x0, which does not represent EOA, nor does it represent a contract, it does not consume ether and initiate a transaction, but only serves the purpose of registering a contract.
Special transaction: Burn
Burn address
Digital signature
Digital signatures are mathematical schemes used to prove the authenticity of digital information or files. A valid digital signature gives the recipient reason to believe that the information was created by a known sender, the sender cannot deny sending the information, and the information has not been changed during transmission. (Authentication + Non-repudiation + Integrity)
Here we discuss how digital signatures work and how to provide proof of ownership of the private key without leaking the private key.
Elliptic Curve Digital Signature Algorithm (ECDSA)
ECDSA is an algorithm used for digital signatures based on elliptic curve private/public key pairs.
The use of digital signatures in Ethereum
The signature proves the ownership of the private key
The proof of authorization is irrefutable
The signature proves that the transaction data is not modified after the transaction is signed
(Authentication + Non-repudiation + Integrity)
How does a digital signature work
A digital signature consists of two parts. The first part is creating a signature from the transaction using the private key, and the second part allows anyone to verify the signature using the public key.
Creating a digital signature
In ECDSA:
F_sig generates a signature Sig consisting of two values, usually called R and S
To be signed: Transaction (from the hash of the transaction)
Signature key: EOA private key
Signature result: Signature
Verification of the signature
The verification of the signature must have the signature (R and S) and the serialized transaction and public key (corresponding to the private key used to create the signature).
验证签名代表着:只有生成此公钥的私钥的所有者才能在此交易上签名。
Verifying the signature represents: only the owner of the private key that generates this public key can sign on this transaction.
If the signature is valid for this message, return TRUE
※※※ECDSA mathematics–to be added later※※※
✨Signature process in practice
To sign a transaction on Ethereum, the sender must:
Create a transaction data structure containing nine short words
nonce, gasPrice, startGas, to, value, data, v, r, s (rs is the output value of the ECDSA encryption algorithm, i.e., the signature. v is the ID used to recover the result)
Generate the serialized message of the transaction’s RLP encoding
Calculate the Keccak256 hash of this serialized message
Signature prefix v and public key recovery
The public key recovery from the ECDSA signature is called public key recovery
The transaction signature contains a prefix value v, which tells me which of the two possible Rs is the temporary public key. (R and R’ are two possibilities of the public key)
If v is even, R is the correct value. If v is odd, R’ is the correct value
Offline signing (for security)
Transaction broadcasting
The Ethereum network uses the ‘flooding’ routing protocol. Each Ethereum client, acting as a _node_ in _Peer-to-Peer (P2P)_ and ideally forming a _mesh_ network, has no ‘special’ network nodes; they all act as equal peers. We will use the term ‘node’ to refer to the Ethereum clients that are connected and participate in the P2P network.
The spread of transactions begins with the Ethereum node that creates (or receives offline) a signed transaction. The transaction is verified and then transmitted to all other Ethereum nodes directly connected to the originating node. On average, each Ethereum node maintains a connection with at least 13 other nodes, known as _neighbors_. Each neighbor node verifies the transaction immediately upon receiving it. If they agree that it is valid, they will save a copy and spread it to all their neighbors (except its own neighbors). As a result, transactions ripple outwards from the originating node across the network until all nodes in the network have a copy of the transaction.
Within a few seconds, Ethereum transactions will spread to all Ethereum nodes worldwide. From the perspective of each node, it is impossible to distinguish the origin of the transaction. The neighbor of our node may be the initiator of the transaction, or it may have received it from its neighbor. To be able to track the origin of the transaction or interfere with the spread, the attacker must control a significant percentage of all nodes. This is part of the P2P network security and privacy design, especially suitable for blockchain.
Write to the blockchain
Although all nodes in Ethereum are the same peer nodes, some of them are operated by _miners_ and provide transactions and data blocks to _mining farms_, which are computers equipped with high-performance graphics processing units (GPUs). Mining computers add transactions to candidate blocks and attempt to find a _Proof-of-Work_ that makes the candidate block valid.
Without going into too many details, valid transactions will eventually be included in a transaction block and recorded in the Ethereum blockchain. Once mined into a block, transactions will also modify the Ethereum singleton’s state by modifying the account balance (in simple payment cases) or by calling a contract to change its internal state. These changes will be recorded along with the transaction in the form of a transaction_receipt, and the transaction may also contain events.
Our transaction has completed its journey from creation to being signed by an EOA, propagated, and finally mined. It has changed the singleton’s state and left an indelible mark on the blockchain.
There are two types of accounts: EOA and contract accounts
EOA is controlled by software outside of Ethereum
Contract accounts are controlled by software running within the EVM
The following will discuss the contract accounts and the software that controls them: smart contracts (smart contract)
Smart contract: an immutable computer program that runs deterministically in the Ethereum virtual machine environment, which operates as a decentralized world computer.
Each contract has an Ethereum address representing it, which originates from the contract creation transaction. The Ethereum address of a contract can be used as a recipient in a transaction, where funds can be sent to the contract or to call a function of the contract.
Contracts only run when called by a transaction; all smart contracts on Ethereum are executed by transactions. Contracts do not run automatically.
The content of a contract can be a call to another contract, and continuous calls can produce a contract chain.
Contracts cannot be changed but can be deleted. To delete a contract, an EVM operation code named SELFDESTRUCT (formerly known as SUICIDE) must be executed, which costs negative gas. However, this operation does not delete the transaction history of the contract.
Transactions within a contract are ‘atomic’: the execution records the state changes (contract, account, etc.) only when the transaction is successfully terminated, and successful termination means that there were no errors during the program execution. If a transaction fails due to an error, all effects (state changes) will be rolled back as if the transaction had never occurred. However, failed transactions are still stored on the blockchain and the gas cost is deducted from the original account, but there is no other impact on the contract or account state.
The lifecycle of a smart contract: written in an advanced language (solidity) –> compiled into low-level bytecode that can run in EVM –> deployed to the Ethereum blockchain with the transactions following the contract creation
EVM
EVM is a virtual machine that runs a special form of machine code called EVM bytecode, just like a computer CPU runs machine code x86_64.
We use advanced languages to write programs and compile them into bytecode using compilers.
High-level languages
Generally, programming languages are divided into functional (declarative) and procedural (imperative)
In functional programming, the program we write expresses logic (logic) rather than flow (flow), such as SQL, HTML, etc.
In procedural programming, the program written is a set of logic and flow mixed together, such as C, C++, Java, etc.
Some programming languages are mixed, encouraging functional programming but also using procedural expressions for some necessary logic, such as Python, JS, etc.
Solidity is a procedural language and the most rich smart contract language.
Current smart contract languages include LLL, Serpent, Solidity, Vyper, Bamboo (from old to new)
Before writing a smart contract in Solidity
Solidity Compiler: Solidity compiler (solc)
Integrated Development Environment: Remix IDE
Locally, solc can compile .sol files
The result of solc is to produce a hexadecimal serialized binary file that can be submitted to the Ethereum blockchain
Ethereum Contract Application Binary Interface (ABI)
ABI is an interface between two program modules, usually one at the machine code level and the other at the level of the user-running program. ABI is the main way to encode data into machine code and decode data from machine code.
In Ethereum, ABI is used to encode contract calls to the EVM and read data from transactions. The purpose of ABI is to define which functions in the contract can be called and describe how functions accept parameters and return data.
The JSON format of the contract ABI is given by an array of function descriptions and events.
solc generates ABI for .sol files
As you can see, the compiler generates a JSON object describing the two functions defined by Faucet.sol. This JSON object can be used by any application that wants to access the Faucet contract at deployment time. Using ABI, applications (such as wallets or DApp browsers) can construct transactions calling functions in Faucet with the correct parameters and parameter types. For example, a wallet would know to call the function +withdraw+, which must provide a uint256 parameter named withdraw_amount. The wallet can prompt the user to provide this value, then create a transaction that encodes it and executes the +withdraw+ function.
All the content needed for an application to interact with a contract is ABI and the contract’s deployment address.
This code can detect whether the local compiler version is compatible with the target version.
Solidity syntax
Solidity complete documentation: https://solidity.readthedocs.io/en/latest/
Solidity data types:
Boolean (bool): Boolean values, true or false, as well as logical operators ! (not), && (and), || (or), == (equal), != (not equal).
Integers (int/uint): Signed (int) and unsigned (uint) integers, ranging from u/int8 to u/int256, increasing by 8 bits, without a size suffix, representing 256 bits.
Fixed-point numbers (fixed/ufixed): Fixed-point numbers, defined as u/fixedMxN, where M is the bit size (increasing by 8), and N is the number of decimal places after the decimal point.
Address: 20-byte Ethereum address. The address object has member methods balance (returns the account balance) and transfer (transfers ether to the account).
Byte array (fixed): A fixed-size byte array, defined as +bytes1+ to +bytes32+.
Byte array (dynamic): A byte array of dynamic size, defined as +bytes+ or +string+.
enum: A user-defined type for discrete values.
struct: A user-defined data container containing a set of variables.
mapping: +key ⇒ value+ hash table for hash lookup.
In addition to the above data types, Solidity also provides various literals that can be used for calculating different units:
Time units: seconds, minutes, hours, and days can be used as suffixes, converting to multiples of the basic unit seconds.
The units of ether: wei, finney, szabo, and ether can be used as suffixes, converting to multiples of the basic unit wei.
In the withdraw function, we limit the maximum withdrawal amount, representing the quantity as wei, the basic unit of ether:
This is not easy to read, so we can improve our code by using unit multiples of ether to represent values instead of wei:
Predefined global variables and functions
When executing a contract in the EVM, it can access a set of global objects within a smaller scope. These include the block, msg, and tx objects. Additionally, Solidity exposes many EVM opcodes as predefined Solidity functions.
Call transaction/message
msg: The msg object is the transaction (originating from EOA) or message (originating from a contract) that initiates the execution of the contract. It contains many useful properties:
msg.sender: We have used this before. It represents the address that initiated the message. If our contract is called by an EOA transaction, then this is the address that signed the transaction.
msg.value: The ether value sent with the message.
msg.gasgasleft(): The gas carried by this transaction minus the gas used so far. It has been deprecated and will be replaced by the gasleft() function in Solidity v0.4.21.
msg.data: The data in the message that calls the contract.
msg.sig: The first four bytes of the data, which is the function selector that allows EVM to know exactly which function we want to call.
When a contract calls another contract, the values of all properties of msg will change to reflect the information of the new caller. The only exception is the delegatecall function that runs code of another contract/library in the original msg context.
Transaction
tx.gasprice: The gas price of the transaction that initiated the call.
tx.origin: The complete call stack of the transaction from which it originated (EOA).
Block
block: A block object containing information about the current block.
block.blockhash(blockNumber)blockhash(): The hash of the block with the specified block number, up to the previous 256 blocks. Deprecated and replaced by the blockhash() function in Solidity v.0.4.22.
block.coinbase: The miner’s address of the current block.
block.difficulty: The difficulty of the current block (Proof-of-Work).
block.gaslimit: The gas limit of the current block.
Each block has a gas limit, which is the maximum total gas allowed in a single block and can determine how many transactions can be packaged in a single block.
We set a gas limit for each transaction or contract call. If the gas used for this operation is less than or equal to the gas limit you set, it will be executed. However, if the total gas consumption exceeds the gas limit, all operations will be reset, but the fee will still be charged. The total gas value consumed during execution is called gas used, and any unused gas will be refunded to the original account.
block.number: The current block number (height).
block.timestamp: The timestamp at which the miner placed the current block, starting from the Unix epoch (seconds).
Address object
Any address (passed as input or converted from a contract object) has some properties and methods:
address.balance: The balance of the address, in wei units. For example, the current contract balance is address(this).balance.
address.transfer(amount): Transfers the amount (wei) to the address and throws an exception if any error occurs. We use this function on the msg.sender address in the Faucet example, msg.sender.transfer().
address.send(amount): Similar to the previous transfer, but does not throw an exception if it fails, instead returning false.
address.call(): A low-level calling function that can construct any message with value, data. Returns false if there is an error.
address.delegatecall(): A low-level calling function that maintains the msg context of the calling contract and returns false if there is an error.
Built-in functions
addmod, mulmod: Modular addition and multiplication. For example, addmod(x, y, k) calculates (x + y) % k.
keccak256, sha256, sha3, ripemd160: Functions to calculate hash values using various standard hash algorithms.
ecrecover: Recovers the address used to sign the message from the signature.
Contract definition
The main data type in Solidity is the contract object
A contract is a container that includes data and methods
Solidity provides two additional objects similar to contracts:
interface: Often called a stub because it tells you about the parameters and return values of the function, with no implementation, used to specify the contract interface.
library: A library contract is a contract that can only be deployed once and is used by other contracts.
function
Contracts define functions that can be called by EOA transactions or other contracts (in the Faucet example, there are withdraw and fallback functions).
Define the syntax of the function:
Wherein:
FunctionName
Define the name of the function, used to call the function through transactions (EOA), other contracts, or the same contract. A function in each contract can be defined without a name, in which case it is the fallback function, which is called when no other function is specified. The fallback function cannot have any parameters or return any content.
parameters
After the name, we specify the parameters that must be passed to the function, including the name and type. In our Faucet example, we define uint withdraw_amount as the unique parameter of the withdraw function.
The keywords public, private, internal, and external specify the visibility of functions:
public
Public is the default, and these functions can be called by other contracts, EOA transactions, or the contract itself. In our Faucet example, both functions are defined as public.
external
External functions are like public, but they cannot be called from the contract unless the keyword this is used as a prefix.
internal
Internal functions can only be ‘visible’ within the contract, cannot be called by other contracts or EOA transactions. They can be called by derived contracts (inherited).
private
Private functions are similar to internal functions but cannot be called by derived contracts (inherited).
Remember that the terms internal and private are somewhat misleading. Any function or data in a public blockchain is always visible, meaning anyone can see the code or data. These keywords only affect the way and timing of function calls.
The keywords pure, constant, view, payable affect the behavior of functions:
constant/view (constant is deprecated)online casino cheats and The most fun game
Functions marked as view promise not to modify any state. The term constant is an alias for view and will be deprecated. Currently, the compiler does not enforce the view modifier, only producing a warning, but this should become a mandatory keyword in Solidity v0.5.
pure
Pure (pure) functions do not read or write any variables. They can only operate on parameters and return data without involving any stored data. Pure functions are intended to encourage declarative programming without side effects or state.
payable
Payable functions are functions that can accept payments. Functions without payable will reject receipts unless they come from coinbase (mining income) or as the destination for SELFDESTRUCT (contract termination). In these cases, due to design decisions in the EVM, the contract cannot prevent receipts.
As you can see in the Faucet example, we have a payable function (fallback function), which is the only function that can receive payments.
The construction and destruction of contracts
(constructor and destructor)
Solidity v.0.4.21, the constructor is a function that matches the contract name
The lifecycle of a contract begins with the creation transaction of EOA or another contract. If there is a constructor, it will be called in the same creation transaction and can initialize the contract state when the contract is created.
the constructor keyword, generally the function name of the constructor should be the same as the contract name, but it can be
instead of
Avoided errors caused by renaming contracts, and it is easier to determine which function is the constructor.
`// Version of Solidity compiler this program was written for`
pragma solidity ^0.4.22;
// Our first contract is a faucet!
contract Faucet {
address owner;
// Initialize Faucet contract: set owner
constructor() {
owner = msg.sender;
}
The other end of the contract lifecycle is contract destruction, which is a special EVM operation code called SELFDESTRUCT. It was previously known as SUICIDE, but due to the negative connotation of the word, the name has been deprecated. In Solidity, this opcode is exposed as a high-level built-in function selfdestruct, which takes one parameter: the address to receive the remaining balance of the contract account. It looks like this:
Function modifier modifier
This function modifier onlyOwner sets a condition for any function it modifies, requiring that the msg.sender of the transaction be the same as the owner of the contract.
To use a function modifier, you need to add its name to the function declaration, and you can apply multiple modifiers to a function, separated by commas.
This is the same as the self-destruct function above
Within a modifier function, you can access all variables and parameters of the modified function, but the modified function cannot access any variables within the modifier function.
Contract inheritance
Inherited contracts are used to add functionality, extend the basic contract, and enable modularization
To specify the parent contract for an inherited contract, use the is keyword
Supports multiple inheritance
Error handling: assert, require, revert
If a contract encounters an error, all state changes are reverted, except for the gas that has been spent (which indicates that the transaction is atomic, either completed or having no effect on the state).
The assert and require functions operate in the same way: if the condition is false, execution stops and an error is returned. Generally, assert is used when the expectation is true, which means we generally use assert to test internal conditions. require is used when testing inputs (such as function parameters or transaction fields).
The require function is a guard condition that prevents the execution of other parts of the function and generates an error when not met. Moreover, starting from Solidity v.0.4.22, require can also include a text message to display the reason for the error, so we can add an error message in the require function:
The revert function stops the contract and reverses any state changes
Adding error checking code will slightly increase the gas cost, but it provides better error reporting than not checking (adding error information after the error handling statement). Developers need to control the balance between the two.
Events Events
Event functions are convenient for generating transaction logs.
When a transaction is completed, a transaction receipt containing log entries is generated, which provides information about the operations that occurred during the execution of the transaction. Events are the Solidity advanced objects used to construct these logs.
Events are particularly useful in lightweight clients and DApps, where they can monitor specific events and return them to the user interface or change the application state to reflect the events in the underlying contract
Try to add two events
contract Faucet is mortal {
event Withdrawal(address indexed to, uint amount);//Records any withdrawal
event Deposit(address indexed from, uint amount);//Records any deposit
…
}
Use emit to trigger events
function withdraw(uint withdraw_amount) public {
…
msg.sender.transfer(withdraw_amount);
emit Withdrawal(msg.sender, withdraw_amount);//This should be recorded in the log, triggering the withdrawal event
}
function () public payable {
emit Deposit(msg.sender, msg.value);//This should be recorded in the log, triggering the deposit event.
//This is used to trigger when there are no functions declared in the contract during transactions or no data is included.
}
Catch events:
The web3.js library provides a data structure that includes the transaction result with transaction logs. Here we can see the events generated by the transaction.
Run test transactions on the latest version of the contract using Turffle:
Use the developed() function to get the deployed contract.
Execute two transactions: the first one is deposit (send), which triggers the Deposit event
The second one is withdrawal, which triggers the Withdraw event
The res returned the logs array (this comes from Turffle), where logs[0] contains the event name of logs[0].event and the event parameters of logs[0].args
Event This mechanism is not only used for communication within contracts, but also for debugging in the development process.
Contract calls (call, send, delegatecall, callcode)
Call other contracts:
Calling contracts is a useful but dangerous operation. The more flexible the call, the more dangerous it is usually.
By instantiating through new, this can create contracts on the blockchain and return an object that can be used to refer to it.
If not in the same file, use import
new can be used to pass parameters _faucet = (new Faucet).value(0.5 ether)();
Original call, delegatecall
⭐⭐⭐solidity->bytecode(bytecode)->opcode(operation code) ⭐⭐⭐
Lower-level functions can be used when calling contracts, which directly correspond to the same-named EVM opcodes, which is a blind call (blind).
Risk warning: Security risks such as reentrancy, if there is a problem, return false
delegatecall is a variant of call, replacing the more dangerous callcode.
delegatecall is different from call, it does not change the msg context, and should be used with caution.
Gas control
Gas is a factor that must be considered in smart contract programming
Gas is the resource that limits the maximum amount of loss allowed by Ethereum transactions, if the gas limit is exceeded during the calculation process:
Trigger out of gas exception
The contract state before the function execution is restored
All gas is given as transaction fees to miners and is not returned
Gas is paid by the user who creates the transaction, so programmers should minimize the gas cost of contract functions:
Avoid dynamic-sized arrays (there is a risk of introducing too much gas)
Avoid calling other contracts (the gas cost of other contracts is unknown)
To estimate gas cost (JavaScript), this should be part of the development process
This can estimate the gas units required to execute the contract based on the call parameters — gasEstimate
Get the price of the grid
Estimate gas cost
Security
All smart contracts are public, and any user can create transactions to interact with them, so any vulnerability can be exploited.
Vulnerability issues in the field of smart contracts are costly.
The programming style of defensive programming is particularly suitable for smart contract programming:
Minimalism/Saving: Implement projects with fewer methods, fewer codes, fewer complexities, and fewer features.
Code reuse: This is the most basic software security principle — maximize the reuse of trusted code: that is, if libraries and contracts already exist, please reuse them. If some code segments are used multiple times, please write them as functions or libraries.
Code Quality: Treat smart contract code with rigorous engineering and software development methodologies, rather than general programming.
Readability: Code should be well-documented and easy to read, adhering to some style and naming conventions of the Ethereum community.
Test Coverage: Test all possible inputs.
Common Security Risks: Re-entrancy
When a contract sends some Ether to an unknown address, an external malicious contract calls the previous function of the attacked contract (such as through the fallback function), in a similar recursive manner, to drain all the Ether in the contract.
In the THE DAO event, hackers used this method to cause the hard fork of Ethereum.
Design Patterns
Access Control
State Flow
Fund Disbursement
Deploy Smart Contracts
Test Smart Contracts
Test Framework:
Truffle Test
Embark Framework Testing
DApp
populus
Test on the blockchain
Enter in the geth terminal
Can be used to obtain the contract address at.
Get the contract code deployed at. This can be used to verify the correct deployment.
Get the complete log of the contract located at the address, specify it in the options. This helps to view the history of contract calls.
Get the storage located at address and display the data stored in the contract using the offset of position.
Framework
Truffle
Github; https://github.com/Trufflesuite/Truffle
Website; https://Truffleframework.com
Documentation; https://Truffleframework.com/docs
Truffle Boxes; http://Truffleframework.com/boxes/
npm package repository; https://www.npmjs.com/package/Truffle
nodejs
npm
nvm (node version manager)
A hidden file .nvmrc containing the Node.js version supported by the DApp was created, so developers only need to run nvm install in the project to automatically install and switch to this version of nvm
Continue to install truffle globally using npm -g
Use a DApp based on a pre-built template
Create a Truffle project
Name the project file Faucet
Initialize Truffle, directory structure:
.
├── contracts
│ └── Migrations.sol
├── migrations
│ └── 1_initial_migration.js
├── test
└── truffle-config.js
Install js support packages
Install truffle dependencies
Configure Truffle
truffle-config.js sets a default Ethereum node, which assumes that we are running an Ethereum client, which can be either a full node or a lightweight node.
truffle-config.js indicates that truffle communicates with the local node on port 8545 through RPC.
Truffle will connect to any Ethereum and test network through a local node, and the local node will also have wallet functionality.
Deploy contracts using truffle
Paste the contracts in the contracts subdirectory.
You can also execute truffle compile to compile the contracts.
Understanding Truffle migrations
Truffle tracks which contracts have been deployed through migrations.sol. If a project has dozens of contracts and complex dependencies, there is no need to pay gas for contracts that have not been changed.
There is a script 1_initial_migration.js in the migrations directory, which will deploy Migrations.sol
We need a second migrations script to deploy Faucets.sol, which can be named 2_deploy_contracts.js, and only slight modifications are needed for 1_initial_migration.js.
After being ready, use truffle migrate to deploy the contract
Embark
Github; https://github.com/embark-framework/embark/
Documentation; https://embark.status.im/docs/
npm package repository; https://www.npmjs.com/package/embark
$ npm -g install embark
OpenZeppelin
OpenZeppelin is an open framework for reusable and secure smart contracts in Solidity.
It is driven by the community and led by the [Zeppelin] team at https://zeppelin.solutions/.
The most distinctive feature is security.
When using it, first install the openzeppelin-solidity library locally
openzeppelin can be well integrated with truffle.
zeppelin_os
zeppelin_os is an open-source distributed tool and service platform located on EVM, which can safely develop and manage smart contract applications.
Different from OpenZeppelin’s code that needs to be redeployed for each application, the code of zeppelin_os is on-chain.
Utility
ethereumJS helpeth: Command-line utility
helpeth is a command-line tool that makes it easier for developers to operate keys and transactions.
It is part of the collection of libraries and tools based on JavaScript, ethereumjs.
https://github.com/ethereumjs/helpeth
Usage: helpeth [command]
dapp.tools
https://dapp.tools/
Dapp
https://dapp.tools/dapp/
Seth
https://dapp.tools/seth/
Hevm
https://dapp.tools/hevm/
SputnikVM
SputnikVM is an independent, pluggable virtual machine for different Ethereum-based blockchains. It is written in Rust and can be used as a binary, a library, a shared library, or integrated through FFI, Protobuf, and JSON interfaces. It has a separate binary sputnikvm-dev for testing purposes, which simulates most of the JSON RPC API and block mining.
Github link; https://github.com/etcdevteam/sputnikvm
Libraries【Libraries】
web3.js
web3.js is a JavaScript API compatible with Ethereum, used for communication with clients through JSON RPC developed by the Ethereum Foundation.
Github link; https://github.com/ethereum/web3.js
npm package repository link; https://www.npmjs.com/package/web3
Documentation link for web3.js API 0.2x.x; https://github.com/ethereum/wiki/wiki/JavaScript-API
Documentation link for web3.js API 1.0.0-beta.xx; https://web3js.readthedocs.io/en/1.0/web3.html
web3.py
web3.py is a Python library for interacting with the Ethereum blockchain. It is also available on the Ethereum Foundation’s GitHub.
Github link; https://github.com/ethereum/web3.py
PyPi link; https://pypi.python.org/pypi/web3/4.0.0b9
Documentation link; https://web3py.readthedocs.io/
EthereumJS
A collection of libraries and utilities for Ethereum.
Github link; https://github.com/ethereumjs
Website link; https://ethereumjs.github.io/
web3j
web3j is a Java and Android library for integrating with Ethereum clients and using smart contracts.
Github link; https://github.com/web3j/web3j
Website link; https://web3j.io
Documentation link; https://docs.web3j.io
Etherjar
Etherjar is another Java library that integrates with Ethereum and works with smart contracts. It is designed specifically for server-side projects based on Java 8+, providing low-level and high-level encapsulation of RPC, Ethereum data structures, and access to smart contracts.
Github link; https://github.com/infinitape/etherjar
Nethereum
Nethereum is a .Net integrated library for Ethereum.
Github link; https://github.com/Nethereum/Nethereum
Website link; http://nethereum.com/
Documentation link; https://nethereum.readthedocs.io/en/latest/
ethers.js
The ethers.js library is a compact, complete, feature-rich, and widely tested Ethereum library that is fully licensed under the MIT license and has received DevEx funding from the Ethereum Foundation to expand and maintain it.
GitHub link: https://github.com/ethers-io/ethers.js
Documentation: https://docs.ethers.io
Emerald Platform
Emerald Platform provides libraries and UI components that can be used to build Dapps on Ethereum. Emerald JS and Emerald JS UI provide a set of modules and React components to build JavaScript applications and websites, and Emerald SVG Icons is a set of blockchain-related icons. In addition to JavaScript libraries, it also has Rust libraries to operate private keys and transaction signatures. All Emerald libraries and components are licensed under Apache 2.
Github link; https://github.com/etcdevteam/emerald-platform
Documentation link; https://docs.etcdevteam.com
What’s Token
In the blockchain, Tokens are an abstract concept that can be owned, representing assets, currency, or access rights.
How to use Tokens
The most obvious use of Tokens is digital private currency, but they can also participate in programming, providing many functions. For example, conveying voting rights, access rights, and ownership of resources.
Currency
Tokens can be said to be a form of currency, such as ETH, Bitcoin
Resources
Tokens can be resources generated in a shared economy or resource-sharing environment, such as network-shared storage, CPU
Assets
Tangible or intangible, gold, oil
Access
Access rights, for digital or physical assets
Equity
Shareholder rights of digital organizations or legal virtual entities
Voting
Digital or legal voting rights
Collectibles
Identity
Avatar or ID card
Actual use
Access or payment
Tokens are divided into fungible and non-fungible
Counterparty risk is the risk that the other party in a transaction cannot fulfill its obligations.
Blockchain-based Tokens can eliminate counterparty risk (constraints of consensus rules)
Many projects use Tokens for payment for their services.
The Token of a new project is divided into utility Tokens (used for payment services, applications, and resources) and equity Tokens (representing the Tokens of the startup team’s stock)
If the application environment of Tokens is very limited, then Tokens only have ‘negligible value’.
The adoption of Tokens is because it cannot work without Tokens, not for quick fundraising.
ERC20
ERC: Ethereum Request for Comments
20: Issue number automatically allocated by Github
Currently, the vast majority of Tokens are based on ERC20, and ERC20 will eventually become EIP20 (Ethereum Improvement Proposal)
https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
ERC20 is a standard for replaceable Tokens, the different units of ERC marks are interchangeable, and there are no unique properties
ERC must functions and events:
totalSupply: Returns the total number of Tokens currently in existence
balanceOf: Returns the balance of the given address
transfer: Given an address and quantity, transfers the specified quantity of Tokens from the balance of the address executing the method to the specified address
transferFrom: Given the sender, recipient, and quantity, transfers the Token from one account to another, used together with approve
approve: When given the recipient’s address and quantity, authorizes that address to execute multiple transfers from the standard account until the specified quantity is reached
allowance: Given the owner’s address and the consumer’s address, returns the remaining amount approved for the consumer to withdraw from the owner
Transfer event: The event triggered by a successful transfer
Approval event: The event triggered by a successful call to approve
ERC20 optional functions
name: Returns the readable name of the Token
symbol: Returns the human-readable symbol of the Token
decimals: Returns the number of decimal places used to divide the Token (if it is 2, then divide the Token by 100 to get the representation).
Define the ERC20 interface in Solidity
The ERC20 interface specification in Solidity
ERC20 data structure
Any ERC20 implementation will include two data structures, one for tracking balances, and another for tracking allowances (allowances). In Solidity, they are implemented using data mappings (data mappings).
The first data mapping is to allow the Token contract to track who owns the Token.
The second data mapping is quota, which allows spenders to spend a specific amount from the owner’s account and track the quota (from the owner’s address to a spender’s address and quota amount) through a two-dimensional mapping.
ERC20 workflow: transfer and approve & transferFrom
One is a single-step transaction workflow using transfer:
If Alice wants to send 10 Tokens to Bob, her wallet will send a transaction to the Token contract’s address and call the transfer function with Bob’s address and ’10’ as parameters. The Token contract adjusts Alice’s balance (-10) and Bob’s balance (10) and emits a +Transfer event.
One is a two-step transaction workflow using approve and transferFrom:
This workflow allows the Token owner to delegate control to another address, commonly used to delegate control to a contract to distribute Tokens, but can also be used by exchanges.
Suppose Alice wants to allow the AliceICO contract to sell 50% of all AliceCoin Tokens to buyers like Bob and Charlie. First, Alice issues the AliceCoin ERC20 contract, distributing all AliceCoin to her own address. Then, Alice issues the AliceICO contract that can sell Tokens for ether. Next, Alice initiates the approve & transferFrom workflow. She sends a transaction to AliceCoin, calling approve with parameters of the AliceICO address and 50% of the totalSupply. This triggers an Approval event. Now, the AliceICO contract can sell AliceCoin.
When AliceICO receives ether from Bob, it needs to send some AliceCoin to Bob as compensation. The exchange rate between AliceCoin and ether is within the AliceICO contract. The exchange rate set by Alice when creating AliceICO determines how many Tokens Bob will get based on the amount of ether he sends to AliceICO. When AliceICO calls the AliceCoin transferFrom function, it sets Alice’s address as the sender, Bob’s address as the recipient, and uses the exchange rate to determine how many AliceCoin Tokens will be transferred to Bob in the ‘value’ field. The AliceCoin contract transfers the balance from Alice’s address to Bob’s address and triggers a Transfer event. As long as it does not exceed the approval limit set by Alice, the AliceICO contract can call transferFrom an unlimited number of times. The AliceICO contract can track how many AliceCoin Tokens it can sell by calling the allowance function.
Implement ERC20
EIP20 mentions two implementations:
Consensys EIP20
A simple and readable implementation of an ERC20-compatible Token.
Solidity code implemented by Consensys:
https://github.com/ConsenSys/Tokens/blob/master/contracts/eip20/EIP20.sol
OpenZeppelin StandardToken
This implementation is compatible with ERC20 and has additional security precautions.
It is the foundation of the OpenZeppelin library, implementing more complex Tokens compatible with ERC20, such as fundraising, auctions, etc.
Solidity code for OpenZeppelin StandardToken: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/Token/ERC20/StandardToken.sol
Launch your own ERC20
Use the Truffle framework:
Initialization
Edit truffle-config.js to set up the Truffle environment, or directly copy an existing environment:
https://github.com/ethereumbook/ethereumbook/blob/develop/code/truffle/METoken/truffle-config.js
Import OpenZeppelin StandardContract
It implements key security checks and is easy to extend.
Create and write contracts
Example code:
https://github.com/ethereumbook/ethereumbook/blob/develop/code/truffle/METoken/contracts/METoken.sol
Truffle compilation
Create a new migration script to deploy the METoken contract
Firstly, use the local blockchain for testing
ganache-cli: Private Ethereum blockchain, which can be used for testing and executing commands: https://truffleframework.com/ganache/
Start ganache blockchain from the command line of ganache-cli or from the graphical user interface.
At this time, on the ganache console, you can see that we have deployed and created 4 transactions
Interact with METoken in the truffle console
It is an interactive JavaScript environment that can access the Truffle environment and access the blockchain through Web3.
Firstly, connect truffle to ganache
If we want to interact with deployed contracts, we must use asynchronous calls in the form of JavaScript ‘promise’.
Problems with ERC20Token
ERC20Token exposes subtle differences between Tokens and ether.
ERC223
A Token contract interface standard
It solves the problem of unintentionally transferring Tokens to contracts by detecting whether the destination address is a contract.
ERC777
Another improved Token contract standard
https://github.com/ethereum/EIPs/issues/777
ERC721
The ERC721 proposal is a non-interchangeable Tokens standard, also known as certificates/deeds.
All previous Token standards are interchangeable Tokens.
Token standard🪐
What is Token standard:
The minimum scope that is implemented, in order to comply with ERC20, you must at least implement the functions and behaviors stipulated by ERC20. It mainly encourages interoperability between contracts, so that all wallets, exchanges, user interfaces, and other infrastructures can communicate with contracts following any specifications in a predictable manner.
Complexity is the enemy of security
Common functions of project expansion
Owner control
Specific addresses or a group of addresses (multi-signature) have special functions, such as blacklist, whitelist, minting, recovery, and so on.
Burning
Token burning refers to the deliberate destruction of Tokens when they are transferred to unreliable addresses or the balance is deleted, thereby reducing the supply.
Minting
The ability to add the total supply of Tokens at a predictable rate, or through the ‘command’ of the Token creator.
Crowdfunding
The ability to provide Token sales, such as through auctions, market sales, reverse auctions, and so on.
Ceiling
The predefined and unchangeable limit of the total supply, which is opposite to the ‘minting’ function.
Recovering ‘backdoors’
The function of recovering funds, reversing the transmission, or dismantling Tokens (multi-signature) activated by specified addresses or a group of addresses.
Whitelist
The function of limiting the transmission of Tokens to the listed addresses. After passing the rule review of different jurisdictions, it is most commonly used to provide Tokens to ‘accredited investors’. There is usually a mechanism for updating the whitelist.
Blacklist
Limit the ability to transfer Tokens by banning specific addresses. Typically, there is a function to update the blacklist.
Tokens and ICOs
ICO: Initial Public Offering lottery and How to find it Financing
Tokens are an important component
Currently, many Tokens on the Ethereum are disguised scams, pyramid schemes, and fundraising.
The long-term vision and impact of this technology should be distinguished from the short-term bubble of Token ICO.
Fraud is rampant in the bubble, but Token standards and platforms will survive and may change the world.
DApp
P2p connects internet users together.
USENET is the first p2p architecture distributed messaging system.
Napster is a music and file sharing application that marks the beginning of the conversion of the completely point-to-point network movement into BitTorrent, with participating users completely independent of the physical network and not required to comply with any management institution.
DApp does not belong to a single server but builds the entire stack on the p2p network for distributed storage and operation.
A DApp includes front end, back end, and data storage.
DApp has the following advantages compared to traditional centralized architecture:
Resilience:
DApp will not have downtime as long as the blockchain is there.
Transparency
It allows anyone to fork the code and run the same application on the blockchain.
Any interaction with the block will be permanently stored.
Anyone with a blockchain copy can obtain access rights to it.
It may not be possible to decompile bytecode into source code and fully understand the contract code.
Anti-censorship
Users can interact with DApp without interference from centralized institutions, and once the code is deployed on the network, no one can modify the code.
Components of DApp
Smart contracts
Smart contracts are used to store the business logic, state, and computation of decentralized applications.
Problems with running smart contracts as core business logic functions:
Once deployed, it cannot be modified.
A large contract requires a large amount of gas to deploy and run. Therefore, some applications may take offline computation and external data sources.
The core business logic of DApp relies on external data or servers, which means that your users must trust these external entities.
Front end
The front end of DApp is not different from traditional web front end.
Interaction between the front end and DApp is usually carried out through the browser itself using tools such as the Mist browser or Metamask browser extension.
Currently, due to the lack of available mobile clients with key management functions, etc., there are no projects such as creating mobile DApps.
Data storage
High gas costs make smart contracts currently unsuitable for storing large amounts of data. Therefore, most DApps will use decentralized storage (IPFS or Swarm) to store and distribute large amounts of static resources.
The hash of the content is usually stored as bytes in smart contracts using data mapping, and then the frontend application calls the smart contract to retrieve the asset to get each asset’s equivalent URL.
On-chain & off-chain
IPFS & Swarm
Centralized data
DApp framework
Truffleentry method lottery entry method and Latest Address
Embark
Embark focuses on using Ethereum, IPFS, and other serverless decentralized applications.
Blockchain (Ethereum):
Automatically deploy contracts and make them available in JS code. Start monitoring changes, if you update the contract, Embark will automatically redeploy the contract (if necessary) and DApp.
Contracts are used with promises via JS.
Use JavaScript for test-driven development with contracts.
Track deployed contracts; deploy only when truly needed.
Manage different chains (such as testnet, private net, livenet)
Easily manage complex systems of interdependent contracts.
Decentralized storage (IPFS):
Easily store and retrieve data on DApps using EmbarkJS, including uploading and retrieving files.
Deploy the entire application to IPFS or Swarm.
Decentralized communication (Whisper, Orbit):
Send and receive messages via Whisper or Orbit through P2P
Network technology:
Integrate with any network technology, such as React, Foundation, etc.
Use any build pipeline or tool, such as grunt, gulp, webpack
Emerld Platform
This is a framework and toolkit that simplifies the development of DApps
It provides:
JS library
Common icons
A Rust library for managing private keys
Integrated components or services
SputnikVM, an independent EVM
Active DApps
The following lists active DApps on the Ethereum network:
EthPM
A project aimed at bringing package management to the Ethereum ecosystem.
Website: https://www.ethpm.com/
Radar Relay
DEX (Decentralized Exchange) focuses on direct transactions of Ethereum-based tokens from wallet to wallet.
Website: https://radarrelay.com/
CryptoKitties
A game deployed on Ethereum that allows players to buy, collect, breed, and sell various types of virtual cats. It represents one of the earliest attempts to deploy blockchain technology for leisure and relaxation purposes.
Website: https://www.cryptokitties.co
Ethlance
Ethlance is a platform that connects freelancers and developers, using ether for payment and collection.
Website: https://ethlance.com/
Decentraland
Decentraland is a virtual reality platform supported by the Ethereum blockchain. Users can create, experience content and applications, and profit from them.
Website: https://decentraland.org/
EVM can guarantee that the same operation returns the same output regardless of where it is executed. This ensures the security of Ethereum, but prevents smart contracts from retrieving and processing off-chain data, which Oracles can solve.
Oracles can be defined as an authoritative source of offline data, allowing smart contracts to receive external information and conditionally execute —-> It can also be said that Oracles are mechanisms that bridge the gap between on-chain and off-chain, allowing smart contracts to enforce contract relationships based on actual time and data.
Example data provided by oracles:
Random numbers of physical quantities, natural disaster trigger parameters, exchange rate data, capital market data, benchmark reference data, static data, events and time intervals, weather, politics, sports, geographical location, compensation, other events on other blockchains (interoperable functions), gas price, flights
The main functions of oracles:
Respond to queries of decentralized applications, parse queries, check if they meet payment and data permissions, retrieve data from off-chain sources, sign data in transactions, broadcast transactions to the network, and further arrange transactions
Subscription Pattern
Request-Response Pattern: Common in client-server architectures
Publish-Subscribe Pattern: For example, publishers are oracles, which do not directly publish information to users but distribute the published information into different categories. Subscribers can subscribe to multiple categories. At this point, oracles can write interest rates to their internal storage, and only when they change, multiple DApps will read them from oracles to reduce the impact on network bandwidth.
Data Authentication
The task of data authentication is to ensure that the data returned by the off-chain method is complete, secure, and not tampered with.
Two common methods used for data authentication:
Authenticity Proof
Based on various proof technologies (such as digital signatures), it effectively transfers trust from the data carrier to the prover.
Oraclize is an example of an oracle service that uses authenticity proofs, and currently, TLSNotary Proof is available for querying on the Ethereum mainnet.
TLSNotary Proof relies on TLSNotary being signed by PageSigner, utilizing the Transport Layer Security (TLS) protocol, to distribute the master key for TLS signing of data among three parties: servers (oracles), auditees (Oraclize), and auditors.
Oraclize uses Amazon Web Service (AWS) as an auditor to prove that it has not been modified since its instantiation.
This method requires that Amazon itself will not tamper with the instance.
Trusted Execution Environment (TEE)
TownCrier is an authenticated data delivery system based on TEE, which uses a secure hardware area to verify the integrity of the data.
Computational oracle
Oracles can be used to perform any calculation, which is particularly useful in the Ethereum environment.
Decentralized oracle
Centralized oracle systems may meet many applications, but they are indeed a central point of failure for the Ethereum network.
ChainLink proposes a decentralized oracle network, including three key smart contracts and off-chain registration of data providers:
Reputation contract
Used to track the performance of data providers
Order matching contract
Use reputation contracts to select bids
Summary contract
Collect submissions from multiple oracles, ChainLink suggests calculating weighted responses, and provides a set of standard summary contracts.
An idea: SchellingCoin protocol: use the median as the answer
Oracle client interface in Solidity
This is complex, learn Solidity first
Ethereum is used as a unit to measure the amount of computation required to execute a set of actions, both transactions and smart contract execution require a certain amount of gas.
Gas has dual functions:
Connected to the Ethereum price and the reward for miners’ work (and against the volatility of the Ethereum price)
Resist denial-of-service attacks
The cost of sending a transaction is 21,000 gas, and adding two numbers costs 3 gas
Downtime issues
Transaction overload
Pay gas
Gas has a price but cannot be owned or spent; it only exists within the EVM and serves as a measure of work.
Collect ether—>convert to gas—>convert back to ether
Gas price, cost limit, exhaustion
Before the transaction, the initiating party needs to specify the gas limit and gas price
If the gas limit is too high, the initiating party receives a refund
If the gas limit is too low, the transaction fails and the gas is not refunded
Estimate gas
Gas is estimated by pretending that the transaction has already been included in the blockchain
Code
Gas price and transaction priority
Higher gas price settings generally result in faster processing
Block gas limit
Block gas limit is the maximum gas allowed in a block, locking the number of transactions that can be contained in the block
In 2018, the block gas limit was around 500w, which could accommodate about 238 transactions, with each transaction consuming 21,000 gas
Miners determine what the block gas limit is; miners can vote on the gas limit to expand capacity
Gas refund
Ethereum encourages the deletion of stored variables by refunding up to half of the gas fees
There are 2 negative gas operations in EVM:
Clear contract is -24,000 (SELFDESTRUCT)
Clear storage to -15,000 (SSTORE [x] = 0)
gasToken
gasToken is an ERC20 token that allows anyone to store gas when gas prices are low and use gas when gas prices are high
Rent
The Ethereum community suggests charging ‘rent’ for smart contracts to maintain vitality
When the rent is not paid, the contract will be asleep, and simple read operations cannot be performed. It is necessary to wake up the sleeping contract by paying rent and submitting merkle evidence.
EVM is the actual part that processes internal state and calculations, and in actuality, EVM is a large decentralized virtual machine containing millions of objects
Differences between Virtual Machines (Virtualbox, cloud computing) and EVM:
The purpose of virtual machine technology is to provide management program functionality, or to handle system calls, task scheduling, and resource management between the guest operating system and the underlying operating system and hardware through software abstraction.
JVM and EVM
JVM and EVM are quite similar.
JVM is designed to provide a runtime environment independent of the underlying host operating system or hardware, thus achieving compatibility with various operating systems.
Advanced programming languages (JAVA, Scala) running on JVM are compiled into corresponding instruction set bytecode. This is analogous to compiling Solidity source files to be run on EVM.
EVM machine language
EVM machine language is divided into a set of specific instructions:
Arithmetic, logic and comparison, control flow, system calls, stack operations, memory operations, account management, gas, and block information
Stack operations:
Stack and memory management opcodes instructions:
POP // Pop item from stack
PUSH // Push item onto stack
MLOAD // Load item into memory
MSTORE // Store item in memory
JUMP // Change the position of the program counter
PC // Program counter
MSIZE // Active memory size
GAS // Gas available for transaction
DUP // Duplicate stack items
SWAP // Swap stack items
Arithmetic operations
General arithmetic operation code instructions:
ADD // Addition
MUL // Multiplication
SUB // Subtraction
DIV // Integer division
SDIV // Signed integer division
MOD // Modulo (remainder) operation
SMOD // Signature modulo operation
ADDMOD // Modulo addition
MULMOD // Modulo multiplication
EXP // Exponential operation
STOP // Stop operation
Environment operation code
General operation codes for processing execution environment information:
ADDRESS // Address of the current executing account
BALANCE // Account balance
CALLVALUE // Transaction value of the execution environment
ORIGIN // Original address of the execution environment
CALLER // Address of the caller executing the call
CODESIZE // Code size of the execution environment
GASPRICE // Gas price state
EXTCODESIZE // The size of the account’s code
RETURNDATACOPY // Copy of the data output from the previous memory call
State
Just like a CPU tracks the execution process, the EVM must track the status of various components to support Ethereum transactions.
Ethereum is also described as a state-based virtual machine, including the following components
World State
The relationship between the 160-bit address state identifier and the account state is maintained in an immutable Merkle tree data structure.
Account State
Contains the following four components
nonce: The value of the number of transactions sent from the corresponding account
balance: The amount of wei owned by the account
storageRoot: The 256-bit hash value of the root node of the Merkle tree
codeHash: The immutable hash value of the EVM code for each account
Storage State
Account-specific state information maintained during runtime on the EVM
Block State
The state values required for the transaction include
blockhash: The hash value of the most recently completed block.
coinbase: The address of the recipient.
timestamp: The timestamp of the current block.
number: The number of the current block.
difficulty: The current block difficulty.
gaslimit: The current gas limit of the block.
Runtime Environment Information
Used to use the information of the transaction.
gasprice: The current gas price specified by the transaction sender.
codesize: The size of the transaction code library.
caller: The address of the account executing the current transaction.
origin: The address of the original sender of the current transaction.
State transition calculation function
Ethereum state transition function
Used to calculate the _valid state transition_.
Block termination state transition function
Used to determine the final state of the block, as part of the mining process, including block rewards.
区块级状态转换函数
The block-level state transition function
The result state of the block termination state transition function when applied to the transaction state.
solc command
solc –help
A .opcode machine language opcode file is generated after compiling with the –opcode command
A .evm machine language description file is generated after compiling with the –asm command
A bytecode file is generated after compiling with the –bin command
A runtime bytecode file is generated after compiling with the –bin-runtime command
Execute EVM bytecode
Gas
Turing completeness and gas
Turing-complete: the system can solve any problem you input.
The EVM is theoretically Turing-complete, but gas organizes it to do so. However, for most problems, the EVM is still Turing-complete.
Bytecode and runtime bytecode
During compilation, contract bytecode and runtime bytecode are obtained.
Contract bytecode
Contract bytecode is the bytecode that ultimately resides on the blockchain, plus the bytecode required to place the bytecode on the blockchain and run the constructor.
Runtime bytecode
Runtime bytecode is just the bytecode that ultimately resides on the blockchain, excluding the bytecode required to initialize the contract and place it on the blockchain.
Disassembly bytecode
In the Ethereum network, consensus refers to the ability of multiple nodes or agents to reach an agreement on the blockchain state at a given time. The community must reach a consensus both technically (within the grid) and socially (to ensure that the protocol will not fork or break).
Ethereum can resist attacks more effectively, but is not decisive in dealing with changes.
The ability to obtain consensus and trust information is of great significance for the future use of blockchain technology as an asset class and technology. To meet this challenge and maintain decentralization, the community continuously tries different consensus models.
Consensus measures
Consensus measures are measurable data, and the nodes of the blockchain network must reach a consensus on this data.
Every time a new block is added to the chain, each network node measures and approves the consistency measure.
As a result of consensus measures, the blockchain acts as a truth chain extending from a certain verifiable fact to the next fact. Based on consensus measures, the nodes of the blockchain protocol become mini-notaries, which can immediately distinguish the erroneous copies of the blockchain from real nodes and report them to the entire network, so that the organization can submit blocks with false information to deceive the network.
Based on consistency measures, the blockchain not only establishes integrity but also maintains long-term stability.
There are many types of consensus measures, with the two most important ones being the measures based on work and the measures based on risk.
POW
Based on Proof of Work (POW), a consensus is established between measures: because they use the protocol to set computers to find the answers to difficult problems, that is, to find the difficult problem requirements suitable for network parameters, requiring nodes to submit processing power and use electricity to compete with other nodes to propose effective hashes.
It is difficult to calculate the hash, but it is very simple to verify whether the result is correct.
On the Bitcoin network, the average time to generate each block is ten minutes.
On the Ethereum network, the average time to generate each block is ten seconds.
Risk-based metric
The risk-based metric is based on consensus: anyone who chooses to create an invalid block will lose more than they gain by creating a valid block.
This metric is created through consensus within the chain, rather than the off-chain consensus of PoW.
The consensus metric of PoW mainly focuses on the quality and accuracy of SHA-256 hash
The consensus metric based on risk mainly focuses on the risk any specific node undertakes when adding a new block
PoS (Proof of Stake) is a class of consensus algorithms
In blockchain based on PoS, a group of verifiers take turns suggesting and voting on the next moment, and each verifier’s voting weight depends on the size of their deposit
The advantages of PoS include security, reduced concentration risk, and energy efficiency
In PoS, anyone can become a verifier through a special transaction to participate in creating and agreeing on new blocks.
From the perspective of the algorithm, PoS is divided into proof of stake based on the chain and BFT-style proof of stake:
In proof-based consensus, the algorithm pseudo-randomly selects a verifier in each time slot (10s) and assigns the authority to create a single block to that verifier.
In BFT-style proof of stake, verifiers are randomly assigned the right to propose blocks, but the process of determining which block is canonical is determined through a multi-round process, where each verifier votes on a specific block in each round, and at the end of the process, all (honest and online) verifiers permanently agree on whether any given block belongs to the chain.
PoA
PoA is a subset of PoS and is commonly used in testnets, private, or consortium networks.
In the PoA blockchain, the validity of transactions is ultimately determined by a batch of approved on-chain accounts (authorized nodes).
PoA is the fastest way to reach consensus
DPoS (Delegated Proof of Stake)
DPoS is a modified version of PoS, where network participants vote to elect a series of representatives to verify and protect the blockchain. This may be similar to PoA, but their authority can be revoked by the voters.
Ethereum consensus Ethash
Ethash is a pow algorithm that depends on the initial epoch of the dataset, which is approximately 1GB and is a directed acyclic graph (DAG).
DAG utilizes the version of Dagger-Hashimoto algorithm, which is a combination of Vitalik Buterin’s Dagger algorithm and Thaddeus Dryja’s Hashimoto algorithm. The Dagger-Hashimoto algorithm is the mining algorithm used in Ethereum 1.0. Over time, the DAG grows linearly and is updated every epoch (30,000 blocks, 125 hours).
Introduction to Polkadot
Polkadot is an inter-chain blockchain protocol that includes integration with Proof of Stake (PoS) chains, allowing Parachain to achieve consensus without internal consensus.
Basic categories of smart contract vulnerabilities:
Suicide contract
Contracts that can be killed by any address
Greedy contract
Ether cannot be released after a certain execution state
Wasteful contract
Inadvertently releasing ether to any address
Vtper is an experimental programming language for smart contracts, targeting the EVM.
Vyper is committed to providing excellent auditability by simplifying code and making it human-readable. One of Vyper’s principles is to make it almost impossible for developers to write misleading code.
Comparison with Solidity
Decorators
Functions can be written using decorators in Solidity
But modifying decorators in the future will cause errors
Vyper has removed decorators and uses inline checks and assertions as part of the function, which improves auditability and readability.
Class inheritance
Class inheritance allows programmers to obtain pre-existing functions, properties, and behaviors from software libraries, which can promote code reuse.
Solidity supports multiple inheritance and polymorphism, which are important features of object-oriented programming.
Vyper does not support, inheritance would cause developers and auditors to jump between multiple files, which is not conducive to understanding the program.
Inline assembly
Inline assembly allows developers to access the EVM at a low level, that is, to use EVM opcodes in high-level source code.
Vyper does not support
Function overloading
Multiple function definitions with the same name and different parameter options.
foo(“hello”) and foo(“hello”,“world”)
Variable type conversion
A mechanism that allows programmers to convert variables from one data type to another.
Preconditions and postconditions
Vyper explicitly handles preconditions and state changes. Although it may produce redundancy, it indeed offers more readability and security.
Considerations when writing contracts in Vyper:
Condition: what is the current state/condition of Ethereum status variables?
Effect: what impact does this contract have on the execution status variables, what will be affected and what will not, and whether these impacts are consistent with our intentions?
Interaction: fully consider all permanent results, consequences, and scenarios of code execution, including interactions with other contracts.
Vyper
Vyper opens a new door, diverging from traditional object-oriented programming (OOP).
Decorators
Such decorators as @private, @public, @constant, @payable are declared at the beginning of each function.
@private:合约外部无法访问
@public:公开可见可执行
@constant:不允许变量改变
@payable:只有以@payable开头声明的函数才能接受价值
在线代码编辑器
Vyper拥有自己的在线代码编辑器
命令行运行
扩展名为 .v.py ,安装Vyper后,可以运行命令来编译和提供字节码
读写数据
智能合约可以将数据写入两个地方:以太坊的全球状态查找树或以太坊的链数据。
全局状态
给定智能合约中的状态变量,存储在以太坊的全局状态查找树中,给定的智能合约只能存储,读取和修改与该合约地址相关的数据(即智能合约无法读取或写入其他智能合约)。
Log
智能合约也可以通过日志事件写入以太坊的链数据。最初Vyper用_log_语法来生命,但现在已经更新。目前是
虽然智能合约可以写入以太坊的链数据(通过日志事件),但智能合约无法读取他们创建的链上日志事件。但可以在公共链上由轻客户端发现和读取日志。
ERC20接口
Vyper中ERC20上预编译合同,默认可用。Vyper中的合约必须声明为全局变量。如:
操作码(OPCODES)
合约一般用Solidity或Vyper等高级语言编写,编译器负责获取高级代码并创建他的低级解释,然后在EVM上运行。编译器可以提取代码的最低表示(在EVM执行前)是操作码。这种情况下需要高级语言的每个实现来提供适当的编译机制以允许将高级代码编译到通用预定义的EVM操作码中。
Vyper实现了以太坊的分片操作码
https://github.com/oldnicke/MasteringEthereum/blob/master/Chapter17.asciidoc
EIPs
EIP代表以太坊改进提案。
EIP是一个设计文档,为以太坊社区提供信息,或描述以太坊或其过程或环境的新功能。
EIP应提供该功能的简明技术规范和该功能的基本原理。
EIP作者负责在社区内建立共识并记录不同意见。
ERCs
ERC代表以太坊征求建议。
如果EIP被接受,它将成为ERC的一部分
多数的硬分叉作为路线图的一部分,包含社区普遍认同的更新,这被称为共识。
但也有一些硬分叉不是共识,这会导致多个不同的区块链,例如以太坊/以太坊经典。
以太坊经典(ETC)
2016年7月20日,在192w的区块高度上,以太坊通过硬分叉引入了改变,退还了360w的ether,这些ether来自名为The DAO的合约。
The DAO
The DAO was created by Slock.lt and is considered a way to provide funding for projects based on the community.
The core idea is to submit proposals, managers manage proposals, funds are raised from Ethereum investors, and investors will receive returns if the project is successful.
The DAO is an experiment with the Ethereum token.
Re-Entrancy Bug (Re-Entrancy)
The DAO attacker extracted 360w ether from the DAO.
RHG volunteers began to extract the remaining funds using the same vulnerability and plan to return them to the community, protecting most of the community’s ether.
Re-Entrancy
The DAO attacker initiated multiple requests, which allowed the attacker to withdraw again before the contract recorded the attacker’s successful withdrawal.
Attack Process
The attacker requires the contract to withdraw tokens
Request the withdrawal of tokens again before the successful withdrawal is recorded
Repeat the previous step as much as possible
The contract recorded a DAO withdrawal and lost the withdrawals that occurred during that period
ETH and ETC
Technical Differences & Ideological Differences
Basic Documentation Related to Ethereum
Ethereum Yellow Paper: https://ethereum.github.io/yellowpaper/paper.pdf
The Brown Paper: Rewritten in a less formal language for a wider audience from the ‘Yellow Paper’: https://github.com/chronaeon/beigepaper
ÐΞVp2p Network Protocol: https://github.com/ethereum/wiki/wiki/ÐΞVp2p-Wire-Protocol
An ‘Awesome’ Resource List for the Ethereum Virtual Machine (EVM): https://github.com/ethereum/wiki/wiki/Ethereum-Virtual-Machine-(EVM)-Awesome-List
LevelDB Database (most commonly used to store local copies of blockchains): http://leveldb.org
Merkle Patricia Trees: https://github.com/ethereum/wiki/wiki/Patricia-Tree
Ethash Proof-of-Work Consensus Algorithm: https://github.com/ethereum/wiki/wiki/Ethash
Casper Proof-of-Stake v1 Implementation Guide: https://github.com/ethereum/research/wiki/Casper-Version-1-Implementation-Guide
Go-Ethereum (Geth) Client: https://geth.ethereum.org/
Parity Ethereum Client: https://parity.io/
An independent web page for generating mnemonic phrases, seeds, and extended private keys
https://iancoleman.io/bip39/
Complete Documentation of Solidity
https://solidity.readthedocs.io/en/latest/
The Best Practices Guide for Ethereum Secure Development
https://github.com/ConsenSys/smart-contract-best-practices/blob/master/README-zh.md
A library called OpenZeppelin that has undergone community security review: https://openzeppelin.org/[OpenZeppelin], with a wide range of reviewed simple behaviors
An open-source platform called zeppelin_os for safe development and management of smart contracts: https://zeppelinos.org/[zeppelin_os], which provides a layer on EVM, allowing developers to easily deploy and upgrade DApps
For a more strict and in-depth explanation of the Ethereum ABI, you can find it here: https://solidity.readthedocs.io/en/develop/abi-spec.html
Otherwise
Github: https://github.com/ConsenSys/smart-contract-best-practices/
Docs: https://consensys.github.io/smart-contract-best-practices/
https://blog.zeppelin.solutions/onward-with-ethereum-smart-contract-security-97a827e47702
https://medium.com/zeppelin-blog/the-hitchhikers-guide-to-smart-contracts-in-ethereum-848f08001f05#.cox40d2ut
Contract Library
Github Link: https://github.com/ethpm
Repository Link: https://www.ethpm.com/registry
Website: https://www.ethpm.com/
Documentation: https://www.ethpm.com/docs/integration-guide
Swarm & IPFS
Swarm Homepage: http://swarm-gateways.net/bzz:/theswarm.eth/
Read the Documentation: https://swarm-guide.readthedocs.io/en/latest/index.html
Swarm Developer’s Getting Started Guide: https://github.com/ethersphere/swarm/wiki/swarm
Swarm Discussion Group: https://gitter.im/ethersphere/orange-lounge
Similarities and differences between Ethereum’s Swarm and IPFS; https://github.com/ethersphere/go-ethereum/wiki/IPFS-&-SWARM
Truffle
Getting Started and Documentation: http://truffleframework.com/docs
Github: https://github.com/trufflesuite/truffle
Website: https://truffleframework.com
Embark
Getting Started and Documentation: https://embark.readthedocs.io
Github: https://github.com/embark-framework/embark
Website: https://github.com/embark-framework/embark
Emerald Platform
Getting Started and Documentation: https://docs.etcdevteam.com
Github: https://github.com/etcdevteam/emerald-platform
Website: https://emeraldplatform.io
dapp_develotment_tool_sec: A command-line tool for smart contracts
Package management, source code building, unit testing, simple contract deployment
Getting Started and Documentation: https://dapp.readthedocs.io/en/latest/
Used in Chapter 12 Oracle Oracle
Click to view all websites
gasToken: Understand the mathematics involved in calculating profitability and how to use the gas released
https://gastoken.io/
Contract Rent
ethereum/EIPs#35
https://ethresear.ch/t/a-simple-and-principled-way-to-compute-rent-fees/1455 https://ethresear.ch/t/improving-the-ux-of-rent-with-a-sleeping-waking-mechanism/1480
Decompiler
Porosity is a popular open-source decompiler: https://github.com/comaeio/porosity
Ethersplay is an EVM plugin for Binary Ninja, a disassembler: https://github.com/trailofbits/ethersplay
IDA-Evm is an EVM plugin for IDA, another disassembler: https://github.com/trailofbits/ida-evm
EVM Tools: ByteCode To Opcode Disassembler (Used to check/debug whether the compilation runs completely, and can be used for reverse engineering if the source code is not released)
Vyper Online Code Editor
https://vyper.online
ÐΞVp2p
https://github.com/oldnicke/MasteringEthereum/blob/master/Chapter17.asciidoc
Ethereum Improvement Proposals (EIPs)
https://eips.ethereum.org/
The most important EIP and ERC tables
https://github.com/oldnicke/MasteringEthereum/blob/master/Chapter18.asciidoc#The_most_important_EIP_and_ERC_tables