api.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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. "bytes"
  19. "compress/gzip"
  20. "context"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "io/ioutil"
  25. "math/big"
  26. "os"
  27. "strings"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/hexutil"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/state"
  33. "github.com/ethereum/go-ethereum/core/types"
  34. "github.com/ethereum/go-ethereum/core/vm"
  35. "github.com/ethereum/go-ethereum/internal/ethapi"
  36. "github.com/ethereum/go-ethereum/log"
  37. "github.com/ethereum/go-ethereum/miner"
  38. "github.com/ethereum/go-ethereum/params"
  39. "github.com/ethereum/go-ethereum/rlp"
  40. )
  41. const defaultTraceTimeout = 5 * time.Second
  42. // PublicEthereumAPI provides an API to access Ethereum full node-related
  43. // information.
  44. type PublicEthereumAPI struct {
  45. e *Ethereum
  46. }
  47. // NewPublicEthereumAPI creates a new Etheruem protocol API for full nodes.
  48. func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI {
  49. return &PublicEthereumAPI{e}
  50. }
  51. // Etherbase is the address that mining rewards will be send to
  52. func (api *PublicEthereumAPI) Etherbase() (common.Address, error) {
  53. return api.e.Etherbase()
  54. }
  55. // Coinbase is the address that mining rewards will be send to (alias for Etherbase)
  56. func (api *PublicEthereumAPI) Coinbase() (common.Address, error) {
  57. return api.Etherbase()
  58. }
  59. // Hashrate returns the POW hashrate
  60. func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 {
  61. return hexutil.Uint64(api.e.Miner().HashRate())
  62. }
  63. // PublicMinerAPI provides an API to control the miner.
  64. // It offers only methods that operate on data that pose no security risk when it is publicly accessible.
  65. type PublicMinerAPI struct {
  66. e *Ethereum
  67. agent *miner.RemoteAgent
  68. }
  69. // NewPublicMinerAPI create a new PublicMinerAPI instance.
  70. func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI {
  71. agent := miner.NewRemoteAgent(e.BlockChain(), e.Engine())
  72. e.Miner().Register(agent)
  73. return &PublicMinerAPI{e, agent}
  74. }
  75. // Mining returns an indication if this node is currently mining.
  76. func (api *PublicMinerAPI) Mining() bool {
  77. return api.e.IsMining()
  78. }
  79. // SubmitWork can be used by external miner to submit their POW solution. It returns an indication if the work was
  80. // accepted. Note, this is not an indication if the provided work was valid!
  81. func (api *PublicMinerAPI) SubmitWork(nonce types.BlockNonce, solution, digest common.Hash) bool {
  82. return api.agent.SubmitWork(nonce, digest, solution)
  83. }
  84. // GetWork returns a work package for external miner. The work package consists of 3 strings
  85. // result[0], 32 bytes hex encoded current block header pow-hash
  86. // result[1], 32 bytes hex encoded seed hash used for DAG
  87. // result[2], 32 bytes hex encoded boundary condition ("target"), 2^256/difficulty
  88. func (api *PublicMinerAPI) GetWork() ([3]string, error) {
  89. if !api.e.IsMining() {
  90. if err := api.e.StartMining(); err != nil {
  91. return [3]string{}, err
  92. }
  93. }
  94. work, err := api.agent.GetWork()
  95. if err != nil {
  96. return work, fmt.Errorf("mining not ready: %v", err)
  97. }
  98. return work, nil
  99. }
  100. // SubmitHashrate can be used for remote miners to submit their hash rate. This enables the node to report the combined
  101. // hash rate of all miners which submit work through this node. It accepts the miner hash rate and an identifier which
  102. // must be unique between nodes.
  103. func (api *PublicMinerAPI) SubmitHashrate(hashrate hexutil.Uint64, id common.Hash) bool {
  104. api.agent.SubmitHashrate(id, uint64(hashrate))
  105. return true
  106. }
  107. // PrivateMinerAPI provides private RPC methods to control the miner.
  108. // These methods can be abused by external users and must be considered insecure for use by untrusted users.
  109. type PrivateMinerAPI struct {
  110. e *Ethereum
  111. }
  112. // NewPrivateMinerAPI create a new RPC service which controls the miner of this node.
  113. func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI {
  114. return &PrivateMinerAPI{e: e}
  115. }
  116. // Start the miner with the given number of threads. If threads is nil the number
  117. // of workers started is equal to the number of logical CPUs that are usable by
  118. // this process. If mining is already running, this method adjust the number of
  119. // threads allowed to use.
  120. func (api *PrivateMinerAPI) Start(threads *int) error {
  121. // Set the number of threads if the seal engine supports it
  122. if threads != nil {
  123. type threaded interface {
  124. SetThreads(threads int)
  125. }
  126. if th, ok := api.e.engine.(threaded); ok {
  127. log.Info("Updated mining threads", "threads", *threads)
  128. th.SetThreads(*threads)
  129. } else {
  130. log.Warn("Current seal engine isn't threaded")
  131. }
  132. }
  133. // Start the miner and return
  134. if !api.e.IsMining() {
  135. return api.e.StartMining()
  136. }
  137. return nil
  138. }
  139. // Stop the miner
  140. func (api *PrivateMinerAPI) Stop() bool {
  141. api.e.StopMining()
  142. return true
  143. }
  144. // SetExtra sets the extra data string that is included when this miner mines a block.
  145. func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) {
  146. if err := api.e.Miner().SetExtra([]byte(extra)); err != nil {
  147. return false, err
  148. }
  149. return true, nil
  150. }
  151. // SetGasPrice sets the minimum accepted gas price for the miner.
  152. func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool {
  153. api.e.Miner().SetGasPrice((*big.Int)(&gasPrice))
  154. return true
  155. }
  156. // SetEtherbase sets the etherbase of the miner
  157. func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool {
  158. api.e.SetEtherbase(etherbase)
  159. return true
  160. }
  161. // GetHashrate returns the current hashrate of the miner.
  162. func (api *PrivateMinerAPI) GetHashrate() uint64 {
  163. return uint64(api.e.miner.HashRate())
  164. }
  165. // PrivateAdminAPI is the collection of Etheruem full node-related APIs
  166. // exposed over the private admin endpoint.
  167. type PrivateAdminAPI struct {
  168. eth *Ethereum
  169. }
  170. // NewPrivateAdminAPI creates a new API definition for the full node private
  171. // admin methods of the Ethereum service.
  172. func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI {
  173. return &PrivateAdminAPI{eth: eth}
  174. }
  175. // ExportChain exports the current blockchain into a local file.
  176. func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) {
  177. // Make sure we can create the file to export into
  178. out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm)
  179. if err != nil {
  180. return false, err
  181. }
  182. defer out.Close()
  183. var writer io.Writer = out
  184. if strings.HasSuffix(file, ".gz") {
  185. writer = gzip.NewWriter(writer)
  186. defer writer.(*gzip.Writer).Close()
  187. }
  188. // Export the blockchain
  189. if err := api.eth.BlockChain().Export(writer); err != nil {
  190. return false, err
  191. }
  192. return true, nil
  193. }
  194. func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool {
  195. for _, b := range bs {
  196. if !chain.HasBlock(b.Hash()) {
  197. return false
  198. }
  199. }
  200. return true
  201. }
  202. // ImportChain imports a blockchain from a local file.
  203. func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) {
  204. // Make sure the can access the file to import
  205. in, err := os.Open(file)
  206. if err != nil {
  207. return false, err
  208. }
  209. defer in.Close()
  210. var reader io.Reader = in
  211. if strings.HasSuffix(file, ".gz") {
  212. if reader, err = gzip.NewReader(reader); err != nil {
  213. return false, err
  214. }
  215. }
  216. // Run actual the import in pre-configured batches
  217. stream := rlp.NewStream(reader, 0)
  218. blocks, index := make([]*types.Block, 0, 2500), 0
  219. for batch := 0; ; batch++ {
  220. // Load a batch of blocks from the input file
  221. for len(blocks) < cap(blocks) {
  222. block := new(types.Block)
  223. if err := stream.Decode(block); err == io.EOF {
  224. break
  225. } else if err != nil {
  226. return false, fmt.Errorf("block %d: failed to parse: %v", index, err)
  227. }
  228. blocks = append(blocks, block)
  229. index++
  230. }
  231. if len(blocks) == 0 {
  232. break
  233. }
  234. if hasAllBlocks(api.eth.BlockChain(), blocks) {
  235. blocks = blocks[:0]
  236. continue
  237. }
  238. // Import the batch and reset the buffer
  239. if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil {
  240. return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err)
  241. }
  242. blocks = blocks[:0]
  243. }
  244. return true, nil
  245. }
  246. // PublicDebugAPI is the collection of Etheruem full node APIs exposed
  247. // over the public debugging endpoint.
  248. type PublicDebugAPI struct {
  249. eth *Ethereum
  250. }
  251. // NewPublicDebugAPI creates a new API definition for the full node-
  252. // related public debug methods of the Ethereum service.
  253. func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI {
  254. return &PublicDebugAPI{eth: eth}
  255. }
  256. // DumpBlock retrieves the entire state of the database at a given block.
  257. func (api *PublicDebugAPI) DumpBlock(number uint64) (state.Dump, error) {
  258. block := api.eth.BlockChain().GetBlockByNumber(number)
  259. if block == nil {
  260. return state.Dump{}, fmt.Errorf("block #%d not found", number)
  261. }
  262. stateDb, err := api.eth.BlockChain().StateAt(block.Root())
  263. if err != nil {
  264. return state.Dump{}, err
  265. }
  266. return stateDb.RawDump(), nil
  267. }
  268. // PrivateDebugAPI is the collection of Etheruem full node APIs exposed over
  269. // the private debugging endpoint.
  270. type PrivateDebugAPI struct {
  271. config *params.ChainConfig
  272. eth *Ethereum
  273. }
  274. // NewPrivateDebugAPI creates a new API definition for the full node-related
  275. // private debug methods of the Ethereum service.
  276. func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI {
  277. return &PrivateDebugAPI{config: config, eth: eth}
  278. }
  279. // BlockTraceResult is the returned value when replaying a block to check for
  280. // consensus results and full VM trace logs for all included transactions.
  281. type BlockTraceResult struct {
  282. Validated bool `json:"validated"`
  283. StructLogs []ethapi.StructLogRes `json:"structLogs"`
  284. Error string `json:"error"`
  285. }
  286. // TraceArgs holds extra parameters to trace functions
  287. type TraceArgs struct {
  288. *vm.LogConfig
  289. Tracer *string
  290. Timeout *string
  291. }
  292. // TraceBlock processes the given block'api RLP but does not import the block in to
  293. // the chain.
  294. func (api *PrivateDebugAPI) TraceBlock(blockRlp []byte, config *vm.LogConfig) BlockTraceResult {
  295. var block types.Block
  296. err := rlp.Decode(bytes.NewReader(blockRlp), &block)
  297. if err != nil {
  298. return BlockTraceResult{Error: fmt.Sprintf("could not decode block: %v", err)}
  299. }
  300. validated, logs, err := api.traceBlock(&block, config)
  301. return BlockTraceResult{
  302. Validated: validated,
  303. StructLogs: ethapi.FormatLogs(logs),
  304. Error: formatError(err),
  305. }
  306. }
  307. // TraceBlockFromFile loads the block'api RLP from the given file name and attempts to
  308. // process it but does not import the block in to the chain.
  309. func (api *PrivateDebugAPI) TraceBlockFromFile(file string, config *vm.LogConfig) BlockTraceResult {
  310. blockRlp, err := ioutil.ReadFile(file)
  311. if err != nil {
  312. return BlockTraceResult{Error: fmt.Sprintf("could not read file: %v", err)}
  313. }
  314. return api.TraceBlock(blockRlp, config)
  315. }
  316. // TraceBlockByNumber processes the block by canonical block number.
  317. func (api *PrivateDebugAPI) TraceBlockByNumber(number uint64, config *vm.LogConfig) BlockTraceResult {
  318. // Fetch the block that we aim to reprocess
  319. block := api.eth.BlockChain().GetBlockByNumber(number)
  320. if block == nil {
  321. return BlockTraceResult{Error: fmt.Sprintf("block #%d not found", number)}
  322. }
  323. validated, logs, err := api.traceBlock(block, config)
  324. return BlockTraceResult{
  325. Validated: validated,
  326. StructLogs: ethapi.FormatLogs(logs),
  327. Error: formatError(err),
  328. }
  329. }
  330. // TraceBlockByHash processes the block by hash.
  331. func (api *PrivateDebugAPI) TraceBlockByHash(hash common.Hash, config *vm.LogConfig) BlockTraceResult {
  332. // Fetch the block that we aim to reprocess
  333. block := api.eth.BlockChain().GetBlockByHash(hash)
  334. if block == nil {
  335. return BlockTraceResult{Error: fmt.Sprintf("block #%x not found", hash)}
  336. }
  337. validated, logs, err := api.traceBlock(block, config)
  338. return BlockTraceResult{
  339. Validated: validated,
  340. StructLogs: ethapi.FormatLogs(logs),
  341. Error: formatError(err),
  342. }
  343. }
  344. // traceBlock processes the given block but does not save the state.
  345. func (api *PrivateDebugAPI) traceBlock(block *types.Block, logConfig *vm.LogConfig) (bool, []vm.StructLog, error) {
  346. // Validate and reprocess the block
  347. var (
  348. blockchain = api.eth.BlockChain()
  349. validator = blockchain.Validator()
  350. processor = blockchain.Processor()
  351. )
  352. structLogger := vm.NewStructLogger(logConfig)
  353. config := vm.Config{
  354. Debug: true,
  355. Tracer: structLogger,
  356. }
  357. if err := api.eth.engine.VerifyHeader(blockchain, block.Header(), true); err != nil {
  358. return false, structLogger.StructLogs(), err
  359. }
  360. statedb, err := blockchain.StateAt(blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1).Root())
  361. if err != nil {
  362. return false, structLogger.StructLogs(), err
  363. }
  364. receipts, _, usedGas, err := processor.Process(block, statedb, config)
  365. if err != nil {
  366. return false, structLogger.StructLogs(), err
  367. }
  368. if err := validator.ValidateState(block, blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1), statedb, receipts, usedGas); err != nil {
  369. return false, structLogger.StructLogs(), err
  370. }
  371. return true, structLogger.StructLogs(), nil
  372. }
  373. // callmsg is the message type used for call transitions.
  374. type callmsg struct {
  375. addr common.Address
  376. to *common.Address
  377. gas, gasPrice *big.Int
  378. value *big.Int
  379. data []byte
  380. }
  381. // accessor boilerplate to implement core.Message
  382. func (m callmsg) From() (common.Address, error) { return m.addr, nil }
  383. func (m callmsg) FromFrontier() (common.Address, error) { return m.addr, nil }
  384. func (m callmsg) Nonce() uint64 { return 0 }
  385. func (m callmsg) CheckNonce() bool { return false }
  386. func (m callmsg) To() *common.Address { return m.to }
  387. func (m callmsg) GasPrice() *big.Int { return m.gasPrice }
  388. func (m callmsg) Gas() *big.Int { return m.gas }
  389. func (m callmsg) Value() *big.Int { return m.value }
  390. func (m callmsg) Data() []byte { return m.data }
  391. // formatError formats a Go error into either an empty string or the data content
  392. // of the error itself.
  393. func formatError(err error) string {
  394. if err == nil {
  395. return ""
  396. }
  397. return err.Error()
  398. }
  399. type timeoutError struct{}
  400. func (t *timeoutError) Error() string {
  401. return "Execution time exceeded"
  402. }
  403. // TraceTransaction returns the structured logs created during the execution of EVM
  404. // and returns them as a JSON object.
  405. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, txHash common.Hash, config *TraceArgs) (interface{}, error) {
  406. var tracer vm.Tracer
  407. if config != nil && config.Tracer != nil {
  408. timeout := defaultTraceTimeout
  409. if config.Timeout != nil {
  410. var err error
  411. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  412. return nil, err
  413. }
  414. }
  415. var err error
  416. if tracer, err = ethapi.NewJavascriptTracer(*config.Tracer); err != nil {
  417. return nil, err
  418. }
  419. // Handle timeouts and RPC cancellations
  420. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  421. go func() {
  422. <-deadlineCtx.Done()
  423. tracer.(*ethapi.JavascriptTracer).Stop(&timeoutError{})
  424. }()
  425. defer cancel()
  426. } else if config == nil {
  427. tracer = vm.NewStructLogger(nil)
  428. } else {
  429. tracer = vm.NewStructLogger(config.LogConfig)
  430. }
  431. // Retrieve the tx from the chain and the containing block
  432. tx, blockHash, _, txIndex := core.GetTransaction(api.eth.ChainDb(), txHash)
  433. if tx == nil {
  434. return nil, fmt.Errorf("transaction %x not found", txHash)
  435. }
  436. block := api.eth.BlockChain().GetBlockByHash(blockHash)
  437. if block == nil {
  438. return nil, fmt.Errorf("block %x not found", blockHash)
  439. }
  440. // Create the state database to mutate and eventually trace
  441. parent := api.eth.BlockChain().GetBlock(block.ParentHash(), block.NumberU64()-1)
  442. if parent == nil {
  443. return nil, fmt.Errorf("block parent %x not found", block.ParentHash())
  444. }
  445. stateDb, err := api.eth.BlockChain().StateAt(parent.Root())
  446. if err != nil {
  447. return nil, err
  448. }
  449. signer := types.MakeSigner(api.config, block.Number())
  450. // Mutate the state and trace the selected transaction
  451. for idx, tx := range block.Transactions() {
  452. // Assemble the transaction call message
  453. msg, err := tx.AsMessage(signer)
  454. if err != nil {
  455. return nil, fmt.Errorf("sender retrieval failed: %v", err)
  456. }
  457. context := core.NewEVMContext(msg, block.Header(), api.eth.BlockChain())
  458. // Mutate the state if we haven't reached the tracing transaction yet
  459. if uint64(idx) < txIndex {
  460. vmenv := vm.NewEVM(context, stateDb, api.config, vm.Config{})
  461. _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
  462. if err != nil {
  463. return nil, fmt.Errorf("mutation failed: %v", err)
  464. }
  465. stateDb.DeleteSuicides()
  466. continue
  467. }
  468. vmenv := vm.NewEVM(context, stateDb, api.config, vm.Config{Debug: true, Tracer: tracer})
  469. ret, gas, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas()))
  470. if err != nil {
  471. return nil, fmt.Errorf("tracing failed: %v", err)
  472. }
  473. switch tracer := tracer.(type) {
  474. case *vm.StructLogger:
  475. return &ethapi.ExecutionResult{
  476. Gas: gas,
  477. ReturnValue: fmt.Sprintf("%x", ret),
  478. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  479. }, nil
  480. case *ethapi.JavascriptTracer:
  481. return tracer.GetResult()
  482. }
  483. }
  484. return nil, errors.New("database inconsistency")
  485. }
  486. // Preimage is a debug API function that returns the preimage for a sha3 hash, if known.
  487. func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) {
  488. db := core.PreimageTable(api.eth.ChainDb())
  489. return db.Get(hash.Bytes())
  490. }
  491. // GetBadBLocks returns a list of the last 'bad blocks' that the client has seen on the network
  492. // and returns them as a JSON list of block-hashes
  493. func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]core.BadBlockArgs, error) {
  494. return api.eth.BlockChain().BadBlocks()
  495. }