1. Glossary
    1. 账户Account
      1. 合约账户
      2. 外部拥有账户(EOA)
    2. 地址Address
    3. 区块Block
    4. 区块链Blockchain
    5. 合约创建交易Contract creation transaction
    6. 去中心化自治组织 DAO
    7. 难度 Difficulty
    8. 数字签名 Digital signature
    9. 椭圆曲线数字签名算法 ECDSA
    10. 以太坊改进建议 EIP
      1. 以太坊注释请求 ERC
    11. 以太 Ether
    12. 事件Event
    13. 以太坊虚拟机 EVM
    14. EVM汇编语言 EVM Assembly Language
    15. 后备方法 Fallback function
    16. 水龙头 Faucet
    17. 燃气 Gas
    18. 燃气限制 Gas limit
    19. 创世区块 Genesis block
    20. Geth
    21. 分层确定钱包 HD wallet
      1. 分层确定钱包种子 HD wallet seed
    22. 内部交易(又称“消息”)
    23. Keccak256
    24. Keystore 文件
    25. 库 Library
    26. 矿工 Miner
    27. 节点 Node
    28. 随机数 Nonce
    29. 叔块Ommer
    30. 权益证明 Proof-of-Stake (PoS)
    31. 工作量证明 Proof-of-Work (PoW)
    32. 奖励 Reward
    33. 私钥private key
    34. 智能合约 Smart Contract
    35. Solidity
      1. Solidity inline assembly
    36. 测试网 Testnet
    37. 钱包 Wallet
    38. Web3
    39. Wei
    40. 零地址 Zero address
  2. 1.What is Ethereum
    1. 以太坊的定义
      1. “世界的计算机”
      2. “一个图灵完备的可编程和通用区块链”
      3. 计算机科学的角度:
      4. 更实际的角度:
    2. 与比特币的比较
    3. 以太坊的开发
    4. 以太坊的诞生
      1. 2013年底,Vitalik向Mastercoin提案允许用灵活且可编写脚本的合约
      2. 2013年12月,Vitalik分享一份白皮书,描述了以太坊背后的想法
      3. 从2013年12月开始,Vitalik和Gavin完善并发展了这个想法,共同构建了形成以太坊的协议层。
      4. 2015年7月30日,第一个以太坊地块被开采。世界计算机开始为世界服务…​…​
    5. 以太坊开发的四个阶段
      1. Frontier
        1. Block #0
          1. 以太坊的初始阶段, 从2015年7月30日持续到2016年3月。
      2. Ice Age
        1. Block #200,000
          1. 引入指数级难度增长的一个难题,激励了到权益证明的过渡。
      3. Homestead
        1. Block #1,150,000
          1. 以太坊的第二阶段,2016年3月启动
      4. DAO
        1. Block #1,192,000
          1. 恢复被破坏的DAO合约的硬分叉,导致以太坊和以太坊经典分成两个竞争系统。
      5. Tangerine Whistle
        1. Block #2,463,000
          1. 改变某些IO密集操作的燃气计算方法和清除拒绝服务攻击(利用这些操作的低燃气成本)累积状态的硬分叉
      6. Spurious Dragon
        1. Block #2,675,000
          1. 解决更多拒绝服务攻击向量和另一种状态清除的硬分叉,还包括转播攻击保护机制
      7. Metropolis
        1. 大都会拜占庭
          1. Block #4,370,000
          2. 大都会是以太坊的第三阶段,正是撰写本书的时间,于2017年10月启动。拜占庭是Metropolis的两个硬分叉中的第一个。
        2. Constantinople
          1. 大都会阶段的第二部分,计划在2018年中期。预计将包括切换到混合的工作证明/权益证明共识算法,以及其他变更
      8. Serenity
        1. 以太坊的第四个也是最后一个阶段。宁静尚未有计划的发布日期。
    6. 以太坊的组件
      1. P2P Network
      2. Consensus rules
      3. Transactions
      4. State Machine
      5. Blockchain
      6. Consensus Algorithm
      7. Clients
        1. Geth
        2. Parity
    7. 以太坊和图灵完整性
      1. 以太坊在一个名为以太坊虚拟机的状态机中执行存储程序,在内存中读写数据的能力,使其成为一个图灵完整系统,因此是一台通用图灵机
      2. 以太坊的突破性创新是将存储程序计算机的通用计算架构与去中心化区块链相结合,从而创建分布式单状态(单例)世界计算机
      3. 以太坊程序“到处”运行,但却产生了共识规则所保证的共同(共识)状态
    8. 从通用区块链到去中心化应用 (DApps)
      1. DApp至少由两部分组成
        1. 区块链上的智能合约
        2. 一个Web前端用户界面
      2. DApp是一个基于开放的,去中心化的,点对点基础架构服务的Web应用程序
    9. 万维网的进化
      1. Web 2.0
        1. 网络向用户生成内容,响应接口和交互性的演变
      2. Web 3.0
        1. 从集中拥有和管理的应用程序到基于去中心化协议的应用程序
    10. 以太坊的开发文化
    11. 为什么学习以太坊?
  3. 2.Intro
    1. 以太网货币单位
      1. 以太坊的货币单位称为 以太 ether
      2. 以太最小单位被命名为wei,一个 ether 是 1×10^18或1,000,000,000,000,000,000 个 wei
      3. 以太坊Ethereum是系统,以太Ether是货币
    2. 使用MetaMask
      1. 安装MetaMask浏览器插件
      2. 切换到测试网
      3. 获得测试Ether
      4. 发送Ether
      5. 查询交易记录
    3. 控制和责任
      1. 以太坊的每个用户都应该控制自己的密钥,这些密钥可以控制对资金和合约的访问
      2. 如果你丢失了你的钥匙,你将无法获得资金和合约。没有人可以帮助你重新获得访问权 - 你的资金将永远锁定
      3. 管理这一责任的提示
        1. 提示你选择密码时:强化它,备份并不共享
        2. 当系统提示你备份密钥或助记词时,请使用笔和纸进行物理备份
        3. 不要在数字文档,数字照片,屏幕截图,在线驱动器,加密的PDF等中存储密钥材料(加密或不加密),不要临时凑合的安全性
        4. 在传输任何大量数据之前,先做一个小的测试交易(例如,1美元)
        5. 勿将金钱汇入本书所示的任何地址
    4. 合约示例
      1. // SPDX-License-Identifier: CC-BY-SA-4.0 // Version of Solidity compiler this program was written for pragma solidity 0.6.4; // Our first contract is a faucet! contract Faucet { // Accept any incoming amount receive() external payable {} // Give out ether to anyone who asks function withdraw(uint withdraw_amount) public { // Limit withdrawal amount require(withdraw_amount <= 100000000000000000); // Send the amount to the address that requested it msg.sender.transfer(withdraw_amount); } }
        1. 1. 编译合约
        2. 2. 部署合约至链上
        3. 3. 与合约交互
          1. 查看合约
          2. 向合约发送以太
          3. 从合约中提取以太
  4. 3.Client
    1. 以太坊客户端是一个软件应用程序,它实现了以太坊规范并通过对等网络与其他以太坊客户端进行通信
    2. 六个主要实现
      1. Parity(Rust)
      2. Geth(Go)
      3. cpp-ethereum(C++)
      4. pyethereum(Python)
      5. Mantis(Scala)
      6. Harmony(Java)
    3. Full Node
      1. Advantages
        1. Supports the resilience and censorship resistance of Ethereum-based networks
        2. Authoritatively validates all transactions
        3. Can interact with any contract on the public blockchain without an intermediary
        4. Can directly deploy contracts into the public blockchain without an intermediary
        5. Can query (read-only) the blockchain status (accounts, contracts, etc.) offline
        6. Can query the blockchain without letting a third party know the information you’re reading
      2. Disadvantages
        1. Requires significant and growing hardware and bandwidth resources
        2. May require several days to fully sync when first started
        3. Must be maintained, upgraded, and kept online to remain synced
    4. Public Testnet
      1. Advantages
        1. A testnet node needs to sync and store significantly less data compared to mainnet—about 75 GB depending on the network.
        2. A testnet node can sync fully in much less time.
        3. Deploying contracts or making transactions requires test ether, which has no value and can be acquired for free from several "faucets."
        4. Testnets are public blockchains with many other users and contracts, running "live."
    5. Local Blockchain Simulation, e.g. Ganache
      1. Advantages
        1. No syncing and almost no data on disk; you mine the first block yourself
        2. No need to obtain test ether; Ganache is initialized with accounts that already hold ether for testing
        3. No other users, just you
        4. No other contracts, just the ones you deploy after you launch it unless you use the option of forking off an existing Ethereum node
      2. Disadvantages
        1. Having no other users means that it doesn’t behave the same as a public blockchain. There’s no competition for transaction space or sequencing of transactions.
        2. No miners other than you means that mining is more predictable; therefore, you can’t test some scenarios that occur on a public blockchain.
        3. If you are forking off an existing Ethereum node, it will need to be an archival node for you to interact with state from blocks that may have been pruned otherwise
  5. 4. Keys-addresses
    1. Private Keys
      1. A private key is simply a number, picked at random.
      2. Ownership and control of the private key is the root of user control over all funds associated with the corresponding Ethereum address, as well as access to contracts that authorize that address.
      3. The private key is used to create signatures required to spend ether by proving ownership of funds used in a transaction.
    2. Public Keys
      1. An Ethereum public key is a point on an elliptic curve, meaning it is a set of x and y coordinates that satisfy the elliptic curve equation.
      2. These numbers are produced from the private key by a calculation that can only go one way.
    3. Cryptographic Hash Functions
      1. a hash function is “any function that can be used to map data of arbitrary size to data of fixed size.”
      2. main properties
        1. Determinism
          1. A given input message always produces the same hash output.
        2. Verifiability
          1. Computing the hash of a message is efficient (linear complexity).
        3. Noncorrelation
          1. A small change to the message (e.g., a 1-bit change) should change the hash output so extensively that it cannot be correlated to the hash of the original message.
        4. Irreversibility
          1. Computing the message from its hash is infeasible, equivalent to a brute-force search through all possible messages.
        5. Collision protection
          1. It should be infeasible to calculate two different messages that produce the same hash output.
      3. Keccak-256
        1. Ethereum uses the Keccak-256 cryptographic hash function
    4. Ethereum Addresses
      1. Ethereum addresses are unique identifiers that are derived from public keys or contracts using the Keccak-256 one-way hash function.
    5. Derivation
      1. Private key k = f8f8a2f43c8376ccb0871305060d7b27b0554d2cc72bccf41b2705608452f315
      2. Public key K (x and y coordinates concatenated and shown as hex): K = 6e145ccef1033dea239875dd00dfb4fee6e3348b84985c92f103444683bae07b83b5c38e5e...
      3. We use Keccak-256 to calculate the hash of this public key: Keccak256(K) = 2a5bc342ed616b5ba5732269001d3f1ef827552ae1114027bd3ecf1f086ba0f9
      4. Then we keep only the last 20 bytes (least significant bytes), which is our Ethereum address: 001d3f1ef827552ae1114027bd3ecf1f086ba0f9
      5. Most often you will see Ethereum addresses with the prefix 0x that indicates they are hexadecimal-encoded, like this: 0x001d3f1ef827552ae1114027bd3ecf1f086ba0f9
  6. 5. Wallets
    1. Nondeterministic (Random) Wallets
    2. Deterministic (Seeded) Wallets
      1. wallets that contain private keys that are all derived from a single master key, or seed
    3. Hierarchical Deterministic Wallets (BIP-32/BIP-44)
      1. easy to derive many keys from a single seed
    4. Wallet Best Practices
      1. Mnemonic code words, based on BIP-39
      2. HD wallets, based on BIP-32
      3. Multipurpose HD wallet structure, based on BIP-43
      4. Multicurrency and multiaccount wallets, based on BIP-44
  7. 6. Transactions
    1. Structure of a transaction
      1. Nonce
        1. A scalar value equal to the number of transactions sent from this address or, in the case of accounts with associated code, the number of contract-creations made by this account.
      2. Gas price
      3. Gas limit
      4. Recipient
      5. Value
      6. Data
      7. v,r,s
  8. 7. Smart Contracts and Solidity
    1. "Immutable computer programs that run deterministically in the context of an Ethereum Virtual Machine as part of the Ethereum network protocol."
    2. High-level programming languages for smart contracts
      1. LLL
        1. Declarative
      2. Serpent
      3. Solidity
        1. Imperative
      4. Vyper
      5. Bamboo
    3. ABI
      1. "an interface between two program modules; often, between the operating system and user programs"
      2. "to define the functions in the contract that can be invoked and describe how each function will accept arguments and return its result."
      3. specified as a JSON array of function descriptions and events
    4. Data Types
    5. Global Variables and Functions
    6. Contract Definition
      1. interface
      2. library
    7. Functions
    8. Constructor and selfdestruct
    9. Function Modifiers
    10. Inheritance
    11. Error Handling
      1. assert
      2. require
      3. revert
    12. Events
    13. Calling Other Contracts
      1. Send
      2. call
      3. callcode
      4. delegatecall
    14. Gas consideration
      1. Avoid Dynamically Sized Arrays
      2. Avoid Calls to Other Contracts
      3. Estimating Gas Cost
  9. 9. Smart Contracts Security
    1. Security Best Practices
      1. Minimalism/simplicity
      2. Code reuse
      3. Code quality
      4. Readability/auditability
      5. Test coverage
    2. Security Risks and Antipatterns
      1. Reentrancy
      2. Arithmetic Over/Underflows
      3. Unexpected Ether
      4. DELEGATECALL
      5. Default Visibilities
      6. Entropy Illusion
      7. External Contract Referencing
      8. Short Address/Parameter Attack
      9. Unchecked CALL Return Values
      10. Race Conditions/Front Running
      11. Denial of Service (DoS)
      12. Block Timestamp Manipulation
      13. Constructors with Care
      14. Uninitialized Storage Pointers
      15. Floating Point and Precision
      16. Tx.Origin Authentication
      17. Contract Libraries
  10. 10. Tokens
    1. Usage
      1. Currency
      2. Resource
      3. Asset
      4. Access
      5. Equity
      6. Voting
      7. Collectible
      8. Identity
      9. Attestation
      10. Utility
    2. Fungibility
      1. Fungible tokens
        1. we can substitute any single unit of the token for another without any difference in its value or function
      2. Non-fungible tokens
        1. tokens that each represent a unique tangible or intangible item and therefore are not interchangeable
    3. Counterparty Risk
      1. the risk that the other party in a transaction will fail to meet their obligations.
    4. Intrinsicality
      1. intrinsic assets
      2. extrinsic assets
        1. e.g. real estate, corporate voting shares, trademarks, and gold bars
    5. Standard
      1. ERC20
        1. a standard for fungible tokens
      2. ERC223
      3. ERC777
      4. ERC721
        1. Non-fungible Token (Deed) Standard
  11. 11. Oracles
    1. systems that can provide external data sources to Ethereum smart contracts
    2. Why Oracles?
      1. In order to maintain consensus, EVM execution must be totally deterministic and based only on the shared context of the Ethereum state and signed transactions.
    3. Use Cases
      1. extrinsic (i.e., "real-world" or off-chain) information
        1. e.g. football games, the price of gold, or truly random numbers
      2. Attestations
        1. e.g. academic certificates or government IDs
      3. More examples
        1. Random numbers/entropy from physical sources such as quantum/thermal processes: e.g., to fairly select a winner in a lottery smart contract
        2. Parametric triggers indexed to natural hazards: e.g., triggering of catastrophe bond smart contracts, such as Richter scale measurements for an earthquake bond
        3. Exchange rate data: e.g., for accurate pegging of cryptocurrencies to fiat currency
        4. Capital markets data: e.g., pricing baskets of tokenized assets/securities
        5. Benchmark reference data: e.g., incorporating interest rates into smart financial derivatives
        6. Static/pseudostatic data: security identifiers, country codes, currency codes, etc.
        7. Time and interval data: for event triggers grounded in precise time measurements
        8. Weather data: e.g., insurance premium calculations based on weather forecasts
        9. Political events: for prediction market resolution
        10. Sporting events: for prediction market resolution and fantasy sports contracts
        11. Geolocation data: e.g., as used in supply chain tracking
        12. Damage verification: for insurance contracts
        13. Events occurring on other blockchains: interoperability functions
        14. Ether market price: e.g., for fiat gas price oracles
        15. Flight statistics: e.g., as used by groups and clubs for flight ticket pooling
    4. Design Patterns
      1. key functions
        1. Collect data from an off-chain source.
        2. Transfer the data on-chain with a signed message.
        3. Make the data available by putting it in a smart contract’s storage.
      2. 3 main ways to set up an oracle
        1. request–response
        2. publish-subscribe
          1. effectively provides a broadcast service for data that is expected to change
          2. e.g. price feeds, weather information, economic or social statistics, traffic data
        3. immediate-read
          1. provide data that is only needed for an immediate decision
    5. Computation Oracles
    6. Decentralized Oracles
  12. 12. DApps
    1. What Is a DApp
      1. an application that is mostly or entirely decentralized
    2. Advantages of DApp
      1. Resiliency
      2. Transparency
      3. Censorship resistance
    3. Components
      1. Backend(Smart Contract)
      2. Frontend
      3. Data Storage
        1. IPFS, Swarm, etc.
      4. Decentralized Message Communications Protocols
        1. Whisper, etc.
    4. DApp Example: Auction DApp
    5. ENS
  13. 13. EVM
    1. What is EVM
      1. The EVM is the part of Ethereum that handles smart contract deployment and execution.
      2. EVM running on the Ethereum blockchain can be thought of as a global decentralized computer containing millions of executable objects, each with its own permanent data store.
      3. The EVM has a stack-based architecture, storing all in-memory values on a stack.
    2. Gas
      1. Gas is Ethereum’s unit for measuring the computational and storage resources required to perform actions on the Ethereum blockchain.
      2. miner fee = gas cost * gas price
      3. Block Gas Limit
        1. the maximum amount of gas that may be consumed by all the transactions in a block, and constrains how many transactions can fit into a block.
  14. 14. Consensus
    1. Proof of Work (PoW)
    2. Proof of Stake (PoS)