api.go 16 KB

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