api.go 15 KB

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