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