api.go 15 KB

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