github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/eth/api.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:37</date>
    10  //</624450087463948289>
    11  
    12  
    13  package eth
    14  
    15  import (
    16  	"compress/gzip"
    17  	"context"
    18  	"errors"
    19  	"fmt"
    20  	"io"
    21  	"math/big"
    22  	"os"
    23  	"runtime"
    24  	"strings"
    25  	"time"
    26  
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/common/hexutil"
    29  	"github.com/ethereum/go-ethereum/core"
    30  	"github.com/ethereum/go-ethereum/core/rawdb"
    31  	"github.com/ethereum/go-ethereum/core/state"
    32  	"github.com/ethereum/go-ethereum/core/types"
    33  	"github.com/ethereum/go-ethereum/internal/ethapi"
    34  	"github.com/ethereum/go-ethereum/params"
    35  	"github.com/ethereum/go-ethereum/rlp"
    36  	"github.com/ethereum/go-ethereum/rpc"
    37  	"github.com/ethereum/go-ethereum/trie"
    38  )
    39  
    40  //PublicEthereumAPI提供了一个API,用于访问与Ethereum完整节点相关的
    41  //信息。
    42  type PublicEthereumAPI struct {
    43  	e *Ethereum
    44  }
    45  
    46  //NewPublicEthereumAPI为完整节点创建新的Ethereum协议API。
    47  func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
    48  	return &PublicEthereumAPI{e}
    49  }
    50  
    51  //EtherBase是采矿奖励将发送到的地址
    52  func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
    53  	return api.e.Etherbase()
    54  }
    55  
    56  //CoinBase是采矿奖励将发送到的地址(EtherBase的别名)
    57  func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
    58  	return api.Etherbase()
    59  }
    60  
    61  //Hashrate returns the POW hashrate
    62  func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
    63  	return hexutil.Uint64(api.e.Miner().HashRate())
    64  }
    65  
    66  //chainID是当前以太坊链配置的EIP-155重放保护链ID。
    67  func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
    68  	chainID := new(big.Int)
    69  	if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) {
    70  		chainID = config.ChainID
    71  	}
    72  	return (hexutil.Uint64)(chainID.Uint64())
    73  }
    74  
    75  //publicMinerapi提供了一个API来控制矿工。
    76  //它只提供对数据进行操作的方法,这些数据在公开访问时不会带来安全风险。
    77  type PublicMinerAPI struct {
    78  	e *Ethereum
    79  }
    80  
    81  //NewPublicMinerapi创建新的PublicMinerapi实例。
    82  func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
    83  	return &PublicMinerAPI{e}
    84  }
    85  
    86  //挖掘返回当前是否正在挖掘此节点的指示。
    87  func (api *PublicMinerAPI) Mining() bool {
    88  	return api.e.IsMining()
    89  }
    90  
    91  //privateminerapi提供私有的RPC方法来控制矿工。
    92  //这些方法可能会被外部用户滥用,并且必须被认为不受信任的用户使用是不安全的。
    93  type PrivateMinerAPI struct {
    94  	e *Ethereum
    95  }
    96  
    97  //newprivateminerapi创建一个新的RPC服务,该服务控制此节点的矿工。
    98  func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
    99  	return &PrivateMinerAPI{e: e}
   100  }
   101  
   102  //start用给定数量的线程启动miner。如果螺纹为零,
   103  //启动的工作线程数等于
   104  //可在此过程中使用。如果挖掘已在运行,则此方法将调整
   105  //允许使用和更新的线程数
   106  //事务池。
   107  func (api *PrivateMinerAPI) Start(threads *int) error {
   108  	if threads == nil {
   109  		return api.e.StartMining(runtime.NumCPU())
   110  	}
   111  	return api.e.StartMining(*threads)
   112  }
   113  
   114  //停止终止矿工,无论是在共识引擎级别还是在
   115  //the block creation level.
   116  func (api *PrivateMinerAPI) Stop() {
   117  	api.e.StopMining()
   118  }
   119  
   120  //setextra设置此矿工挖掘块时包含的额外数据字符串。
   121  func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
   122  	if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
   123  		return false, err
   124  	}
   125  	return true, nil
   126  }
   127  
   128  //setgasprice为矿工设定了最低可接受的天然气价格。
   129  func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
   130  	api.e.lock.Lock()
   131  	api.e.gasPrice = (*big.Int)(&gasPrice)
   132  	api.e.lock.Unlock()
   133  
   134  	api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
   135  	return true
   136  }
   137  
   138  //SetEtherbase sets the etherbase of the miner
   139  func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
   140  	api.e.SetEtherbase(etherbase)
   141  	return true
   142  }
   143  
   144  //setrecommittinterval更新矿工密封工作重新投入的时间间隔。
   145  func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
   146  	api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
   147  }
   148  
   149  //GetHashrate返回矿工的当前哈希率。
   150  func (api *PrivateMinerAPI) GetHashrate() uint64 {
   151  	return api.e.miner.HashRate()
   152  }
   153  
   154  //PrivateAdminAPI is the collection of Ethereum full node-related APIs
   155  //在私有管理终结点上公开。
   156  type PrivateAdminAPI struct {
   157  	eth *Ethereum
   158  }
   159  
   160  //newprivateadminapi为完整节点private创建新的api定义
   161  //EAUTHUM服务的管理方法。
   162  func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
   163  	return &PrivateAdminAPI{eth: eth}
   164  }
   165  
   166  //exportchain将当前区块链导出到本地文件中。
   167  func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
   168  //确保我们可以创建要导出到的文件
   169  	out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
   170  	if err != nil {
   171  		return false, err
   172  	}
   173  	defer out.Close()
   174  
   175  	var writer io.Writer = out
   176  	if strings.HasSuffix(file, ".gz") {
   177  		writer = gzip.NewWriter(writer)
   178  		defer writer.(*gzip.Writer).Close()
   179  	}
   180  
   181  //导出区块链
   182  	if err := api.eth.BlockChain().Export(writer); err != nil {
   183  		return false, err
   184  	}
   185  	return true, nil
   186  }
   187  
   188  func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
   189  	for _, b := range bs {
   190  		if !chain.HasBlock(b.Hash(), b.NumberU64()) {
   191  			return false
   192  		}
   193  	}
   194  
   195  	return true
   196  }
   197  
   198  //importchain从本地文件导入区块链。
   199  func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
   200  //确保可以访问要导入的文件
   201  	in, err := os.Open(file)
   202  	if err != nil {
   203  		return false, err
   204  	}
   205  	defer in.Close()
   206  
   207  	var reader io.Reader = in
   208  	if strings.HasSuffix(file, ".gz") {
   209  		if reader, err = gzip.NewReader(reader); err != nil {
   210  			return false, err
   211  		}
   212  	}
   213  
   214  //在预配置的批中实际运行导入
   215  	stream := rlp.NewStream(reader, 0)
   216  
   217  	blocks, index := make([]*types.Block, 0, 2500), 0
   218  	for batch := 0; ; batch++ {
   219  //从输入文件加载一批块
   220  		for len(blocks) < cap(blocks) {
   221  			block := new(types.Block)
   222  			if err := stream.Decode(block); err == io.EOF {
   223  				break
   224  			} else if err != nil {
   225  				return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
   226  			}
   227  			blocks = append(blocks, block)
   228  			index++
   229  		}
   230  		if len(blocks) == 0 {
   231  			break
   232  		}
   233  
   234  		if hasAllBlocks(api.eth.BlockChain(), blocks) {
   235  			blocks = blocks[:0]
   236  			continue
   237  		}
   238  //导入批并重置缓冲区
   239  		if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
   240  			return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
   241  		}
   242  		blocks = blocks[:0]
   243  	}
   244  	return true, nil
   245  }
   246  
   247  //publicDebugAPI是公开的以太坊完整节点API的集合
   248  //在公共调试终结点上。
   249  type PublicDebugAPI struct {
   250  	eth *Ethereum
   251  }
   252  
   253  //NewPublicDebugAPI creates a new API definition for the full node-
   254  //以太坊服务的相关公共调试方法。
   255  func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
   256  	return &PublicDebugAPI{eth: eth}
   257  }
   258  
   259  //dumpblock在给定的块中检索数据库的整个状态。
   260  func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
   261  	if blockNr == rpc.PendingBlockNumber {
   262  //如果我们要抛弃这个悬而未决的国家,我们需要请求
   263  //挂起块和来自的挂起状态
   264  //矿工和操作这些
   265  		_, stateDb := api.eth.miner.Pending()
   266  		return stateDb.RawDump(), nil
   267  	}
   268  	var block *types.Block
   269  	if blockNr == rpc.LatestBlockNumber {
   270  		block = api.eth.blockchain.CurrentBlock()
   271  	} else {
   272  		block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
   273  	}
   274  	if block == nil {
   275  		return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
   276  	}
   277  	stateDb, err := api.eth.BlockChain().StateAt(block.Root())
   278  	if err != nil {
   279  		return state.Dump{}, err
   280  	}
   281  	return stateDb.RawDump(), nil
   282  }
   283  
   284  //privatedebugapi是通过
   285  //专用调试终结点。
   286  type PrivateDebugAPI struct {
   287  	config *params.ChainConfig
   288  	eth    *Ethereum
   289  }
   290  
   291  //NealPrimeDebug GAPI为完整的节点创建一个新的API定义
   292  //以太坊服务的专用调试方法。
   293  func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
   294  	return &PrivateDebugAPI{config: config, eth: eth}
   295  }
   296  
   297  //PrimI图是一个调试API函数,它返回Sh3哈希的预图像,如果已知的话。
   298  func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
   299  	if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
   300  		return preimage, nil
   301  	}
   302  	return nil, errors.New("unknown preimage")
   303  }
   304  
   305  //badblockargs表示查询坏块时返回的列表中的条目。
   306  type BadBlockArgs struct {
   307  	Hash  common.Hash            `json:"hash"`
   308  	Block map[string]interface{} `json:"block"`
   309  	RLP   string                 `json:"rlp"`
   310  }
   311  
   312  //GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
   313  //并将其作为块哈希的JSON列表返回
   314  func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
   315  	blocks := api.eth.BlockChain().BadBlocks()
   316  	results := make([]*BadBlockArgs, len(blocks))
   317  
   318  	var err error
   319  	for i, block := range blocks {
   320  		results[i] = &BadBlockArgs{
   321  			Hash: block.Hash(),
   322  		}
   323  		if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
   324  results[i].RLP = err.Error() //哈奇,但是嘿,它起作用了
   325  		} else {
   326  			results[i].RLP = fmt.Sprintf("0x%x", rlpBytes)
   327  		}
   328  		if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil {
   329  			results[i].Block = map[string]interface{}{"error": err.Error()}
   330  		}
   331  	}
   332  	return results, nil
   333  }
   334  
   335  //StestAgRangeReSurt是Debug的StasgStAgReangRangeAPI调用的结果。
   336  type StorageRangeResult struct {
   337  	Storage storageMap   `json:"storage"`
   338  NextKey *common.Hash `json:"nextKey"` //如果存储包含trie中的最后一个密钥,则为nil。
   339  }
   340  
   341  type storageMap map[common.Hash]storageEntry
   342  
   343  type storageEntry struct {
   344  	Key   *common.Hash `json:"key"`
   345  	Value common.Hash  `json:"value"`
   346  }
   347  
   348  //StorageRangeAt returns the storage at the given block height and transaction index.
   349  func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
   350  	_, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
   351  	if err != nil {
   352  		return StorageRangeResult{}, err
   353  	}
   354  	st := statedb.StorageTrie(contractAddress)
   355  	if st == nil {
   356  		return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
   357  	}
   358  	return storageRangeAt(st, keyStart, maxResult)
   359  }
   360  
   361  func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
   362  	it := trie.NewIterator(st.NodeIterator(start))
   363  	result := StorageRangeResult{Storage: storageMap{}}
   364  	for i := 0; i < maxResult && it.Next(); i++ {
   365  		_, content, _, err := rlp.Split(it.Value)
   366  		if err != nil {
   367  			return StorageRangeResult{}, err
   368  		}
   369  		e := storageEntry{Value: common.BytesToHash(content)}
   370  		if preimage := st.GetKey(it.Key); preimage != nil {
   371  			preimage := common.BytesToHash(preimage)
   372  			e.Key = &preimage
   373  		}
   374  		result.Storage[common.BytesToHash(it.Key)] = e
   375  	}
   376  //添加“下一个密钥”,以便客户端可以继续下载。
   377  	if it.Next() {
   378  		next := common.BytesToHash(it.Key)
   379  		result.NextKey = &next
   380  	}
   381  	return result, nil
   382  }
   383  
   384  //GetModifiedAccountsByNumber返回在
   385  //two blocks specified. A change is defined as a difference in nonce, balance,
   386  //代码哈希或存储哈希。
   387  //
   388  //使用一个参数,返回在指定块中修改的帐户列表。
   389  func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
   390  	var startBlock, endBlock *types.Block
   391  
   392  	startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
   393  	if startBlock == nil {
   394  		return nil, fmt.Errorf("start block %x not found", startNum)
   395  	}
   396  
   397  	if endNum == nil {
   398  		endBlock = startBlock
   399  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   400  		if startBlock == nil {
   401  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   402  		}
   403  	} else {
   404  		endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
   405  		if endBlock == nil {
   406  			return nil, fmt.Errorf("end block %d not found", *endNum)
   407  		}
   408  	}
   409  	return api.getModifiedAccounts(startBlock, endBlock)
   410  }
   411  
   412  //GetModifiedAccountsByHash returns all accounts that have changed between the
   413  //指定两个块。变化被定义为非现金、余额和
   414  //代码哈希或存储哈希。
   415  //
   416  //使用一个参数,返回在指定块中修改的帐户列表。
   417  func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
   418  	var startBlock, endBlock *types.Block
   419  	startBlock = api.eth.blockchain.GetBlockByHash(startHash)
   420  	if startBlock == nil {
   421  		return nil, fmt.Errorf("start block %x not found", startHash)
   422  	}
   423  
   424  	if endHash == nil {
   425  		endBlock = startBlock
   426  		startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
   427  		if startBlock == nil {
   428  			return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
   429  		}
   430  	} else {
   431  		endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
   432  		if endBlock == nil {
   433  			return nil, fmt.Errorf("end block %x not found", *endHash)
   434  		}
   435  	}
   436  	return api.getModifiedAccounts(startBlock, endBlock)
   437  }
   438  
   439  func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
   440  	if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
   441  		return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
   442  	}
   443  	triedb := api.eth.BlockChain().StateCache().TrieDB()
   444  
   445  	oldTrie, err := trie.NewSecure(startBlock.Root(), triedb, 0)
   446  	if err != nil {
   447  		return nil, err
   448  	}
   449  	newTrie, err := trie.NewSecure(endBlock.Root(), triedb, 0)
   450  	if err != nil {
   451  		return nil, err
   452  	}
   453  	diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
   454  	iter := trie.NewIterator(diff)
   455  
   456  	var dirty []common.Address
   457  	for iter.Next() {
   458  		key := newTrie.GetKey(iter.Key)
   459  		if key == nil {
   460  			return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
   461  		}
   462  		dirty = append(dirty, common.BytesToAddress(key))
   463  	}
   464  	return dirty, nil
   465  }
   466