api.go 18 KB

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