1. 账户
账户类型
Ethereum has two account types:
- Externally-owned – controlled by anyone with the private keys
- Contract – a smart contract deployed to the network, controlled by code.
Both account types have the ability to:
- Receive, hold and send ETH and tokens
- Interact with deployed smart contracts
不同
Externally-owned
- Creating an account costs nothing 创建一个帐户不花钱
- Can initiate transactions 可以发起交易
- Transactions between externally-owned accounts can only be ETH transfers 外部账户之间的交易只能是ETH转账
Contract
- Creating an account has a cost because you're using network storage 创建帐户需要付费,因为您正在使用网络存储
- Can only send transactions in response to receiving a transaction 只能发送交易以响应收到交易
- Transactions from an external account to a contract account can trigger code which can execute many different actions, such as transferring tokens or even creating a new contract 外部帐户到合同帐户的交易可以触发代码,该代码可以执行许多不同的操作,例如转移令牌甚至创建新合同
一个账户
Ethereum accounts have four fields:
-
nonce
– a counter that indicates the number of transactions sent from the account. This ensures transactions are only processed once.In a contract account, this number represents the number of contracts created by the account
balance
– the number of wei owned by this address. Wei is a denomination of ETH and there are 1e+18 wei per ETH.codeHash
– this hash refers to the code of an account on the Ethereum virtual machine (EVM). Contract accounts have code fragments programmed in that can perform different operations. This EVM code gets executed if the account gets a message call. It cannot be changed unlike the other account fields. All such code fragments are contained in the state database under their corresponding hashes for later retrieval. This hash value is known as a codeHash. For externally owned accounts, the codeHash field is the hash of an empty string. 该哈希表示以太坊虚拟机(EVM)上的帐户代码。合约帐户具有编程的代码片段,可以执行不同的操作。如果帐户收到消息调用,则将执行此EVM代码。不能像其他帐户字段一样更改它。所有这些代码片段都包含在状态数据库中的相应哈希值下,以供以后检索。此哈希值称为codeHash。对于外部拥有的帐户,codeHash字段是空字符串的哈希。storageRoot
– Sometimes known as a storage hash. A 256-bit hash of the root node of a Merkle Patricia trie that encodes the storage contents of the account (a mapping between 256-bit integer values), encoded into the trie as a mapping from the Keccak 256-bit hash of the 256-bit integer keys to the RLP-encoded 256-bit integer values. This trie encodes the hash of the storage contents of this account, and is empty by default. 有时称为存储哈希。Merkle Patricia trie的根节点的256位哈希,该哈希对帐户的存储内容进行编码(256位整数值之间的映射),并编码为Trie,作为来自256的Keccak 256位哈希的映射位整数键,用于RLP编码的256位整数值。此Trie对此帐户的存储内容的哈希进行编码,默认情况下为空。
外部账户和密钥对
An account is made up of a cryptographic pair of keys: public and private. They help prove that a transaction was actually signed by the sender and prevent forgeries. Your private key is what you use to sign transactions, so it grants you custody over the funds associated with your account. You never really hold cryptocurrency, you hold private keys – the funds are always on Ethereum's ledger.
This prevents malicious actors from broadcasting fake transactions because you can always verify the sender of a transaction.
If Alice wants to send ether from her own account to Bob’s account, Alice needs to create a transaction request and send it out to the network for verification. Ethereum’s usage of public-key cryptography ensures that Alice can prove that she originally initiated the transaction request. Without cryptographic mechanisms, a malicious adversary Eve could simply publicly broadcast a request that looks something like “send 5 ETH from Alice’s account to Eve’s account,” and no one would be able to verify that it didn’t come from Alice.
账户的创建
When you want to create an account most libraries will generate you a random private key.
A private key is made up of 64 hex characters and can be encrypted with a password.
Example:
fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036415f
The public key is generated from the private key using the Elliptic Curve Digital Signature Algorithm.
You get a public address for your account by taking the last 20 bytes of the public key and adding 0x
to the beginning.
Here's an example of creating an account in the console using GETH's personal_newAccount
> personal.newAccount()
Passphrase:
Repeat passphrase:
"0x5e97870f263700f46aa00d967821199b9bc5a120"
> personal.newAccount("h4ck3r")
"0x3d80b31a78c30fc628f20b2c89d7ddbf6e53cedc"
It is possible to derive new public keys from your private key but you cannot derive a private key from public keys. This means it's vital to keep a private key safe and, as the name suggests, PRIVATE.
You need a private key to sign messages and transactions which output a signature. Others can then take the signature to derive your public key, proving the author of the message. In your application, you can use a javascript library to send transactions to the network.
合约账户
Contract accounts also have a 42 character hexadecimal address:
Example:
0x06012c8cf97bead5deae237070f9587f8e7a266d
The contract address is usually given when a contract is deployed to the Ethereum Blockchain. The address comes from the creator's address and the number of transactions sent from that address (the “nonce”).
钱包
An account is not a wallet. A wallet is the keypair associated with a user-owned account, which allow a user to make transactions from or manage the account.
2. 交易
Transactions are cryptographically signed instructions from accounts. An account will initiate a transaction to update the state of the Ethereum network. The simplest transaction is transferring ETH from one account to another.
交易是来自帐户的加密签名指令。一个账户将发起一个交易以更新以太坊网络的状态。最简单的交易是将ETH从一个帐户转移到另一个帐户。
什么是交易
An Ethereum transaction refers to an action initiated by an externally-owned account, in other words an account managed by a human, not a contract. For example, if Bob sends Alice 1 ETH, Bob's account must be debited and Alice's must be credited. This state-changing action takes place within a transaction.
以太坊交易是指由外部账户发起的操作,换句话说,是由人管理的账户,而不是合约。例如,如果Bob向Alice发送1 ETH,则必须从Bob的帐户中扣款,并向Alice的帐户贷记。这种状态改变动作发生在交易中。
Transactions, which change the state of the EVM, need to be broadcast to the whole network. Any node can broadcast a request for a transaction to be executed on the EVM; after this happens, a miner will execute the transaction and propagate the resulting state change to the rest of the network.
Transactions require a fee and must be mined to become valid. To make this overview simpler we'll cover gas fees and mining elsewhere.
A submitted transaction includes the following information:
-
recipient
– the receiving address (if an externally-owned account, the transaction will transfer value. If a contract account, the transaction will execute the contract code) -
signature
– the identifier of the sender. This is generated when the sender's private key signs the transaction and confirms the sender has authorised this transaction -
value
– amount of ETH to transfer from sender to recipient (in WEI, a denomination of ETH) -
data
– optional field to include arbitrary data -
gasLimit
– the maximum amount of gas units that can be consumed by the transaction. Units of gas represent computational steps -
gasPrice
– the fee the sender pays per unit of gas
Gas is a reference to the computation required to process the transaction by a miner. Users have to pay a fee for this computation. The gasLimit
and gasPrice
determine the maximum transaction fee paid to the miner.
The transaction object will look a little like this:
{
from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",
to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",
gasLimit: "21000",
gasPrice: "200",
nonce: "0",
value: "10000000000",
}
But a transaction object needs to be signed using the sender's private key. This proves that the transaction could only have come from the sender and was not sent fraudulently.
An Ethereum client like Geth will handle this signing process.
{
"id": 2,
"jsonrpc": "2.0",
"method": "account_signTransaction",
"params": [
{
"from": "0x1923f626bb8dc025849e00f99c25fe2b2f7fb0db",
"gas": "0x55555",
"gasPrice": "0x1234",
"input": "0xabcd",
"nonce": "0x0",
"to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
"value": "0x1234"
}
]
}
Example response:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"raw": "0xf88380018203339407a565b7ed7d7a678680a4c162885bedbb695fe080a44401a6e4000000000000000000000000000000000000000000000000000000000000001226a0223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20ea02aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",
"tx": {
"nonce": "0x0",
"gasPrice": "0x1234",
"gas": "0x55555",
"to": "0x07a565b7ed7d7a678680a4c162885bedbb695fe0",
"value": "0x1234",
"input": "0xabcd",
"v": "0x26",
"r": "0x223a7c9bcf5531c99be5ea7082183816eb20cfe0bbc322e97cc5c7f71ab8b20e",
"s": "0x2aadee6b34b45bb15bc42d9c09de4a6754e7000908da72d48cc7704971491663",
"hash": "0xeba2df809e7a612a0a0d444ccfa5c839624bdc00dd29e3340d46df3870f8a30e"
}
}
}
- the
raw
is the signed transaction in Recursive Length Prefix (RLP) encoded form - the
tx
is the signed transaction in JSON form
With the signature hash, the transaction can be cryptographically proven that it came from the sender and submitted to the network.
gas
As mentioned, transactions cost gas to execute. Simple transfer transactions require 21000 units of Gas.
So for Bob to send Alice 1ETH at a gasPrice
of 200 Gwei, he'll need to pay the following fee:
200*21000 = 4,200,000 GWEI
--or--
0.0042 ETH
Bob's account will be debited -1.0042 ETH
Alice's account will be credited +1.0 ETH
The miner processing the transaction will get +0.0042 ETH
Gas is required for any smart contract interaction too.
Any gas not used in a transaction is refunded to the user account.
交易生命周期
Once the transaction has been submitted the following happens:
Once you send a transaction, cryptography generates a transaction hash:
0x97d99bc7729211111a21b12c933c949d4f31684f1d6954ff477d0477538ff017
The transaction is then broadcast to the network and included in a pool with lots of other transactions.
-
A miner must pick your transaction and include it in a block in order to verify the transaction and consider it "successful".
-
You may end up waiting at this stage if the network is busy and miners aren't able to keep up. Miners will always prioritise transactions with higher
GASPRICE
because they get to keep the fees.如果网络繁忙且矿工无法跟上,您可能最终会在此阶段等待。矿工将始终优先考虑较高的交易,
GASPRICE
因为他们可以保留费用。
-
-
Your transaction will also get a block confirmation number. This is the number of blocks created since the block that your transaction was included in. The higher the number, the greater the certainty that the transaction was processed and recognised by the network. This is because sometimes the block your transaction was included in may not have made it into the chain. 您的交易还将获得确认号码。这是自从您的交易包含在其中以来创建的区块数。数字越大,网络处理和识别交易的确定性就越高。这是因为有时您的交易所包含的区块可能尚未进入链中。
-
The larger the block confirmation number the more immutable the transaction is. So for higher value transactions, more block confirmations may be desired.
区块确认号越大,交易越不变。因此,对于更高价值的交易,可能需要更多的区块确认。
-
3. 区块
Blocks are batches of transactions with a hash of the previous block in the chain. This links blocks together (in a chain) because hashes are cryptographically derived from the block data. This prevents fraud, because one change in any block in history would invalidate all the following blocks as all subsequent hashes would change and everyone running the blockchain would notice.
区块是具有链中前一个区块的哈希值的交易批次。这将块链接在一起(成一个链),因为哈希是从块数据中加密得出的。这可以防止欺诈,因为历史上任何区块的一次更改都会使随后的所有区块失效,因为所有后续哈希值都会更改,并且运行区块链的每个人都会注意到。
为什么blocks
To ensure that all participants on the Ethereum network maintain a synchronized state and agree on the precise history of transactions, we batch transactions into blocks. This means dozens (or hundreds) of transactions are committed, agreed on, and synchronized on all at once.
By spacing out commits, we give all network participants enough time to come to consensus: even though transaction requests occur dozens of times per second, blocks on Ethereum are committed approximately once every fifteen seconds.
通过间隔提交,我们为所有网络参与者提供了足够的时间来达成共识:即使每秒发生数十次事务请求,以太坊上的区块也大约每十五秒提交一次。
block如何工作
To preserve the transaction history, blocks are strictly ordered (every new block created contains a reference to its parent block), and transactions within blocks are strictly ordered as well. Except in rare cases, at any given time, all participants on the network are in agreement on the exact number and history of blocks, and are working to batch the current live transaction requests into the next block.
Once a block is put together (mined) by some miner on the network, it is propagated to the rest of the network; all nodes add this block to the end of their blockchain, and mining continues. The exact block-assembly (mining) process and commitment/consensus process is currently specified by Ethereum’s “Proof-of-Work” protocol.
为了保留事务历史记录,对块进行严格排序(每个创建的新块均包含对其父块的引用),并且对块内的事务也进行严格排序。除极少数情况外,在任何给定时间,网络上的所有参与者都同意区块的确切数量和历史记录,并正在努力将当前的实时交易请求分批到下一个区块。
一旦某个区块被网络上的某个矿工放在一起(挖掘),它就会传播到网络的其余部分;所有节点都将此块添加到其区块链的末尾,并且继续挖掘。当前,以太坊的“工作量证明”协议指定了确切的块组装(挖掘)过程和承诺/共识过程。
工作量证明
Proof of work means the following:
- Mining nodes have to spend a variable but substantial amount of energy, time, and computational power to produce a “certificate of legitimacy” for a block they propose to the network. This helps protect the network from spam/denial-of-service attacks, among other things*, since certificates are expensive to produce.
- Other miners who hear about a new block with a valid certificate of legitimacy must* accept the new block as the canonical next block on the blockchain.
- The exact amount of time needed for any given miner to produce this certificate is a random variable with high variance. This ensures that it is unlikely that two miners produce validations for a proposed next block simultaneously; when a miner produces and propagates a certified new block, they can be almost certain that the block will be accepted by the network as the canonical next block on the blockchain, without conflict (though there is a protocol for dealing with conflicts as well in the case that two chains of certified blocks are produced almost simultaneously).
什么是区块
- Timestamp – the time when the block was mined.
- Block number – the length of the blockchain in blocks.
- Difficulty – the effort required to mine the block.
- mixHash – a unique identifier for that block.
- A parent hash – the unique identifier for the block that came before (this is how blocks are linked in a chain).
- Transactions list – the transactions included in the block.
- State root – the entire state of the system: account balances, contract storage, contract code and account nonces are inside.
- Nonce – a hash that, when combined with the mixHash, proves that the block has gone through proof of work.
区块大小
A final important note is that blocks themselves are bounded in size. Each block has a block gas limit which is set by the network and the miners collectively: the total amount of gas expended by all transactions in the block must be less than the block gas limit. This is important because it ensures that blocks can’t be arbitrarily large. If blocks could be arbitrarily large, then less performant full nodes would gradually stop being able to keep up with the network due to space and speed requirements. The block gas limit at block 0 was initialized to 5,000; any miner who mines a new block can alter the gas limit by up to about 0.1% in either direction from the parent block gas limit. The gas limit as of April 2021 currently hovers around 15,000,000.
最后一个重要的注意事项是,块本身的大小是有限的。每个区块都有一个由网络和矿工共同设定的区块gas限制:区块中所有交易消耗的gas总量必须小于区块gas limit。这很重要,因为它可以确保块不能任意大。如果块可以任意大,那么由于空间和速度的要求,性能较低的完整节点将逐渐无法跟上网络。block 0的块gas limit被初始化为5,000;任何开采新区块的矿工都可以从父区块的gas limit中的任一方向将gas limit最多改变约0.1%。截至2021年4月,gas limit目前徘徊在1500万左右。
4. 以太坊虚拟机(EVM)
The EVM’s physical instantiation can’t be described in the same way that one might point to a cloud or an ocean wave, but it does exist as one single entity maintained by thousands of connected computers running an Ethereum client.
The Ethereum protocol itself exists solely for the purpose of keeping the continuous, uninterrupted, and immutable operation of this special state machine; It's the environment in which all Ethereum accounts and smart contracts live. At any given block in the chain, Ethereum has one and only one 'canonical' state, and the EVM is what defines the rules for computing a new valid state from block to block.
EVM的物理实例无法以可能指向云或海浪的相同方式来描述,但它确实是由运行以太坊客户端的数千台已连接计算机维护的单个实体而存在。
以太坊协议本身的存在仅仅是为了保持这种特殊状态机的连续,不间断和不变的运行。这是所有以太坊账户和智能合约赖以生存的环境。在链中任何给定的区块上,以太坊只有一个“规范”状态,而EVM定义了计算区块之间新的有效状态的规则。
从账本到状态机
The analogy of a 'distributed ledger' is often used to describe blockchains like Bitcoin, which enable a decentralized currency using fundamental tools of cryptography. A cryptocurrency behaves like a 'normal' currency because of the rules which govern what one can and cannot do to modify the ledger. For example, a Bitcoin address cannot spend more Bitcoin than it has previously received. These rules underpin all transactions on Bitcoin and many other blockchains.
While Ethereum has its own native cryptocurrency (Ether) that follows almost exactly the same intuitive rules, it also enables a much more powerful function: smart contracts. For this more complex feature, a more sophisticated analogy is required. Instead of a distributed ledger, Ethereum is a distributed state machine. Ethereum's state is a large data structure which holds not only all accounts and balances, but a machine state, which can change from block to block according to a pre-defined set of rules, and which can execute arbitrary machine code. The specific rules of changing state from block to block are defined by the EVM.
通常使用“分布式分类帐”的类比来描述像比特币这样的区块链,它使用密码学的基本工具来实现去中心化的货币。加密货币的行为类似于“正常”货币,这是因为规则支配着人们可以做什么和不可以做什么来修改分类账。例如,比特币地址不能花费比以前更多的比特币。这些规则是比特币和许多其他区块链上所有交易的基础。
以太坊拥有自己的本机加密货币(Ether),几乎遵循完全相同的直观规则,但它还启用了更强大的功能:智能合约。对于此更复杂的功能,需要一个更复杂的类比。以太坊不是分布式账本,而是分布式状态机。以太坊的状态是一个大型数据结构,不仅拥有所有账户和余额,而且拥有机器状态,它可以根据一组预定义的规则在不同的块之间变化,并且可以执行任意机器代码。EVM定义在块之间更改状态的特定规则。
以太坊状态转换函数
The EVM behaves as a mathematical function would: Given an input, it produces a deterministic output. It therefore is quite helpful to more formally describe Ethereum as having a state transition function:
Y(S, T)= S'
Given an old valid state (S)
and a new set of valid transactions (T)
, the Ethereum state transition function Y(S, T)
produces a new valid output state S'
状态
In the context of Ethereum, the state is an enormous data structure called a modified Merkle Patricia Trie, which keeps all accounts linked by hashes and reducible to a single root hash stored on the blockchain.
交易
Transactions are cryptographically signed instructions from accounts. There are two types of transactions: those which result in message calls and those which result in contract creation.
Contract creation results in the creation of a new contract account containing compiled smart contract bytecode. Whenever another account makes a message call to that contract, it executes its bytecode.
EVM 指令
The EVM executes as a stack machine with a depth of 1024 items. Each item is a 256-bit word, which was chosen for the ease of use with 256-bit cryptography (such as Keccak-256 hashes or secp256k1 signatures).
During execution, the EVM maintains a transient memory (as a word-addressed byte array), which does not persist between transactions.
Contracts, however, do contain a Merkle Patricia storage trie (as a word-addressable word array), associated with the account in question and part of the global state.
Compiled smart contract bytecode executes as a number of EVM opcodes, which perform standard stack operations like XOR
, AND
, ADD
, SUB
, etc. The EVM also implements a number of blockchain-specific stack operations, such as ADDRESS
, BALANCE
, KECCAK256
, BLOCKHASH
, etc.
EVM 实现
All implementations of the EVM must adhere to the specification described in the Ethereum Yellow paper.
Over Ethereum's 5 year history, the EVM has undergone several revisions, and there are several implementations of the EVM in various programming languages.
All Ethereum clients include an EVM implementation. Additionally there are multiple standalone implementations, including:
- Py-EVM - Python
- evmone - C++
- ethereumjs-vm - JavaScript
- eEVM - C++
- Hyperledger Burrow - Go
5. Gas and Fees
Gas is essential to the Ethereum network. It is the fuel that allows it to operate, in the same way that a car needs gasoline to run.
什么是Gas
Gas refers to the unit that measures the amount of computational effort required to execute specific operations on the Ethereum network.
Since each Ethereum transaction requires computational resources to execute, each transaction requires a fee. Gas refers to the fee required to successfully conduct a transaction on Ethereum
In essence, gas fees are paid in Ethereum's native currency, ether (ETH). Gas prices are denoted in Gwei, which itself is a denomination of ETH - each Gwei is equal to 0.000000001 ETH (10-9 ETH). For example, instead of saying that your gas costs 0.000000001 Ether, you can say your gas costs 1 Gwei.
本质上, gas fees是以太坊的本币以太(ETH)支付的。Gas价格以Gwei表示,Gwei本身是ETH的名称-每个Gwei等于0.000000001 ETH(10 -9 ETH)。例如,您可以说您的汽油成本为1 Gwei,而不是说您的汽油成本为0.000000001 Ether。
为什么要存在Gas fees
In short, gas fees help keep the Ethereum network secure. By requiring a fee for every computation executed on the network, we prevent actors from spamming the network. In order to prevent accidental or hostile infinite loops or other computational wastage in code, each transaction is required to set a limit to how many computational steps of code execution it can use. The fundamental unit of computation is "gas".
Although a transaction includes a limit, any gas not used in a transaction is returned to the user.
6. 节点和客户端
Ethereum is a distributed network of computers running software (known as nodes) that can verify blocks and transaction data. You need an application, known as a client, on your computer to "run" a node.
什么是节点和客户端
"Node" refers to a running piece of client software. A client is an implementation of Ethereum that verifies all transactions in each block, keeping the network secure and the data accurate.
You can see a real-time view of the Ethereum network by looking at this map of nodes.
Many Ethereum clients exist, in a variety of programming languages such as Go, Rust, JavaScript, Python, C# .NET and Java. What these implementations have in common is they all follow a formal specification (originally the Ethereum Yellow Paper). This specification dictates how the Ethereum network and blockchain functions.
节点类型
If you want to run your own node, you should understand that there are different types of node that consume data differently. In fact, clients can run 3 different types of node - light, full and archive. There are also options of different sync strategies which enables faster synchronization time. Synchronization refers to how quickly it can get the most up-to-date information on Ethereum's state.
全节点
- Stores full blockchain data.
- Participates in block validation, verifies all blocks and states.
- All states can be derived from a full node.
- Serves the network and provides data on request.
轻节点
- Stores the header chain and requests everything else.
- Can verify the validity of the data against the state roots in the block headers.
- Useful for low capacity devices, such as embedded devices or mobile phones, which can't afford to store gigabytes of blockchain data.
存档节点
- Stores everything kept in the full node and builds an archive of historical states. Needed if you want to query something like an account balance at block #4,000,000.
- These data represent units of terabytes which makes archive nodes less attractive for average users but can be handy for services like block explorers, wallet vendors, and chain analytics.
Syncing clients in any mode other than archive will result in pruned blockchain data. This means, there is no archive of all historical state but the full node is able to build them on demand.
为什么要运行以太坊节点
Running a node allows you to trustlessly and privately use Ethereum while supporting the ecosystem.
受益于你
Running your own node enables you to use Ethereum in a truly private, self-sufficient and trustless manner. You don't need to trust the network because you can verify the data yourself with your client. "Don't trust, verify" is a popular blockchain mantra.
Your node verifies all the transactions and blocks against consensus rules by itself. This means you don’t have to rely on any other nodes in the network or fully trust them.
You won't have to leak your addresses and balances to random nodes. Everything can be checked with your own client.
Your dapp can be more secure and private if you use your own node. Metamask, MyEtherWallet and some other wallets can be easily pointed to your own local node.
您的节点将验证所有交易,并自行阻止遵守共识规则。这意味着您不必依赖网络中的任何其他节点或完全信任它们。
您不必将地址和余额泄漏给随机节点。一切都可以由您自己的客户检查。
如果使用自己的节点,则dapp可以更安全和私有。Metamask,MyEtherWallet和其他一些钱包可以很容易地指向您自己的本地节点。
网络受益
A diverse set of nodes is important for Ethereum’s health, security and operational resiliency.
- They provide access to blockchain data for lightweight clients that depend on it. In high peaks of usage, there need to be enough full nodes to help light nodes sync. Light nodes don't store the whole blockchain, instead they verify data via the state roots in block headers. They can request more information from blocks if they need it.
- Full nodes enforce the proof-of-work consensus rules so they can’t be tricked into accepting blocks that don't follow them. This provides extra security in the network because if all the nodes were light nodes, which don't do full verification, miners could attack the network and, for example, create blocks with higher rewards.
If you run a full node, the whole Ethereum network benefits from it.
多样化的节点集对于以太坊的健康,安全性和运营弹性至关重要。
- 他们为依赖它的轻量级客户端提供对区块链数据的访问。在使用高峰期,需要有足够的完整节点来帮助灯光节点同步。轻型节点不存储整个区块链,而是通过块头中的状态根来验证数据。他们可以根据需要从块中请求更多信息。
- 完整节点会强制执行工作量证明共识规则,因此它们不会被欺骗来接受不遵循这些规则的块。这提供了网络中的额外安全性,因为如果所有节点都是轻型节点(不进行完全验证),则矿工可能会攻击网络,例如,创建具有更高奖励的区块。
如果您运行一个完整的节点,则整个以太坊网络将从中受益。
运行自己的节点
Projects
Select a client and follow their instructions
ethnode - Run an Ethereum node (Geth or Parity) for local development.
DAppNode - An operating system GUI for running Web3 nodes, including Ethereum and the beacon chain, on a dedicated machine.
Resources
- Running Ethereum Full Nodes: A Complete Guide Nov 7, 2019 - Justin Leroux
- Node Configuration Cheat Sheet Jan 5, 2019 - Afri Schoeden
- How To Install & Run a Geth Node Oct 4, 2020 - Sahil Sen
- How To Install & Run a OpenEthereum (fka. Parity) Node Sept 22, 2020 - Sahil Sen
替代品
Running your own node can be difficult and you don’t always need to run your own instance. In this case, you can use a third party API provider like Infura, Alchemy, or QuikNode. Alternatively ArchiveNode is a community-funded Archive node that hopes to bring archive data on the Ethereum blockchain to independent developers who otherwise couldn't afford it. For an overview of using these services, check out nodes as a services.
If somebody runs an Ethereum node with a public API in your community, you can point your light wallets (like MetaMask) to a community node via Custom RPC and gain more privacy than with some random trusted third party.
On the other hand, if you run a client, you can share it with your friends who might need it.
客户端
The Ethereum community maintains multiple open-source clients, developed by different teams using different programming languages. This makes the network stronger and more diverse. The ideal goal is to achieve diversity without any client dominating to reduce any single points of failure.
This table summarizes the different clients. All of them are actively worked on and pass client tests.
Client | Language | Operating systems | Networks | Sync strategies | State pruning |
---|---|---|---|---|---|
Geth | Go | Linux, Windows, macOS | Mainnet, Görli, Rinkeby, Ropsten | Fast, Full | Archive, Pruned |
OpenEthereum | Rust | Linux, Windows, macOS | Mainnet, Kovan, Ropsten, and more | Warp, Full | Archive, Pruned |
Nethermind | C#, .NET | Linux, Windows, macOS | Mainnet, Görli, Ropsten, Rinkeby, and more | Fast, Full | Archive, Pruned |
Besu | Java | Linux, Windows, macOS | Mainnet, Rinkeby, Ropsten, and Görli | Fast, Full | Archive, Pruned |
Trinity | Python | Linux, macOS | Mainnet, Görli, Ropsten, and more | Full, Beam, Fast/Header | Archive |
For more on supported networks, read up on Ethereum networks.
不同实现的优势
Each client has unique use cases and advantages, so you should choose one based on your own preferences. Diversity allows implementations to be focused on different features and user audiences. You may want to choose a client based on features, support, programming language, or licences.
Go Ethereum
Go Ethereum (Geth for short) is one of the original implementations of the Ethereum protocol. Currently, it is the most widespread client with the biggest user base and variety of tooling for users and developers. It is written in Go, fully open source and licensed under the GNU LGPL v3.
OpenEthereum
OpenEthereum is a fast, feature-rich and advanced CLI-based Ethereum client. It's built to provide the essential infrastructure for speedy and reliable services which require fast synchronisation and maximum up-time. OpenEthereum’s goal is to be the fastest, lightest, and most secure Ethereum client. It provides a clean, modular codebase for:
- easy customisation.
- light integration into services or products.
- minimal memory and storage footprint.
OpenEthereum is developed using the cutting-edge Rust programming language and licensed under the GPLv3.
Nethermind
Nethermind is an Ethereum implementation created with the C# .NET tech stack, running on all major platforms including ARM. It offers great performance with:
- an optimized virtual machine
- state access
- networking and rich features like Prometheus/Graphana dashboards, seq enterprise logging support, JSON RPC tracing, and analytics plugins.
Nethermind also has detailed documentation, strong dev support, an online community and 24/7 support available for premium users.
Besu
Hyperledger Besu is an enterprise-grade Ethereum client for public and permissioned networks. It runs all of the Ethereum mainnet features, from tracing to GraphQL, has extensive monitoring and is supported by ConsenSys, both in open community channels and through commercial SLAs for enterprises. It is written in Java and is Apache 2.0 licensed.
Sync modes
- Full – downloads all blocks (including headers, transactions and receipts) and generates the state of the blockchain incrementally by executing every block.
- Fast (Default) – downloads all blocks (including headers, transactions and receipts), verifies all headers, and downloads the state and verifies it against the headers.
- Light – downloads all block headers, block data, and verifies some randomly.
- Warp sync – Every 5,000 blocks, nodes will take a consensus-critical snapshot of that block’s state. Any node can fetch these snapshots over the network, enabling a fast sync. More on Warp
- Beam sync – A sync mode that allows you to get going faster. It doesn't require long waits to sync, instead it back-fills data over time. More on Beam
- Header sync – you can use a trusted checkpoint to start syncing from a more recent header and then leave it up to a background process to fill the gaps eventually
You define the type of sync when you get set up, like so:
Setting up light sync in GETH
geth --syncmode "light"
Setting up header sync in Trinity
trinity --sync-from-checkpoint eth://block/byhash/0xa65877df954e1ff2012473efee8287252eee956c0d395a5791f1103a950a1e21?score=15,835,269,727,022,672,760,774
硬件
Hardware requirements differ by client but generally are not that high since the node just needs to stay synced. Don't confuse it with mining which requires much more computing power. Sync time and performance do improve with more powerful hardware however. Depending on your needs and wants, Ethereum can be run on your computer, home server, single-board computers or virtual private servers in the cloud.
An easy way to run your own node is using 'plug and play' boxes like DAppNode. It provides hardware for running clients and applications that depend on them with a simple user interface.
要求
Before installing any client, please ensure your computer has enough resources to run it. Minimum and recommended requirements can be found below, however the key part is the disk space. Syncing the Ethereum blockchain is very input/output intensive. It is best to have a solid-state drive (SSD). To run an Ethereum client on HDD, you will need at least 8GB of RAM to use as a cache.
最小要求
- CPU with 2+ cores
- 4 GB RAM minimum with an SSD, 8 GB+ if you have an HDD
- 8 MBit/s bandwidth
推荐要求
- Fast CPU with 4+ cores
- 16 GB+ RAM
- Fast SSD with at least 500 GB free space
- 25+ MBit/s bandwidth
Depending on which software and sync mode are you going to use, hundreds of GBs of disk space is need. Approximate numbers and growth can be found below.
Client | Disk size (fast sync) | Disk size (full archive) |
---|---|---|
Geth | 400GB+ | 6TB+ |
OpenEthereum | 280GB+ | 6TB+ |
Nethermind | 200GB+ | 5TB+ |
Besu | 750GB+ | 5TB+ |
单计算机上的以太坊
The most convenient and cheap way of running Ethereum node is to use a single board computer with ARM architecture like Raspberry Pi. Ethereum on ARM provides images of Geth, Parity, Nethermind, and Besu clients. Here's a simple tutorial on how to build and setup an ARM client.
Small, affordable and efficient devices like these are ideal for running a node at home.
ETH2 客户端
There is a lot of instructions and information about Ethereum clients on the internet, here are few that might be helpful.
- Ethereum 101 - Part 2 - Understanding Nodes – Wil Barnes, 13 February 2019
- Running Ethereum Full Nodes: A Guide for the Barely Motivated – Justin Leroux, 7 November 2019
- Running an Ethereum Node – ETHHub, updated often
- Analyzing the hardware requirements to be an Ethereum full validated node – Albert Palau, 24 September 2018
- Running a Hyperledger Besu Node on the Ethereum Mainnet: Benefits, Requirements, and Setup – Felipe Faraggi, 7 May 2020
6.1 运行一个节点
Running your own node provides you various benefits, opens new possibilities, and helps to support the ecosystem. This page will guide you through spinning up your own node and taking part in validating Ethereum transactions.
选择一个方法
The first step in spinning up your node is choosing your approach. You have to choose the client (the software), the environment, and the parameters you want to start with. See all the available mainnet clients.
Client settings
Client implementations enable different sync modes and various other options. Sync modes represent different methods of downloading and validating blockchain data. Before starting the node, you should decide what network and sync mode to use. The most important things to consider is the disk space and sync time client will need.
All features and options can be found in documentation of each client. Various client configurations can be set by executing client with corresponding flags. You can get more information on flags from EthHub or client documentation. For testing purposes, you might prefer running client on one of testnet networks. See overview of supported networks.
Environment and hardware
Local or cloud
Ethereum clients are able to run on consumer grade computers and don't require special hardware like mining for example. Therefore you have various options for deploying based on your needs. To simplify let's think about running a node on both a local physical machine and a cloud server:
- Cloud
- Providers offer high server uptime, static public IP addresses
- Getting dedicated or virtual server can be more comfortable then building your own
- Trade off is trusting a third party - server provider
- Because of required storage size for full node, price of a rented server might get high
- Own hardware
- More trustless and sovereign approach
- One time investment
- An option to buy preconfigured machines
- You have to physically prepare, maintain, and potentially troubleshoot the machine
Both options have different advantages summed up above. If you are looking for a cloud solution, in addition to many traditional cloud computing providers, there are also services focused on deploying nodes, for example:
Hardware
However, a censorship-resistant, decentralized network should not rely on cloud providers. It's healthier for the ecosystem if you run your own node on hardware. The easiest options are preconfigured machines like:
Check the minimum and recommended disk space requirements for each client and sync mod. Generally, modest computing power should be enough. The problem is usually drive speed. During initial sync, Ethereum clients perform a lot of read/write operations, therefore SSD is strongly recommended. A client might not even be able to sync current state on HDD and get stuck a few blocks behind mainnet. You can run most of the clients on a single board computer with ARM. You can also use the Ethbian operating system for Raspberry Pi 4. This lets you [run a client by flashing the SD card. Based on your software and the hardware choices, the initial synchronization time and storage requirements may vary. Be sure to check sync times and storage requirements. Also make sure your internet connection is not limited by a bandwidth cap. It's recommended to use an unmetered connection since initial sync and data broadcasted to the network could exceed your limit.
Operating system
All clients support major operating systems - Linux, MacOS, Windows. This means you can run nodes on regular desktop or server machines with the operating system (OS) that suits you the best. Make sure your OS is up to date to avoid potential issues and security vulnerabilities.
部署节点
Getting the client software
First, download your preferred client software
You can simply download an executable application or installation package which suits your operating system and architecture. Always verify signatures and checksums of downloaded packages. Some clients also offer repositories for easier installation and updates. If you prefer, you can build from source. All of the clients are open source so you can build them from source code with the proper compiler.
Executable binaries for stable mainnet client implementations can be downloaded from their release pages:
Starting the client
Before starting Ethereum client software, perform a last check that your environment is ready. For example, make sure:
- There is enough disk space considering chosen network and sync mode.
- Memory and CPU is not halted by other programs.
- Operating system is updated to latest version.
- System has correct time and date.
- Your router and firewall accept connections on listening ports. By default Ethereum clients use a listener (TCP) port and a discovery (UDP) port, both on 30303 by default.
Run your client on a testnet first to help make sure everything is working correctly. Running a Geth light node should help. You need to declare any client settings that aren't default at the start. You can use flags or the config file to declare your preferred configuration. Check out your client's documentation for the specifics Client execution will initiate its core functions, chosen endpoints, and start looking for peers. After successfully discovering peers, the client starts synchronization. Current blockchain data will be available once the client is successfully synced to the current state.
Using the client
Clients offer RPC API endpoints that you can use to control the client and interact with the Ethereum network in various ways:
- Manually calling them with a suitable protocol (e.g. using
curl
) - Attaching a provided console (e.g.
geth attach
) - Implementing them in applications
Different clients have different implementations of the RPC endpoints. But there is a standard JSON-RPC which you can use with every client. For an overview read the JSON-RPC docs. Applications that need information from the Ethereum network can use this RPC. For example, popular wallet MetaMask lets you run a local blockchain instance and connect to it.
Reaching RPC
The default port of JSON-RPC is 8545
but you can modify the ports of local endpoints in the config file. By default, the RPC interface is only reachable on the localhost of your computer. To make it remotely accessible, you might want to expose it to the public by changing the address to 0.0.0.0
. This will make it reachable over local and public IP addresses. In most cases you'll also need to set up port forwarding on your router.
You should do this with caution as this will let anyone on the internet control your node. Malicious actors could access your node to bring down your system or steal your funds if you're using your client as a wallet.
A way around this is to prevent potentially harmful RPC methods from being modifiable. For example, with geth
, you can declare modifiable methods with a flag: --http.api web3,eth,txpool
.
You can also host access to your RPC interface by pointing service of web server, like Nginx, to your client's local address and port.
The most privacy-preserving and simple way to set up a publicly reachable endpoint, you can host it on your own Tor onion service. This will let you reach the RPC outside your local network without a static public IP address or opened ports. To do this:
- Install
tor
- Edit
torrc
config to enable hidden service with address of your client's RPC address and port - Restart
tor
service
Once you restart Tor, you'll get hidden service keys and a hostname in your desired directory. From then, your RPC will be reachable on a .onion
hostname.
Operating the node
You should regularly monitor your node to make sure it's running properly. You may need to do occasional maintenance.
Keeping node online
Your node doesn't have to be online nonstop but you should keep it online as much as possible to keep it in sync with the network. You can shut it down to restart it but keep in mind that:
- Shutting down can take up to a few minutes if the recent state is still being written on disk.
- Forced shut downs can damage the database.
- Your client will go out of sync with the network and will need to resync when you restart it.
This doesn't apply on Eth2 validator nodes. Taking your node offline will affect all services dependent on it. If you are running a node for staking purposes you should try to minimize downtime as much as possible.
您的节点不一定必须不间断在线,但您应尽可能使它保持在线状态,以使其与网络保持同步。您可以关闭它以重新启动它,但请记住:
- 如果最近的状态仍在磁盘上,则关闭可能需要花费几分钟。
- 强制关闭会损坏数据库。
- 您的客户端将与网络不同步,并且在重新启动时需要重新同步。
这不适用于Eth2验证程序节点。使您的节点脱机将影响所有依赖于该节点的服务。如果要出于放样目的而运行节点,则应尽量减少停机时间。
Creating client service
Consider creating a service to run your client automatically on startup. For example on Linux servers, good practice would be creating a service that executes the client with proper config, under user with limited privileges and automatically restarts.
Updating client
You need to keep your client software up-to-date with the latest security patches, features, and EIPs. Especially before hard forks, make sure you are running the correct client version.
您需要使用最新的安全补丁,功能和EIP使客户端软件保持最新。特别是在硬分叉之前,请确保您运行的是正确的客户端版本。
Running additional services
Running your own node lets you use services that require direct access to Ethereum client RPC. These are services built on top of Ethereum like layer 2 solutions, Eth2 clients, and other Ethereum infrastructure.
运行自己的节点使您可以使用需要直接访问以太坊客户端RPC的服务。这些服务是建立在以太坊之上的服务,例如第2层解决方案,Eth2客户端和其他以太坊基础架构。
Monitoring the node
"To properly monitor your node, consider collecting metrics. Clients provide metrics endpoints so you can get comprehensive data about your node. Use tools like InfluxDB or Prometheus to create databases which you can turn into visualizations and charts in software like Grafana. There are many setups for using this software and different Grafana dashboards for you to visualise your node and the network as a whole. TAs part of your monitoring, make sure to keep an eye on your machine's performance. During your node's initial sync, the client software may be very heavy on CPU and RAM. In addition to Grafana, you can use the tools your OS offers like htop
or uptime
to do this.
“要正确监视节点,请考虑收集指标。客户端提供指标端点,以便您可以获取有关节点的全面数据。使用InfluxDB或Prometheus之类的工具来创建数据库,然后可以在诸如Grafana的软件中将其转变为可视化效果和图表。使用此软件的设置以及不同的Grafana仪表板,以使您的节点和整个网络可视化。作为监控的一部分,请务必注意计算机的性能。在节点的初始同步期间,客户端软件可能是除了Grafana之外,您还可以使用操作系统提供的类似工具htop
或uptime
执行此操作。
6.2 节点作为服务
Running your own Ethereum node can be challenging, especially when getting started or while scaling fast. There are a number of services that run optimized node infrastructures for you, so you can focus on developing your application or product instead. We'll explain how node services work, the pros and cons for using them and list providers if you are interested in getting started.
怎样工作
Node service providers run distributed node clients behind the scenes for you, so you don't have to.
These services typically provide an API key that you can use to write to and read from the blockchain. They often including access to Ethereum testnets in addition to the mainnet.
Some services offer you your own dedicated node that they manage for you, while others use load balancers to distribute activity across nodes.
Almost all node services are extremely easy to integrate with, involving one line changes in your code to swap out your self hosted node, or even switch between the services themselves.
Often times node services will run a variety of node clients and types, allowing you to access full and archive nodes in addition to client specific methods in one API.
It's important to note that node services do not and should not store your private keys or information.
节点服务提供商为您在后台运行分布式节点客户端,因此您不必这样做。
这些服务通常提供一个API密钥,您可以使用该API密钥来写入和读取区块链。除主网外,它们通常还包括对以太坊测试网的访问。
一些服务为您提供自己的专用节点,由它们为您管理,而其他服务则使用负载平衡器在节点之间分配活动。
几乎所有节点服务都非常易于集成,涉及到代码中的一行更改以换出您自己的托管节点,甚至在服务本身之间进行切换。
通常,节点服务将运行各种节点客户端和类型,从而允许您在一个API中访问除客户端特定方法之外的完整节点和存档节点。
重要的是要注意,节点服务不也不应存储您的私钥或信息。
好处
The main benefit for using a node service is not having to spend engineering time maintaining and managing nodes yourself. This allows you to focus on building your product rather than having to worry about infrastructure maintenance.
Running your own nodes can be very expensive from storage to bandwidth to valuable engineering time. Things like spinning up more nodes when scaling, upgrading nodes to the latest versions, and ensuring state consistency, can detract from building and spending resources on your desired web3 product.
缺点
By using a node service you are centralizing the infrastructure aspect of your product. For this reason, projects that hold decentralization to the upmost importance might prefer self-hosting nodes rather than outsourcing to a 3rd party.
Read more about the benefits of running your own node.
热门节点服务
-
Alchemy
- Docs
- Features
- Free tier option
- Scale as you go
- Free archival data
- Analytics tools
- Dashboard
- Unique API endpoints
- Webhooks
- Direct support
-
BlockDaemon
- Docs
- Benefits
- Dashboard
- Per node basis
- Analytics
-
Chainstack
- Docs
- Features
- Free shared nodes
- Shared archive nodes
- GraphQL support
- RPC and WSS endpoints
- Dedicated full and archive nodes
- Fast sync time for dedicated deployments
- Bring your cloud
- Pay-per-hour pricing
- Direct 24/7 support
-
GetBlock
- Docs
- Features
- Access to 40+ blockchain nodes
- 40K free daily requests
- Unlimited number of API keys
- High connection speed at 1GB/sec
- Trace+Archive
- Advanced analytics
- Automated updates
- Technical support
-
Infura
- Docs
- Features
- Free tier option
- Scale as you go
- Paid archival data
- Direct Support
- Dashboard
-
QuikNode
- Features
- 7 day free trial
- Varied support
- Webhooks
- Dashboard
- Analytics
- Features
-
Rivet
- Docs
- Features
- Free tier option
- Scale as you go
7. 网络
Since Ethereum is a protocol, this means there can be multiple independent "networks" conforming to this protocol that do not interact with each other.
Networks are different Ethereum environments you can access for development, testing, or production use cases. Your Ethereum account will work across the different networks but your account balance and transaction history wont carry over from the main Ethereum network. For testing purposes, it's useful to know which networks are available and how to get testnet ETH so you can play around with it.
由于以太坊是一种协议,因此这意味着可以有多个独立的“网络”与该协议兼容,并且彼此之间不会相互作用。
网络是您可以访问的不同以太坊环境,用于开发,测试或生产用例。您的以太坊账户将在不同的网络上运行,但您的账户余额和交易历史记录不会从主要的以太坊网络中继承下来。出于测试目的,了解哪些网络可用以及如何获取testnet ETH很有用,以便您可以试用它。
公共网络
Public networks are accessible to anyone in the world with an internet connection. Anyone can read or create transactions on a public blockchain and validate the transactions being executed. Agreement on transactions and the state of the network is decided by a consensus of peers.
Mainnet
Mainnet is the primary public Ethereum production blockchain, where actual-value transactions occur on the distributed ledger.
When people and exchanges discuss ETH prices, they're talking about mainnet ETH.
Testnets
In addition to mainnet, there are public testnets. These are networks used by protocol developers or smart contract developers to test both protocol upgrades as well as potential smart contracts in a production-like environment before deployment to mainnet. Think of this as an analog to production versus staging servers.
It’s generally important to test any contract code you write on a testnet before deploying to the mainnet. If you're building a dapp that integrates with existing smart contracts, most projects have copies deployed to testnests that you can interact with.
Most testnets use a proof-of-authority consensus mechanism. This means a small number of nodes are chosen to validate transactions and create new blocks – staking their identity in the process. It's hard to incentivise mining on a proof-of-work testnet which can leave it vulnerable.
除主网外,还有公共测试网。这些是协议开发人员或智能合约开发人员使用的网络,用于在部署到主网之前在类似生产的环境中测试协议升级以及潜在的智能合约。可以将其视为生产服务器与登台服务器的模拟。
通常,在部署到主网上之前,测试您在测试网上编写的所有合同代码都是很重要的。如果您要构建一个与现有智能合约集成的dapp,则大多数项目都将副本部署到您可以与之交互的测试对象上。
大多数测试网都使用权威证明共识机制。这意味着选择了少数节点来验证交易并创建新的块,从而在过程中保全其身份。很难激励在工作量证明测试网上进行挖掘,这可能会使它容易受到攻击。
Görli
A proof-of-authority testnet that works across clients.
Kovan
A proof-of-authority testnet for those running OpenEthereum clients.
Rinkeby
A proof-of-authority testnet for those running Geth client.
Ropsten
A proof-of-work testnet. This means it's the best like-for-like representation of Ethereum.
Testnet Faucets
ETH on testnets has no real value; therefore, there are no markets for testnet ETH. Since you need ETH to actually interact with Ethereum, most people get testnet ETH from faucets. Most faucets are webapps where you can input an address which you request ETH to be sent to.
测试网上的ETH没有实际价值;因此,testnet ETH没有市场。由于您需要ETH与以太坊进行实际交互,因此大多数人都从水龙头那里获得了testnet ETH。大多数水龙头都是webapp,您可以在其中输入请求将ETH发送到的地址。
私有网络
An Ethereum network is a private network if its nodes are not connected to a public network (i.e. mainnet or a testnet). In this context, private only means reserved or isolated, rather than protected or secure.
Development networks
To develop an Ethereum application, you'll want to run it on a private network to see how it works before deploying it. Similar to how you create a local server on your computer for web development, you can create a local blockchain instance to test your dapp. This allows for much faster iteration than a public testnet.
There are projects and tools dedicated to assist with this. Learn more about development networks.
Consortium networks
The consensus process is controlled by a pre-defined set of nodes that are trusted. For example, a private network of known academic institutions that each govern a single node, and blocks are validated by a threshold of signatories within the network.
If a public Ethereum network is like the public internet, you can think of a consortium network as a private intranet.
8. 共识机制
When it comes to blockchains like Ethereum, which are in essence distributed databases, the nodes of the network must be able to reach agreement on the current state of the system. This is achieved using consensus mechanisms.
Although not a part of building a dapp, understanding consensus mechanisms will help explain things that are relevant to you and your users' experience, like gas prices and transaction times.
什么是共识机制
Consensus mechanisms (also known as consensus protocols or consensus algorithms) allow distributed systems (networks of computers) to work together and stay secure.
For decades, these mechanisms have been used to establish consensus among database nodes, application servers, and other enterprise infrastructure. In recent years, new consensus protocols have been invented to allow cryptoeconomic systems, such as Ethereum, to agree on the state of the network.
A consensus mechanism in a cryptoeconomic system also helps prevent certain kinds of economic attacks. In theory, an attacker can compromise consensus by controlling 51% of the network. Consensus mechanisms are designed to make this "51% attack" unfeasible. Different mechanisms are engineered to solve this security problem differently.
密码经济系统中的共识机制也有助于防止某些类型的经济攻击。从理论上讲,攻击者可以通过控制51%的网络来破坏共识。共识机制旨在使这种“ 51%攻击”不可行。设计了不同的机制来不同地解决此安全问题。
共识机制类型
Proof of work
Ethereum, like Bitcoin, currently uses a proof-of-work (PoW) consensus protocol.
Block creation
Proof-of-work is done by miners, who compete to create new blocks full of processed transactions. The winner shares the new block with the rest of the network and earns some freshly minted ETH. The race is won by whoever's computer can solve a math puzzle fastest – this produces the cryptographic link between the current block and the block that went before. Solving this puzzle is the work in "proof of work".
Security
The network is kept secure by the fact that you'd need 51% of the network's computing power to defraud the chain. This would require such huge investments in equipment and energy, you're likely to spend more than you'd gain.
More on proof-of-work (PoW)
Proof of stake
Ethereum has plans to upgrade to a proof-of-stake (PoS) consensus protocol.
Block creation
Proof-of-stake is done by validators who have staked ETH to participate in the system. A validator is chosen at random to create new blocks, share them with the network and earn rewards. Instead of needing to do intense computational work, you simply need to have staked your ETH in the network. This is what incentivises healthy network behaviour.
权益证明是由已抵押ETH参与系统的验证者完成的。随机选择一个验证器来创建新块,与网络共享它们并获得奖励。无需进行大量的计算工作,您只需要将ETH放入网络中即可。这就是增强健康网络行为的原因。
Security
A proof-of-stake system is kept secure by the fact that you'd need 51% of the total staked ETH to defraud the chain. And that your stake is slashed for malicious behaviour.
事实证明您需要抵押的ETH总量的51%来欺骗链条,从而确保了权益证明系统的安全。而且,您的赌注也因恶意行为而大为减少。
More on proof-of-stake (PoS)
8.1 工作量证明
Ethereum, like Bitcoin, currently uses a consensus protocol called Proof-of-work (PoW). This allows the nodes of the Ethereum network to agree on the state of all information recorded on the Ethereum blockchain, and prevents certain kinds of economic attacks.
Over the next few years, proof-of-work will be phased out in favour of proof of stake. This will also phase out mining from Ethereum. For more details on timing, check the progress of the Eth2 merge upgrade.
什么是工作量证明
Proof of Work (PoW) is the mechanism that allows the decentralized Ethereum network to come to consensus, or agree on things like account balances and the order of transactions. This prevents users "double spending" their coins and ensures that the Ethereum chain is incredibly difficult to attack or overwrite.
工作量证明和矿工
Proof-of-work is the underlying algorithm that sets the difficulty and rules for the work miners do. Mining is the "work" itself. It's the act of adding valid blocks to the chain. This is important because the chain's length helps the network spot the valid Ethereum chain and understand Ethereum's current state. The more "work" done, the longer the chain, and the higher the block number, the more certain the network can be of the current state of things.
工作量证明是为矿工设定难度和规则的基础算法。采矿本身就是“工作”。这是向链中添加有效块的行为。这一点很重要,因为链的长度有助于网络发现有效的以太坊链并了解以太坊的当前状态。完成的“工作”越多,链条越长,块数越高,网络就可以更加确定当前状态。
以太坊的工作量证明如何工作?
Ethereum transactions are processed into blocks. Each block has a:
- block difficulty – for example: 3,324,092,183,262,715
- mixHash – for example:
0x44bca881b07a6a09f83b130798072441705d9a665c5ac8bdf2f39a3cdf3bee29
- nonce – for example:
0xd3ee432b4fb3d26b
This block data is directly related to PoW.
The work in proof of work
The proof-of-work protocol, known as Ethash, requires miners to go through an intense race of trial and error to find the nonce for a block. Only blocks with a valid nonce can be added to the chain.
When racing to create a block, a miner will repeatedly put a dataset, that you can only get from downloading and running the full chain (as a miner does), through a mathematical function. This is to generate a mixHash that is below a target nonce, as dictated by the block difficulty. The best way to do this is through trial and error.
The difficulty determines the target for the hash. The lower the target, the smaller the set of valid hashes. Once generated, this is incredibly easy for other miners and clients to verify. Even if one transaction was to change, the hash would be completely different, signalling fraud.
Hashing makes fraud easy to spot. But PoW as a process is also a big deterrent to attacking the chain.
Proof-of-work and security
Miners are incentivised to do this work on the main Ethereum chain. There is little incentive for a subset of miners to start their own chain – it undermines the system. Blockchains rely on having a single state as a source of truth. And users will always choose the longest or "heaviest" chain.
The objective of PoW is to extend the chain. The longest chain is most believable as the valid one because it's had the most computational work done on it. Within Ethereum's PoW system it's nearly impossible to create new blocks that erase transactions or create fake ones, or maintain a second chain. That's because a malicious miner would need to always be solving the block nonce faster than everyone else.
To consistently create malicious, yet valid, blocks, you'd need over 51% of the network mining power to beat everyone else. You'd need a lot of computing power to be able to do this amount of "work". And the energy spend might even outweigh the gains you'd make in an attack.
激励矿工在以太坊主链上进行这项工作。一部分矿工建立自己的链,几乎没有动力–这破坏了该系统。区块链依赖于将单一状态作为真理的来源。用户将始终选择最长或“最重”的链。
PoW的目标是延长链条。最长的链是有效链,因此最可信,因为它已完成了最多的计算工作。在以太坊的PoW系统中,几乎不可能创建新块来擦除交易,创建假交易或维持第二条链。这是因为恶意矿工将始终需要比其他所有人更快地解决区块随机数。
为了持续创建恶意但有效的阻止,您需要超过51%的网络挖掘能力才能击败其他所有人。您需要大量的计算能力才能完成这一“工作”。而且能量消耗甚至可能超过您在攻击中所获得的收益。
Proof-of-work economics
PoW is also responsible for issuing new currency into the system and incentivising miners to do the work.
Miners who successfully create a block are rewarded in 2 freshly minted ETH and all the transaction fees within the block. A miner may also get 1.75ETH for an uncle block. This is a valid block, created simultaneously to the succcessful block, by another miner. This usually happens due to network latency.
PoW还负责向系统中发行新货币并激励矿工从事这项工作。
成功创建区块的矿工将获得2个新鲜铸造的ETH以及该区块内的所有交易费用的奖励。矿工还可以获得1.75ETH的叔叔块。这是另一个矿工与成功块同时创建的有效块。这通常是由于网络延迟而发生的。
最后
In distributed networks, a transaction has "finality" when it's part of a block that can't change.
Because miners work in a decentralized way, it's possible for two valid blocks to be mined at the same time. This creates a temporary fork. Eventually one chain will become the accepted chain once a subsequent block has been mined and added, making it longer.
But to complicate things further, transactions that were rejected on the temporary fork may have been included in the accepted chain. This means it could get reversed. So finality refers to the time you should wait before considering a transaction irreversible. For Ethereum the recommended time is 6 blocks or just over 1 minute. Following that you can say with relative confidence that the transaction has been a success. Of course, you can wait longer for even greater assurances.
This is something to bear in mind when designing dapps, as it would be a poor user experience to misrepresent transaction information to your users. Especially if the transaction is high value.
Remember, this timing doesn't include the wait times for having a transaction picked up by a miner.
在分布式网络中,当事务是不可更改的块的一部分时,它具有“最终性”。
由于矿工以分散的方式工作,因此有可能同时开采两个有效区块。这将创建一个临时叉。最终,一旦挖掘并添加了下一个块,则一条链将成为可接受的链,从而使链更长。
但是,更复杂的是,在临时分支上被拒绝的交易可能已包含在接受的链中。这意味着它可能会被逆转。因此,确定性是指您在考虑不可逆交易之前应等待的时间。对于以太坊,建议的时间是6块或刚好超过1分钟。之后,您可以相对确信地说该交易已成功。当然,您可以等待更长的时间以获得更大的保证。
设计dapp时要牢记这一点,因为将用户错误地表示交易信息会给用户带来糟糕的体验。特别是如果交易是高价值的。
请记住,这个时间不包括矿工提起交易的等待时间。
优缺点
Pros | Cons |
---|---|
PoW is neutral. You don't need ETH to get started and block rewards allow you to go from 0ETH to a positive balance. With proof of stake you need ETH to start with. | PoW uses up so much energy that it's bad for the environment. |
PoW is a tried and tested consensus mechanism that has kept Bitcoin and Ethereum secure and decentralized for many years. | If you want to mine, you need such specialized equipment that it's a big investment to start. |
Compared to proof-of-stake it's relatively easy to implement. | Due to increasing computation needed, mining pools could potentially dominate the mining game, leading to centralization and security risks. |
优点 | 缺点 |
---|---|
PoW是中性的。您不需要ETH上手,而区块奖励可以使您从0ETH达到正余额。有了股权证明,您需要ETH入手。 | PoW消耗了太多能量,对环境不利。 |
PoW是一种久经考验的共识机制,已使比特币和以太坊安全并分散了许多年。 | 如果您想进行开采,则需要如此专业的设备,这是一项巨大的投资。 |
与权益证明相比,它相对容易实现。 | 由于需要增加的计算量,采矿池可能会主导采矿游戏,从而导致集中化和安全风险。 |
与PoS比
At a high level, proof-of-stake has the same end goal as proof-of-work: to help the decentralized network reach consensus, securely. But it has some differences in process and personnel:
PoS switches out the importance of computational power for staked ETH.
PoS replaces miners with validators. Validators stake their ETH to activate the ability to create new blocks.
Validators don't compete to create blocks, instead they are chosen at random by an algorithm.
Finality is clearer: at certain checkpoints, if 2/3 validators agree on the state of the block it is considered final. Validators must bet their entire stake on this, so if they try to collude down the line, they'll lose their entire stake.
PoS切换了对抵押ETH的计算能力的重要性。
PoS将矿工替换为验证人。验证者通过投入其ETH来激活创建新区块的能力。
验证程序不竞争创建块,而是由算法随机选择它们。
最终性更加明确:在某些检查点,如果2/3验证者对块的状态达成共识,则将其视为最终状态。验证者必须将全部赌注都押在此上,因此,如果他们试图串通一局,就会失去全部赌注。
8.1.1 矿工
以太坊挖矿是什么?
Mining is the process of creating a block of transactions to be added to the Ethereum blockchain.
Ethereum, like Bitcoin, currently uses a proof-of-work (PoW) consensus mechanism. Mining is the lifeblood of proof-of-work. Ethereum miners - computers running software - using their time and computation power to process transactions and produce blocks.
为什么矿工存在?
In decentralized systems like Ethereum, we need to ensure that everyone agrees on the order of transactions. Miners help this happen by solving computationally difficult puzzles in order to produce blocks, which serves as a way to secure the network from attacks.
以太坊交易如何开采
- A user writes and signs a transaction request with the private key of some account.
- The user broadcasts the transaction request to the entire Ethereum network from some node.
- Upon hearing about the new transaction request, each node in the Ethereum network adds the request to their local mempool, a list of all transaction requests they’ve heard about that have not yet been committed to the blockchain in a block.
- At some point, a mining node aggregates several dozen or hundred transaction requests into a potential block, in a way that maximizes the transaction fees they earn while still staying under the block gas limit. The mining node then:
- Verifies the validity of each transaction request (i.e. no one is trying to transfer ether out of an account they haven’t produced a signature for, the request is not malformed, etc.), and then executes the code of the request, altering the state of their local copy of the EVM. The miner awards the transaction fee for each such transaction request to their own account.
- Begins the process of producing the Proof-of-Work “certificate of legitimacy” for the potential block, once all transaction requests in the block have been verified and executed on the local EVM copy.
- Eventually, a miner will finish producing a certificate for a block which includes our specific transaction request. The miner then broadcasts the completed block, which includes the certificate and a checksum of the claimed new EVM state.
- Other nodes hear about the new block. They verify the certificate, execute all transactions on the block themselves (including the transaction originally broadcasted by our user), and verify that the checksum of their new EVM state after the execution of all transactions matches the checksum of the state claimed by the miner’s block. Only then do these nodes append this block to the tail of their blockchain, and accept the new EVM state as the canonical state.
- Each node removes all transactions in the new block from their local mempool of unfulfilled transaction requests.
- New nodes joining the network download all blocks in sequence, including the block containing our transaction of interest. They initialize a local EVM copy (which starts as a blank-state EVM), and then go through the process of executing every transaction in every block on top of their local EVM copy, verifying state checksums at each block along the way.
Every transaction is mined (included in a new block and propagated for the first time) once, but executed and verified by every participant in the process of advancing the canonical EVM state. This highlights one of the central mantras of blockchain: Don’t trust, verify.
- 用户用某个帐户的私钥编写并签署交易请求。
- 用户从某个节点向整个以太坊网络广播交易请求。
- 听说新的交易请求后,以太坊网络中的每个节点都会将该请求添加到其本地内存池中,这是他们所听说的尚未提交到区块链中的所有交易请求的列表。
- 在某个时候,一个采矿节点将数十个或数百个交易请求聚合到一个潜在的区块中,以最大程度地使他们赚取的交易费用保持在区块天然气限制之下。然后,挖掘节点:
- 验证每个交易请求的有效性(即,没有人试图将以太币从他们没有为其生成签名的帐户中转出,该请求没有格式错误等),然后执行请求的代码,更改他们的EVM本地副本的状态。矿工将每个此类交易请求的交易费用奖励给他们自己的帐户。
- 一旦验证了区块中的所有交易请求并在本地EVM副本上执行了该代码,便开始为该潜在区块生成工作量证明“合法性证明”。
- 最终,一个矿工将为包含我们特定交易请求的区块完成证书的生产。矿工然后广播完成的块,该块包括证书和要求保护的新EVM状态的校验和。
- 其他节点将听到有关新块的信息。他们验证证书,自己执行区块上的所有交易(包括最初由我们的用户广播的交易),并在执行所有交易后验证其新EVM状态的校验和与矿机区块要求的状态的校验和相匹配。 。然后,这些节点才将此块附加到其区块链的尾部,并接受新的EVM状态作为规范状态。
- 每个节点将从其未完成的事务请求的本地内存池中删除新块中的所有事务。
- 加入网络的新节点将按顺序下载所有块,包括包含我们感兴趣的交易的块。他们初始化本地EVM副本(以空白状态EVM开头),然后执行在其本地EVM副本顶部的每个块中执行每个事务的过程,并在此过程中验证每个块的状态校验和。
每个事务都被挖掘一次(包含在一个新块中,并且第一次传播),但是在推进标准EVM状态的过程中,每个参与者都执行并验证了该事务。这凸显了区块链的中心口号之一:不信任,验证。
8.2 股权证明
Ethereum is moving to a consensus mechanism called proof-of-stake (PoS) from proof-of-work (PoW). This was always the plan as it's a key part in the community's strategy to scale Ethereum via the Eth2 upgrades. However getting PoS right is a big technical challenge and not as straightforward as using PoW to reach consensus across the network.
什么是权益证明(POS)
Proof of stake is a type of consensus mechanism used by blockchain networks to achieve distributed consensus.
It requires users to stake their ETH to become a validator in the network. Validators are responsible for the same thing as miners in proof-of-work: ordering transactions and creating new blocks so that all nodes can agree on the state of the network.
Proof-of-stake comes with a number of improvements to the proof-of-work system:
better energy efficiency – you don't need to use lots of energy mining blocks
lower barriers to entry, reduced hardware requirements – you don't need elite hardware to stand a chance of creating new blocks
stronger immunity to centralization – proof-of-stake should lead to more nodes in the network
stronger support for shard chains – a key upgrade in scaling the Ethereum network
更高的能源效率–您无需使用大量的能源开采块
降低进入门槛,降低硬件要求–您不需要精良的硬件就可以创建新模块
对集中化的抵抗力更强–权益证明应导致网络中更多的节点
增强对分片链的支持–扩展以太坊网络的关键升级
权益证明,权益和验证器
Proof-of-stake is the underlying mechanism that activates validators upon receipt of enough stake. For Ethereum, users will need to stake 32 ETH to become a validator. Validators are chosen at random to create blocks and are responsible for checking and confirming blocks they don't create. A user's stake is also used as a way to incentivise good validator behavior. For example, a user can lose a portion of their stake for things like going offline (failing to validate) or their entire stake for deliberate collusion.
股权证明是一种基础机制,可在收到足够的赌注后激活验证程序。对于以太坊,用户将需要投入32 ETH才能成为验证者。验证者是随机选择的以创建块,并负责检查和确认未创建的块。用户的股份也被用作激励良好验证者行为的一种方式。例如,用户可能因为脱机(无法验证)而失去部分股份,或者因故意串通而失去全部股份。
以太坊的权益证明如何运作?
Unlike proof-of-work, validators don't need to use significant amounts of computational power because they're selected at random and aren't competing. They don't need to mine blocks; they just need to create blocks when chosen and validate proposed blocks when they're not. This validation is known as attesting. You can think of attesting as saying "this block looks good to me." Validators get rewards for proposing new blocks and for attesting to ones they've seen.
If you attest to malicious blocks, you lose your stake.
与工作量证明不同,验证器不需要使用大量的计算能力,因为它们是随机选择的,并且不会竞争。他们不需要挖块。他们只需要在选择时创建块,然后在未选择时验证提议的块即可。此验证称为证明。您可以认为证明是说“此区块对我而言很好”。验证者通过提出新的块并证明他们所看到的块而获得奖励。
如果您证明存在恶意阻止,那么您将失去赌注。
The beacon chain
When Ethereum replaces proof-of-work with proof-of-stake, there will be the added complexity of shard chains. These are separate blockchains that will need validators to process transactions and create new blocks. The plan is to have 64 shard chains, with each having a shared understanding of the state of the network. As a result, extra coordination is necessary and will be done by the beacon chain.
The beacon chain receives state information from shards and makes it available for other shards, allowing the network to stay in sync. The beacon chain will also manage the validators from registering their stake deposits to issuing their rewards and penalties.
Here's how that process works.
当以太坊用工作量证明代替工作量证明时,分片链会变得更加复杂。这些是独立的区块链,将需要验证程序来处理交易并创建新的区块。该计划将拥有64个分片链,每个分片链对网络状态都有共同的了解。结果,额外的协调是必要的,并且将由信标链来完成。
信标链从分片接收状态信息,并使状态信息可用于其他分片,从而使网络保持同步。信标链还将管理验证者,从注册其股份存款到颁发其奖励和罚款。
这是该过程的工作方式。
How validation works
When you submit a transaction on a shard, a validator will be responsible for adding your transaction to a shard block. Validators are algorithmically chosen by the beacon chain to propose new blocks.
当您在分片上提交交易时,验证程序将负责将您的交易添加到分片块中。信标链通过算法选择验证器以提出新的块。
Attestation
If a validator isn't chosen to propose a new shard block, they'll have to attest to another validator's proposal and confirm that everything looks as it should. It's the attestation that is recorded in the beacon chain rather than the transaction itself.
At least 128 validators are required to attest to each shard block – this is known as a "committee."
The committee has a time-frame in which to propose and validate a shard block. This is known as a "slot." Only one valid block is created per slot, and there are 32 slots in an "epoch." After each epoch, the committee is disbanded and reformed with different, random participants. This helps keep shards safe from committees of bad actors.
该委员会有一个提出建议和验证分片的时间表。这称为“插槽”。每个插槽仅创建一个有效块,并且“时代”中有32个插槽。在每个时期之后,委员会将解散,并由不同的随机参与者进行改革。这有助于使碎片免受不良行为者委员会的伤害。
Crosslinks
Once a new shard block proposal has enough attestations, a "crosslink" is created which confirms the inclusion of the block and your transaction in the beacon chain.
Once there's a crosslink, the validator who proposed the block gets their reward.
一旦新的分片阻止提议具有足够的证明,便会创建一个“交叉链接”,以确认该阻止和您的交易在信标链中的包含。
一旦有了交叉链接,提议该区块的验证者将获得奖励。
Finality
In distributed networks, a transaction has "finality" when it's part of a block that can't change.
To do this in proof-of-stake, Casper, a finality protocol, gets validators to agree on the state of a block at certain checkpoints. So long as 2/3 of the validators agree, the block is finalised. Validators will lose their entire stake if they try and revert this later on via a 51% attack.
As Vlad Zamfir put it, this is like a miner participating in a 51% attack, causing their mining hardware to immediately burn down.
在分布式网络中,当事务是不可更改的块的一部分时,它具有“最终性”。
为此,在最终证明协议中,Casper(一种确定性协议)使验证程序在某些检查点上就块的状态达成共识。只要2/3的验证者同意,就可以最终确定该区块。如果验证者稍后尝试通过51%攻击将其还原,他们将失去全部股份。
正如弗拉德·扎姆菲尔(Vlad Zamfir)所说,这就像一个矿工参与了51%的攻击,导致其采矿硬件立即烧毁。
权益证明和安全性
The threat of a 51% attack still exists in proof-of-stake, but it's even more risky for the attackers. To do so, you'd need to control 51% of the staked ETH. Not only is this a lot of money, but it would probably cause ETH's value to drop. There's very little incentive to destroy the value of a currency you have a majority stake in. There are stronger incentives to keep the network secure and healthy.
Stake slashings, ejections, and other penalties, coordinated by the beacon chain, will exist to prevent other acts of bad behavior. Validators will also be responsible for flagging these incidents.
股权证明中仍然存在51%攻击的威胁,但对攻击者而言,风险甚至更高。为此,您需要控制所抵押的ETH的51%。这不仅是很多钱,而且可能会导致ETH的价值下降。几乎没有什么动机可以破坏您拥有多数股份的货币的价值。还有更强有力的动机来保持网络的安全和健康。
由信标链协调的放样,弹出和其他惩罚将存在,以防止发生其他不良行为。验证者还将负责标记这些事件。
优缺点
Pros | Cons |
---|---|
Staking makes it easier for you to run a node. It doesn't require huge investments in hardware or energy, and if you don't have enough ETH to stake, you can join staking pools. | Proof-of-stake is still in its infancy, and less battle-tested, compared to proof-of-work |
Staking is more decentralized. It allows for increased participation, and more nodes doesn't mean increased % returns, like with mining. | |
Staking allows for secure sharding. Shard chains allow Ethereum to create multiple blocks at the same time, increasing transaction throughput. Sharding the network in a proof-of-work system would simply lower the power needed to compromise a portion of the network. |
优点 | 缺点 |
---|---|
权益使您更轻松地运行节点。它不需要在硬件或能源上进行大量投资,并且如果您没有足够的ETH来投资,您可以加入赌注池。 | 与工作量证明相比,权益证明仍处于起步阶段,并且经过较少的战斗测试 |
权益更加分散。它允许增加参与度,而更多的节点并不意味着像采矿一样增加了%的回报。 | |
权益可实现安全的分片。分片链允许以太坊同时创建多个区块,从而提高交易吞吐量。在工作量证明系统中对网络进行分片将仅降低破坏一部分网络所需的功率。 |