api.go 18 KB

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