api.go 16 KB

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