api.go 16 KB

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