api.go 18 KB

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