api.go 18 KB

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