api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config.
  62. func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 {
  63. chainID := new(big.Int)
  64. if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) {
  65. chainID = config.ChainID
  66. }
  67. return (hexutil.Uint64)(chainID.Uint64())
  68. }
  69. // PublicMinerAPI provides an API to control the miner.
  70. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  71. type PublicMinerAPI struct {
  72. e *Ethereum
  73. }
  74. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  75. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  76. return &PublicMinerAPI{e}
  77. }
  78. // Mining returns an indication if this node is currently mining.
  79. func (api *PublicMinerAPI) Mining() bool {
  80. return api.e.IsMining()
  81. }
  82. // PrivateMinerAPI provides private RPC methods to control the miner.
  83. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  84. type PrivateMinerAPI struct {
  85. e *Ethereum
  86. }
  87. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  88. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  89. return &PrivateMinerAPI{e: e}
  90. }
  91. // Start starts the miner with the given number of threads. If threads is nil,
  92. // the number of workers started is equal to the number of logical CPUs that are
  93. // usable by this process. If mining is already running, this method adjust the
  94. // number of threads allowed to use and updates the minimum price required by the
  95. // transaction pool.
  96. func (api *PrivateMinerAPI) Start(threads *int) error {
  97. if threads == nil {
  98. return api.e.StartMining(runtime.NumCPU())
  99. }
  100. return api.e.StartMining(*threads)
  101. }
  102. // Stop terminates the miner, both at the consensus engine level as well as at
  103. // the block creation level.
  104. func (api *PrivateMinerAPI) Stop() {
  105. api.e.StopMining()
  106. }
  107. // SetExtra sets the extra data string that is included when this miner mines a block.
  108. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  109. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  110. return false, err
  111. }
  112. return true, nil
  113. }
  114. // SetGasPrice sets the minimum accepted gas price for the miner.
  115. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  116. api.e.lock.Lock()
  117. api.e.gasPrice = (*big.Int)(&gasPrice)
  118. api.e.lock.Unlock()
  119. api.e.txPool.SetGasPrice((*big.Int)(&gasPrice))
  120. return true
  121. }
  122. // SetEtherbase sets the etherbase of the miner
  123. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  124. api.e.SetEtherbase(etherbase)
  125. return true
  126. }
  127. // SetRecommitInterval updates the interval for miner sealing work recommitting.
  128. func (api *PrivateMinerAPI) SetRecommitInterval(interval int) {
  129. api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond)
  130. }
  131. // GetHashrate returns the current hashrate of the miner.
  132. func (api *PrivateMinerAPI) GetHashrate() uint64 {
  133. return api.e.miner.HashRate()
  134. }
  135. // PrivateAdminAPI is the collection of Ethereum full node-related APIs
  136. // exposed over the private admin endpoint.
  137. type PrivateAdminAPI struct {
  138. eth *Ethereum
  139. }
  140. // NewPrivateAdminAPI creates a new API definition for the full node private
  141. // admin methods of the Ethereum service.
  142. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  143. return &PrivateAdminAPI{eth: eth}
  144. }
  145. // ExportChain exports the current blockchain into a local file.
  146. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  147. // Make sure we can create the file to export into
  148. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  149. if err != nil {
  150. return false, err
  151. }
  152. defer out.Close()
  153. var writer io.Writer = out
  154. if strings.HasSuffix(file, ".gz") {
  155. writer = gzip.NewWriter(writer)
  156. defer writer.(*gzip.Writer).Close()
  157. }
  158. // Export the blockchain
  159. 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(), 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(), nil
  249. }
  250. // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over
  251. // the private debugging endpoint.
  252. type PrivateDebugAPI struct {
  253. config *params.ChainConfig
  254. eth *Ethereum
  255. }
  256. // NewPrivateDebugAPI creates a new API definition for the full node-related
  257. // private debug methods of the Ethereum service.
  258. func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
  259. return &PrivateDebugAPI{config: config, eth: eth}
  260. }
  261. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  262. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  263. if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil {
  264. return preimage, nil
  265. }
  266. return nil, errors.New("unknown preimage")
  267. }
  268. // BadBlockArgs represents the entries in the list returned when bad blocks are queried.
  269. type BadBlockArgs struct {
  270. Hash common.Hash `json:"hash"`
  271. Block map[string]interface{} `json:"block"`
  272. RLP string `json:"rlp"`
  273. }
  274. // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network
  275. // and returns them as a JSON list of block-hashes
  276. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) {
  277. blocks := api.eth.BlockChain().BadBlocks()
  278. results := make([]*BadBlockArgs, len(blocks))
  279. var err error
  280. for i, block := range blocks {
  281. results[i] = &BadBlockArgs{
  282. Hash: block.Hash(),
  283. }
  284. if rlpBytes, err := rlp.EncodeToBytes(block); err != nil {
  285. results[i].RLP = err.Error() // Hacky, but hey, it works
  286. } else {
  287. results[i].RLP = fmt.Sprintf("0x%x", rlpBytes)
  288. }
  289. if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil {
  290. results[i].Block = map[string]interface{}{"error": err.Error()}
  291. }
  292. }
  293. return results, nil
  294. }
  295. // StorageRangeResult is the result of a debug_storageRangeAt API call.
  296. type StorageRangeResult struct {
  297. Storage storageMap `json:"storage"`
  298. NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie.
  299. }
  300. type storageMap map[common.Hash]storageEntry
  301. type storageEntry struct {
  302. Key *common.Hash `json:"key"`
  303. Value common.Hash `json:"value"`
  304. }
  305. // StorageRangeAt returns the storage at the given block height and transaction index.
  306. func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) {
  307. _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0)
  308. if err != nil {
  309. return StorageRangeResult{}, err
  310. }
  311. st := statedb.StorageTrie(contractAddress)
  312. if st == nil {
  313. return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress)
  314. }
  315. return storageRangeAt(st, keyStart, maxResult)
  316. }
  317. func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) {
  318. it := trie.NewIterator(st.NodeIterator(start))
  319. result := StorageRangeResult{Storage: storageMap{}}
  320. for i := 0; i < maxResult && it.Next(); i++ {
  321. _, content, _, err := rlp.Split(it.Value)
  322. if err != nil {
  323. return StorageRangeResult{}, err
  324. }
  325. e := storageEntry{Value: common.BytesToHash(content)}
  326. if preimage := st.GetKey(it.Key); preimage != nil {
  327. preimage := common.BytesToHash(preimage)
  328. e.Key = &preimage
  329. }
  330. result.Storage[common.BytesToHash(it.Key)] = e
  331. }
  332. // Add the 'next key' so clients can continue downloading.
  333. if it.Next() {
  334. next := common.BytesToHash(it.Key)
  335. result.NextKey = &next
  336. }
  337. return result, nil
  338. }
  339. // GetModifiedAccountsByNumber returns all accounts that have changed between the
  340. // two blocks specified. A change is defined as a difference in nonce, balance,
  341. // code hash, or storage hash.
  342. //
  343. // With one parameter, returns the list of accounts modified in the specified block.
  344. func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) {
  345. var startBlock, endBlock *types.Block
  346. startBlock = api.eth.blockchain.GetBlockByNumber(startNum)
  347. if startBlock == nil {
  348. return nil, fmt.Errorf("start block %x not found", startNum)
  349. }
  350. if endNum == nil {
  351. endBlock = startBlock
  352. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  353. if startBlock == nil {
  354. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  355. }
  356. } else {
  357. endBlock = api.eth.blockchain.GetBlockByNumber(*endNum)
  358. if endBlock == nil {
  359. return nil, fmt.Errorf("end block %d not found", *endNum)
  360. }
  361. }
  362. return api.getModifiedAccounts(startBlock, endBlock)
  363. }
  364. // GetModifiedAccountsByHash returns all accounts that have changed between the
  365. // two blocks specified. A change is defined as a difference in nonce, balance,
  366. // code hash, or storage hash.
  367. //
  368. // With one parameter, returns the list of accounts modified in the specified block.
  369. func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) {
  370. var startBlock, endBlock *types.Block
  371. startBlock = api.eth.blockchain.GetBlockByHash(startHash)
  372. if startBlock == nil {
  373. return nil, fmt.Errorf("start block %x not found", startHash)
  374. }
  375. if endHash == nil {
  376. endBlock = startBlock
  377. startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash())
  378. if startBlock == nil {
  379. return nil, fmt.Errorf("block %x has no parent", endBlock.Number())
  380. }
  381. } else {
  382. endBlock = api.eth.blockchain.GetBlockByHash(*endHash)
  383. if endBlock == nil {
  384. return nil, fmt.Errorf("end block %x not found", *endHash)
  385. }
  386. }
  387. return api.getModifiedAccounts(startBlock, endBlock)
  388. }
  389. func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) {
  390. if startBlock.Number().Uint64() >= endBlock.Number().Uint64() {
  391. return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64())
  392. }
  393. triedb := api.eth.BlockChain().StateCache().TrieDB()
  394. oldTrie, err := trie.NewSecure(startBlock.Root(), triedb)
  395. if err != nil {
  396. return nil, err
  397. }
  398. newTrie, err := trie.NewSecure(endBlock.Root(), triedb)
  399. if err != nil {
  400. return nil, err
  401. }
  402. diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{}))
  403. iter := trie.NewIterator(diff)
  404. var dirty []common.Address
  405. for iter.Next() {
  406. key := newTrie.GetKey(iter.Key)
  407. if key == nil {
  408. return nil, fmt.Errorf("no preimage found for hash %x", iter.Key)
  409. }
  410. dirty = append(dirty, common.BytesToAddress(key))
  411. }
  412. return dirty, nil
  413. }