api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package eth
  17. import (
  18. "compress/gzip"
  19. "context"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "math/big"
  24. "os"
  25. "runtime"
  26. "strings"
  27. "time"
  28. "github.com/ethereum/go-ethereum/common"
  29. "github.com/ethereum/go-ethereum/common/hexutil"
  30. "github.com/ethereum/go-ethereum/core"
  31. "github.com/ethereum/go-ethereum/core/rawdb"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. "github.com/ethereum/go-ethereum/rpc"
  37. "github.com/ethereum/go-ethereum/trie"
  38. )
  39. // PublicEthereumAPI provides an API to access Ethereum full node-related
  40. // information.
  41. type PublicEthereumAPI struct {
  42. e *Ethereum
  43. }
  44. // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes.
  45. func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
  46. return &PublicEthereumAPI{e}
  47. }
  48. // Etherbase is the address that mining rewards will be send to
  49. func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
  50. return api.e.Etherbase()
  51. }
  52. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  53. func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
  54. return api.Etherbase()
  55. }
  56. // Hashrate returns the POW hashrate
  57. func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
  58. return hexutil.Uint64(api.e.Miner().HashRate())
  59. }
  60. // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
  61. func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
  62. chainID := new(big.Int)
  63. if config := api.e.blockchain.Config(); config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) {
  64. chainID = config.ChainID
  65. }
  66. return (hexutil.Uint64)(chainID.Uint64())
  67. }
  68. // PublicMinerAPI provides an API to control the miner.
  69. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  70. type PublicMinerAPI struct {
  71. e *Ethereum
  72. }
  73. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  74. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  75. return &PublicMinerAPI{e}
  76. }
  77. // Mining returns an indication if this node is currently mining.
  78. func (api *PublicMinerAPI) Mining() bool {
  79. return api.e.IsMining()
  80. }
  81. // PrivateMinerAPI provides private RPC methods to control the miner.
  82. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  83. type PrivateMinerAPI struct {
  84. e *Ethereum
  85. }
  86. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  87. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  88. return &PrivateMinerAPI{e: e}
  89. }
  90. // Start starts the miner with the given number of threads. If threads is nil,
  91. // the number of workers started is equal to the number of logical CPUs that are
  92. // usable by this process. If mining is already running, this method adjust the
  93. // number of threads allowed to use and updates the minimum price required by the
  94. // transaction pool.
  95. func (api *PrivateMinerAPI) Start(threads *int) error {
  96. if threads == nil {
  97. return api.e.StartMining(runtime.NumCPU())
  98. }
  99. return api.e.StartMining(*threads)
  100. }
  101. // Stop terminates the miner, both at the consensus engine level as well as at
  102. // the block creation level.
  103. func (api *PrivateMinerAPI) Stop() {
  104. api.e.StopMining()
  105. }
  106. // SetExtra sets the extra data string that is included when this miner mines a block.
  107. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  108. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  109. return false, err
  110. }
  111. return true, nil
  112. }
  113. // SetGasPrice sets the minimum accepted gas price for the miner.
  114. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  115. api.e.lock.Lock()
  116. api.e.gasPrice = (*big.Int)(&gasPrice)
  117. api.e.lock.Unlock()
  118. api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
  119. return true
  120. }
  121. // SetEtherbase sets the etherbase of the miner
  122. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  123. api.e.SetEtherbase(etherbase)
  124. return true
  125. }
  126. // SetRecommitInterval updates the interval for miner sealing work recommitting.
  127. func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
  128. api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
  129. }
  130. // GetHashrate returns the current hashrate of the miner.
  131. func (api *PrivateMinerAPI) GetHashrate() uint64 {
  132. return api.e.miner.HashRate()
  133. }
  134. // PrivateAdminAPI is the collection of Ethereum full node-related APIs
  135. // exposed over the private admin endpoint.
  136. type PrivateAdminAPI struct {
  137. eth *Ethereum
  138. }
  139. // NewPrivateAdminAPI creates a new API definition for the full node private
  140. // admin methods of the Ethereum service.
  141. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  142. return &PrivateAdminAPI{eth: eth}
  143. }
  144. // ExportChain exports the current blockchain into a local file.
  145. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  146. // Make sure we can create the file to export into
  147. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  148. if err != nil {
  149. return false, err
  150. }
  151. defer out.Close()
  152. var writer io.Writer = out
  153. if strings.HasSuffix(file, ".gz") {
  154. writer = gzip.NewWriter(writer)
  155. defer writer.(*gzip.Writer).Close()
  156. }
  157. // Export the blockchain
  158. if err := api.eth.BlockChain().Export(writer); err != nil {
  159. return false, err
  160. }
  161. return true, nil
  162. }
  163. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  164. for _, b := range bs {
  165. if !chain.HasBlock(b.Hash(), b.NumberU64()) {
  166. return false
  167. }
  168. }
  169. return true
  170. }
  171. // ImportChain imports a blockchain from a local file.
  172. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  173. // Make sure the can access the file to import
  174. in, err := os.Open(file)
  175. if err != nil {
  176. return false, err
  177. }
  178. defer in.Close()
  179. var reader io.Reader = in
  180. if strings.HasSuffix(file, ".gz") {
  181. if reader, err = gzip.NewReader(reader); err != nil {
  182. return false, err
  183. }
  184. }
  185. // Run actual the import in pre-configured batches
  186. stream := rlp.NewStream(reader, 0)
  187. blocks, index := make([]*types.Block, 0, 2500), 0
  188. for batch := 0; ; batch++ {
  189. // Load a batch of blocks from the input file
  190. for len(blocks) < cap(blocks) {
  191. block := new(types.Block)
  192. if err := stream.Decode(block); err == io.EOF {
  193. break
  194. } else if err != nil {
  195. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  196. }
  197. blocks = append(blocks, block)
  198. index++
  199. }
  200. if len(blocks) == 0 {
  201. break
  202. }
  203. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  204. blocks = blocks[:0]
  205. continue
  206. }
  207. // Import the batch and reset the buffer
  208. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  209. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  210. }
  211. blocks = blocks[:0]
  212. }
  213. return true, nil
  214. }
  215. // PublicDebugAPI is the collection of Ethereum full node APIs exposed
  216. // over the public debugging endpoint.
  217. type PublicDebugAPI struct {
  218. eth *Ethereum
  219. }
  220. // NewPublicDebugAPI creates a new API definition for the full node-
  221. // related public debug methods of the Ethereum service.
  222. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  223. return &PublicDebugAPI{eth: eth}
  224. }
  225. // DumpBlock retrieves the entire state of the database at a given block.
  226. func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) {
  227. if blockNr == rpc.PendingBlockNumber {
  228. // If we're dumping the pending state, we need to request
  229. // both the pending block as well as the pending state from
  230. // the miner and operate on those
  231. _, stateDb := api.eth.miner.Pending()
  232. return stateDb.RawDump(false, false, true), nil
  233. }
  234. var block *types.Block
  235. if blockNr == rpc.LatestBlockNumber {
  236. block = api.eth.blockchain.CurrentBlock()
  237. } else {
  238. block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr))
  239. }
  240. if block == nil {
  241. return state.Dump{}, fmt.Errorf("block #%d not found", blockNr)
  242. }
  243. stateDb, err := api.eth.BlockChain().StateAt(block.Root())
  244. if err != nil {
  245. return state.Dump{}, err
  246. }
  247. return stateDb.RawDump(false, false, true), nil
  248. }
  249. // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
  250. // the private debugging endpoint.
  251. type PrivateDebugAPI struct {
  252. eth *Ethereum
  253. }
  254. // NewPrivateDebugAPI creates a new API definition for the full node-related
  255. // private debug methods of the Ethereum service.
  256. func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI {
  257. return &PrivateDebugAPI{eth: eth}
  258. }
  259. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  260. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  261. if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
  262. return preimage, nil
  263. }
  264. return nil, errors.New("unknown preimage")
  265. }
  266. // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  267. type BadBlockArgs struct {
  268. Hash common.Hash `json:"hash"`
  269. Block map[string]interface{} `json:"block"`
  270. RLP string `json:"rlp"`
  271. }
  272. // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  273. // and returns them as a JSON list of block-hashes
  274. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
  275. blocks := api.eth.BlockChain().BadBlocks()
  276. results := make([]*BadBlockArgs, len(blocks))
  277. var err error
  278. for i, block := range blocks {
  279. results[i] = &BadBlockArgs{
  280. Hash: block.Hash(),
  281. }
  282. if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
  283. results[i].RLP = err.Error() // Hacky, but hey, it works
  284. } else {
  285. results[i].RLP = fmt.Sprintf("0x%x", rlpBytes)
  286. }
  287. if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil {
  288. results[i].Block = map[string]interface{}{"error": err.Error()}
  289. }
  290. }
  291. return results, nil
  292. }
  293. // AccountRangeResult returns a mapping from the hash of an account addresses
  294. // to its preimage. It will return the JSON null if no preimage is found.
  295. // Since a query can return a limited amount of results, a "next" field is
  296. // also present for paging.
  297. type AccountRangeResult struct {
  298. Accounts map[common.Hash]*common.Address `json:"accounts"`
  299. Next common.Hash `json:"next"`
  300. }
  301. func accountRange(st state.Trie, start *common.Hash, maxResults int) (AccountRangeResult, error) {
  302. if start == nil {
  303. start = &common.Hash{0}
  304. }
  305. it := trie.NewIterator(st.NodeIterator(start.Bytes()))
  306. result := AccountRangeResult{Accounts: make(map[common.Hash]*common.Address), Next: common.Hash{}}
  307. if maxResults > AccountRangeMaxResults {
  308. maxResults = AccountRangeMaxResults
  309. }
  310. for i := 0; i < maxResults && it.Next(); i++ {
  311. if preimage := st.GetKey(it.Key); preimage != nil {
  312. addr := &common.Address{}
  313. addr.SetBytes(preimage)
  314. result.Accounts[common.BytesToHash(it.Key)] = addr
  315. } else {
  316. result.Accounts[common.BytesToHash(it.Key)] = nil
  317. }
  318. }
  319. if it.Next() {
  320. result.Next = common.BytesToHash(it.Key)
  321. }
  322. return result, nil
  323. }
  324. // AccountRangeMaxResults is the maximum number of results to be returned per call
  325. const AccountRangeMaxResults = 256
  326. // AccountRange enumerates all accounts in the latest state
  327. func (api *PrivateDebugAPI) AccountRange(ctx context.Context, start *common.Hash, maxResults int) (AccountRangeResult, error) {
  328. var statedb *state.StateDB
  329. var err error
  330. block := api.eth.blockchain.CurrentBlock()
  331. if len(block.Transactions()) == 0 {
  332. statedb, err = api.computeStateDB(block, defaultTraceReexec)
  333. if err != nil {
  334. return AccountRangeResult{}, err
  335. }
  336. } else {
  337. _, _, statedb, err = api.computeTxEnv(block.Hash(), len(block.Transactions())-1, 0)
  338. if err != nil {
  339. return AccountRangeResult{}, err
  340. }
  341. }
  342. trie, err := statedb.Database().OpenTrie(block.Header().Root)
  343. if err != nil {
  344. return AccountRangeResult{}, err
  345. }
  346. return accountRange(trie, start, maxResults)
  347. }
  348. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  349. type StorageRangeResult struct {
  350. Storage storageMap `json:"storage"`
  351. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  352. }
  353. type storageMap map[common.Hash]storageEntry
  354. type storageEntry struct {
  355. Key *common.Hash `json:"key"`
  356. Value common.Hash `json:"value"`
  357. }
  358. // StorageRangeAt returns the storage at the given block height and transaction index.
  359. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  360. _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
  361. if err != nil {
  362. return StorageRangeResult{}, err
  363. }
  364. st := statedb.StorageTrie(contractAddress)
  365. if st == nil {
  366. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  367. }
  368. return storageRangeAt(st, keyStart, maxResult)
  369. }
  370. func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
  371. it := trie.NewIterator(st.NodeIterator(start))
  372. result := StorageRangeResult{Storage: storageMap{}}
  373. for i := 0; i < maxResult && it.Next(); i++ {
  374. _, content, _, err := rlp.Split(it.Value)
  375. if err != nil {
  376. return StorageRangeResult{}, err
  377. }
  378. e := storageEntry{Value: common.BytesToHash(content)}
  379. if preimage := st.GetKey(it.Key); preimage != nil {
  380. preimage := common.BytesToHash(preimage)
  381. e.Key = &preimage
  382. }
  383. result.Storage[common.BytesToHash(it.Key)] = e
  384. }
  385. // Add the 'next key' so clients can continue downloading.
  386. if it.Next() {
  387. next := common.BytesToHash(it.Key)
  388. result.NextKey = &next
  389. }
  390. return result, nil
  391. }
  392. // GetModifiedAccountsByNumber returns all accounts that have changed between the
  393. // two blocks specified. A change is defined as a difference in nonce, balance,
  394. // code hash, or storage hash.
  395. //
  396. // With one parameter, returns the list of accounts modified in the specified block.
  397. func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
  398. var startBlock, endBlock *types.Block
  399. startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
  400. if startBlock == nil {
  401. return nil, fmt.Errorf("start block %x not found", startNum)
  402. }
  403. if endNum == nil {
  404. endBlock = startBlock
  405. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  406. if startBlock == nil {
  407. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  408. }
  409. } else {
  410. endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
  411. if endBlock == nil {
  412. return nil, fmt.Errorf("end block %d not found", *endNum)
  413. }
  414. }
  415. return api.getModifiedAccounts(startBlock, endBlock)
  416. }
  417. // GetModifiedAccountsByHash returns all accounts that have changed between the
  418. // two blocks specified. A change is defined as a difference in nonce, balance,
  419. // code hash, or storage hash.
  420. //
  421. // With one parameter, returns the list of accounts modified in the specified block.
  422. func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
  423. var startBlock, endBlock *types.Block
  424. startBlock = api.eth.blockchain.GetBlockByHash(startHash)
  425. if startBlock == nil {
  426. return nil, fmt.Errorf("start block %x not found", startHash)
  427. }
  428. if endHash == nil {
  429. endBlock = startBlock
  430. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  431. if startBlock == nil {
  432. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  433. }
  434. } else {
  435. endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
  436. if endBlock == nil {
  437. return nil, fmt.Errorf("end block %x not found", *endHash)
  438. }
  439. }
  440. return api.getModifiedAccounts(startBlock, endBlock)
  441. }
  442. func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
  443. if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
  444. return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
  445. }
  446. triedb := api.eth.BlockChain().StateCache().TrieDB()
  447. oldTrie, err := trie.NewSecure(startBlock.Root(), triedb)
  448. if err != nil {
  449. return nil, err
  450. }
  451. newTrie, err := trie.NewSecure(endBlock.Root(), triedb)
  452. if err != nil {
  453. return nil, err
  454. }
  455. diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
  456. iter := trie.NewIterator(diff)
  457. var dirty []common.Address
  458. for iter.Next() {
  459. key := newTrie.GetKey(iter.Key)
  460. if key == nil {
  461. return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
  462. }
  463. dirty = append(dirty, common.BytesToAddress(key))
  464. }
  465. return dirty, nil
  466. }