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