api.go 17 KB

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