api.go 17 KB

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