api_tracer.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. // Copyright 2017 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. "context"
  20. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "runtime"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/hexutil"
  28. "github.com/ethereum/go-ethereum/core"
  29. "github.com/ethereum/go-ethereum/core/rawdb"
  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/eth/tracers"
  34. "github.com/ethereum/go-ethereum/internal/ethapi"
  35. "github.com/ethereum/go-ethereum/log"
  36. "github.com/ethereum/go-ethereum/rlp"
  37. "github.com/ethereum/go-ethereum/rpc"
  38. "github.com/ethereum/go-ethereum/trie"
  39. )
  40. const (
  41. // defaultTraceTimeout is the amount of time a single transaction can execute
  42. // by default before being forcefully aborted.
  43. defaultTraceTimeout = 5 * time.Second
  44. // defaultTraceReexec is the number of blocks the tracer is willing to go back
  45. // and reexecute to produce missing historical state necessary to run a specific
  46. // trace.
  47. defaultTraceReexec = uint64(128)
  48. )
  49. // TraceConfig holds extra parameters to trace functions.
  50. type TraceConfig struct {
  51. *vm.LogConfig
  52. Tracer *string
  53. Timeout *string
  54. Reexec *uint64
  55. }
  56. // txTraceResult is the result of a single transaction trace.
  57. type txTraceResult struct {
  58. Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
  59. Error string `json:"error,omitempty"` // Trace failure produced by the tracer
  60. }
  61. // blockTraceTask represents a single block trace task when an entire chain is
  62. // being traced.
  63. type blockTraceTask struct {
  64. statedb *state.StateDB // Intermediate state prepped for tracing
  65. block *types.Block // Block to trace the transactions from
  66. rootref common.Hash // Trie root reference held for this task
  67. results []*txTraceResult // Trace results procudes by the task
  68. }
  69. // blockTraceResult represets the results of tracing a single block when an entire
  70. // chain is being traced.
  71. type blockTraceResult struct {
  72. Block hexutil.Uint64 `json:"block"` // Block number corresponding to this trace
  73. Hash common.Hash `json:"hash"` // Block hash corresponding to this trace
  74. Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
  75. }
  76. // txTraceTask represents a single transaction trace task when an entire block
  77. // is being traced.
  78. type txTraceTask struct {
  79. statedb *state.StateDB // Intermediate state prepped for tracing
  80. index int // Transaction offset in the block
  81. }
  82. // TraceChain returns the structured logs created during the execution of EVM
  83. // between two blocks (excluding start) and returns them as a JSON object.
  84. func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {
  85. // Fetch the block interval that we want to trace
  86. var from, to *types.Block
  87. switch start {
  88. case rpc.PendingBlockNumber:
  89. from = api.eth.miner.PendingBlock()
  90. case rpc.LatestBlockNumber:
  91. from = api.eth.blockchain.CurrentBlock()
  92. default:
  93. from = api.eth.blockchain.GetBlockByNumber(uint64(start))
  94. }
  95. switch end {
  96. case rpc.PendingBlockNumber:
  97. to = api.eth.miner.PendingBlock()
  98. case rpc.LatestBlockNumber:
  99. to = api.eth.blockchain.CurrentBlock()
  100. default:
  101. to = api.eth.blockchain.GetBlockByNumber(uint64(end))
  102. }
  103. // Trace the chain if we've found all our blocks
  104. if from == nil {
  105. return nil, fmt.Errorf("starting block #%d not found", start)
  106. }
  107. if to == nil {
  108. return nil, fmt.Errorf("end block #%d not found", end)
  109. }
  110. if from.Number().Cmp(to.Number()) >= 0 {
  111. return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
  112. }
  113. return api.traceChain(ctx, from, to, config)
  114. }
  115. // traceChain configures a new tracer according to the provided configuration, and
  116. // executes all the transactions contained within. The return value will be one item
  117. // per transaction, dependent on the requestd tracer.
  118. func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
  119. // Tracing a chain is a **long** operation, only do with subscriptions
  120. notifier, supported := rpc.NotifierFromContext(ctx)
  121. if !supported {
  122. return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
  123. }
  124. sub := notifier.CreateSubscription()
  125. // Ensure we have a valid starting state before doing any work
  126. origin := start.NumberU64()
  127. database := state.NewDatabase(api.eth.ChainDb())
  128. if number := start.NumberU64(); number > 0 {
  129. start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1)
  130. if start == nil {
  131. return nil, fmt.Errorf("parent block #%d not found", number-1)
  132. }
  133. }
  134. statedb, err := state.New(start.Root(), database)
  135. if err != nil {
  136. // If the starting state is missing, allow some number of blocks to be reexecuted
  137. reexec := defaultTraceReexec
  138. if config != nil && config.Reexec != nil {
  139. reexec = *config.Reexec
  140. }
  141. // Find the most recent block that has the state available
  142. for i := uint64(0); i < reexec; i++ {
  143. start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1)
  144. if start == nil {
  145. break
  146. }
  147. if statedb, err = state.New(start.Root(), database); err == nil {
  148. break
  149. }
  150. }
  151. // If we still don't have the state available, bail out
  152. if err != nil {
  153. switch err.(type) {
  154. case *trie.MissingNodeError:
  155. return nil, errors.New("required historical state unavailable")
  156. default:
  157. return nil, err
  158. }
  159. }
  160. }
  161. // Execute all the transaction contained within the chain concurrently for each block
  162. blocks := int(end.NumberU64() - origin)
  163. threads := runtime.NumCPU()
  164. if threads > blocks {
  165. threads = blocks
  166. }
  167. var (
  168. pend = new(sync.WaitGroup)
  169. tasks = make(chan *blockTraceTask, threads)
  170. results = make(chan *blockTraceTask, threads)
  171. )
  172. for th := 0; th < threads; th++ {
  173. pend.Add(1)
  174. go func() {
  175. defer pend.Done()
  176. // Fetch and execute the next block trace tasks
  177. for task := range tasks {
  178. signer := types.MakeSigner(api.config, task.block.Number())
  179. // Trace all the transactions contained within
  180. for i, tx := range task.block.Transactions() {
  181. msg, _ := tx.AsMessage(signer)
  182. vmctx := core.NewEVMContext(msg, task.block.Header(), api.eth.blockchain, nil)
  183. res, err := api.traceTx(ctx, msg, vmctx, task.statedb, config)
  184. if err != nil {
  185. task.results[i] = &txTraceResult{Error: err.Error()}
  186. log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
  187. break
  188. }
  189. task.statedb.Finalise(true)
  190. task.results[i] = &txTraceResult{Result: res}
  191. }
  192. // Stream the result back to the user or abort on teardown
  193. select {
  194. case results <- task:
  195. case <-notifier.Closed():
  196. return
  197. }
  198. }
  199. }()
  200. }
  201. // Start a goroutine to feed all the blocks into the tracers
  202. begin := time.Now()
  203. go func() {
  204. var (
  205. logged time.Time
  206. number uint64
  207. traced uint64
  208. failed error
  209. proot common.Hash
  210. )
  211. // Ensure everything is properly cleaned up on any exit path
  212. defer func() {
  213. close(tasks)
  214. pend.Wait()
  215. switch {
  216. case failed != nil:
  217. log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
  218. case number < end.NumberU64():
  219. log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
  220. default:
  221. log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
  222. }
  223. close(results)
  224. }()
  225. // Feed all the blocks both into the tracer, as well as fast process concurrently
  226. for number = start.NumberU64() + 1; number <= end.NumberU64(); number++ {
  227. // Stop tracing if interruption was requested
  228. select {
  229. case <-notifier.Closed():
  230. return
  231. default:
  232. }
  233. // Print progress logs if long enough time elapsed
  234. if time.Since(logged) > 8*time.Second {
  235. if number > origin {
  236. nodes, imgs := database.TrieDB().Size()
  237. log.Info("Tracing chain segment", "start", origin, "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin), "memory", nodes+imgs)
  238. } else {
  239. log.Info("Preparing state for chain trace", "block", number, "start", origin, "elapsed", time.Since(begin))
  240. }
  241. logged = time.Now()
  242. }
  243. // Retrieve the next block to trace
  244. block := api.eth.blockchain.GetBlockByNumber(number)
  245. if block == nil {
  246. failed = fmt.Errorf("block #%d not found", number)
  247. break
  248. }
  249. // Send the block over to the concurrent tracers (if not in the fast-forward phase)
  250. if number > origin {
  251. txs := block.Transactions()
  252. select {
  253. case tasks <- &blockTraceTask{statedb: statedb.Copy(), block: block, rootref: proot, results: make([]*txTraceResult, len(txs))}:
  254. case <-notifier.Closed():
  255. return
  256. }
  257. traced += uint64(len(txs))
  258. }
  259. // Generate the next state snapshot fast without tracing
  260. _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
  261. if err != nil {
  262. failed = err
  263. break
  264. }
  265. // Finalize the state so any modifications are written to the trie
  266. root, err := statedb.Commit(true)
  267. if err != nil {
  268. failed = err
  269. break
  270. }
  271. if err := statedb.Reset(root); err != nil {
  272. failed = err
  273. break
  274. }
  275. // Reference the trie twice, once for us, once for the tracer
  276. database.TrieDB().Reference(root, common.Hash{})
  277. if number >= origin {
  278. database.TrieDB().Reference(root, common.Hash{})
  279. }
  280. // Dereference all past tries we ourselves are done working with
  281. if proot != (common.Hash{}) {
  282. database.TrieDB().Dereference(proot)
  283. }
  284. proot = root
  285. // TODO(karalabe): Do we need the preimages? Won't they accumulate too much?
  286. }
  287. }()
  288. // Keep reading the trace results and stream the to the user
  289. go func() {
  290. var (
  291. done = make(map[uint64]*blockTraceResult)
  292. next = origin + 1
  293. )
  294. for res := range results {
  295. // Queue up next received result
  296. result := &blockTraceResult{
  297. Block: hexutil.Uint64(res.block.NumberU64()),
  298. Hash: res.block.Hash(),
  299. Traces: res.results,
  300. }
  301. done[uint64(result.Block)] = result
  302. // Dereference any paret tries held in memory by this task
  303. database.TrieDB().Dereference(res.rootref)
  304. // Stream completed traces to the user, aborting on the first error
  305. for result, ok := done[next]; ok; result, ok = done[next] {
  306. if len(result.Traces) > 0 || next == end.NumberU64() {
  307. notifier.Notify(sub.ID, result)
  308. }
  309. delete(done, next)
  310. next++
  311. }
  312. }
  313. }()
  314. return sub, nil
  315. }
  316. // TraceBlockByNumber returns the structured logs created during the execution of
  317. // EVM and returns them as a JSON object.
  318. func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  319. // Fetch the block that we want to trace
  320. var block *types.Block
  321. switch number {
  322. case rpc.PendingBlockNumber:
  323. block = api.eth.miner.PendingBlock()
  324. case rpc.LatestBlockNumber:
  325. block = api.eth.blockchain.CurrentBlock()
  326. default:
  327. block = api.eth.blockchain.GetBlockByNumber(uint64(number))
  328. }
  329. // Trace the block if it was found
  330. if block == nil {
  331. return nil, fmt.Errorf("block #%d not found", number)
  332. }
  333. return api.traceBlock(ctx, block, config)
  334. }
  335. // TraceBlockByHash returns the structured logs created during the execution of
  336. // EVM and returns them as a JSON object.
  337. func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  338. block := api.eth.blockchain.GetBlockByHash(hash)
  339. if block == nil {
  340. return nil, fmt.Errorf("block #%x not found", hash)
  341. }
  342. return api.traceBlock(ctx, block, config)
  343. }
  344. // TraceBlock returns the structured logs created during the execution of EVM
  345. // and returns them as a JSON object.
  346. func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
  347. block := new(types.Block)
  348. if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
  349. return nil, fmt.Errorf("could not decode block: %v", err)
  350. }
  351. return api.traceBlock(ctx, block, config)
  352. }
  353. // TraceBlockFromFile returns the structured logs created during the execution of
  354. // EVM and returns them as a JSON object.
  355. func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
  356. blob, err := ioutil.ReadFile(file)
  357. if err != nil {
  358. return nil, fmt.Errorf("could not read file: %v", err)
  359. }
  360. return api.TraceBlock(ctx, blob, config)
  361. }
  362. // traceBlock configures a new tracer according to the provided configuration, and
  363. // executes all the transactions contained within. The return value will be one item
  364. // per transaction, dependent on the requestd tracer.
  365. func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
  366. // Create the parent state database
  367. if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil {
  368. return nil, err
  369. }
  370. parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  371. if parent == nil {
  372. return nil, fmt.Errorf("parent %x not found", block.ParentHash())
  373. }
  374. reexec := defaultTraceReexec
  375. if config != nil && config.Reexec != nil {
  376. reexec = *config.Reexec
  377. }
  378. statedb, err := api.computeStateDB(parent, reexec)
  379. if err != nil {
  380. return nil, err
  381. }
  382. // Execute all the transaction contained within the block concurrently
  383. var (
  384. signer = types.MakeSigner(api.config, block.Number())
  385. txs = block.Transactions()
  386. results = make([]*txTraceResult, len(txs))
  387. pend = new(sync.WaitGroup)
  388. jobs = make(chan *txTraceTask, len(txs))
  389. )
  390. threads := runtime.NumCPU()
  391. if threads > len(txs) {
  392. threads = len(txs)
  393. }
  394. for th := 0; th < threads; th++ {
  395. pend.Add(1)
  396. go func() {
  397. defer pend.Done()
  398. // Fetch and execute the next transaction trace tasks
  399. for task := range jobs {
  400. msg, _ := txs[task.index].AsMessage(signer)
  401. vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
  402. res, err := api.traceTx(ctx, msg, vmctx, task.statedb, config)
  403. if err != nil {
  404. results[task.index] = &txTraceResult{Error: err.Error()}
  405. continue
  406. }
  407. results[task.index] = &txTraceResult{Result: res}
  408. }
  409. }()
  410. }
  411. // Feed the transactions into the tracers and return
  412. var failed error
  413. for i, tx := range txs {
  414. // Send the trace task over for execution
  415. jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  416. // Generate the next state snapshot fast without tracing
  417. msg, _ := tx.AsMessage(signer)
  418. vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
  419. vmenv := vm.NewEVM(vmctx, statedb, api.config, vm.Config{})
  420. if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  421. failed = err
  422. break
  423. }
  424. // Finalize the state so any modifications are written to the trie
  425. statedb.Finalise(true)
  426. }
  427. close(jobs)
  428. pend.Wait()
  429. // If execution failed in between, abort
  430. if failed != nil {
  431. return nil, failed
  432. }
  433. return results, nil
  434. }
  435. // computeStateDB retrieves the state database associated with a certain block.
  436. // If no state is locally available for the given block, a number of blocks are
  437. // attempted to be reexecuted to generate the desired state.
  438. func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, error) {
  439. // If we have the state fully available, use that
  440. statedb, err := api.eth.blockchain.StateAt(block.Root())
  441. if err == nil {
  442. return statedb, nil
  443. }
  444. // Otherwise try to reexec blocks until we find a state or reach our limit
  445. origin := block.NumberU64()
  446. database := state.NewDatabase(api.eth.ChainDb())
  447. for i := uint64(0); i < reexec; i++ {
  448. block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  449. if block == nil {
  450. break
  451. }
  452. if statedb, err = state.New(block.Root(), database); err == nil {
  453. break
  454. }
  455. }
  456. if err != nil {
  457. switch err.(type) {
  458. case *trie.MissingNodeError:
  459. return nil, errors.New("required historical state unavailable")
  460. default:
  461. return nil, err
  462. }
  463. }
  464. // State was available at historical point, regenerate
  465. var (
  466. start = time.Now()
  467. logged time.Time
  468. proot common.Hash
  469. )
  470. for block.NumberU64() < origin {
  471. // Print progress logs if long enough time elapsed
  472. if time.Since(logged) > 8*time.Second {
  473. log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "elapsed", time.Since(start))
  474. logged = time.Now()
  475. }
  476. // Retrieve the next block to regenerate and process it
  477. if block = api.eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
  478. return nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
  479. }
  480. _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
  481. if err != nil {
  482. return nil, err
  483. }
  484. // Finalize the state so any modifications are written to the trie
  485. root, err := statedb.Commit(true)
  486. if err != nil {
  487. return nil, err
  488. }
  489. if err := statedb.Reset(root); err != nil {
  490. return nil, err
  491. }
  492. database.TrieDB().Reference(root, common.Hash{})
  493. if proot != (common.Hash{}) {
  494. database.TrieDB().Dereference(proot)
  495. }
  496. proot = root
  497. }
  498. nodes, imgs := database.TrieDB().Size()
  499. log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  500. return statedb, nil
  501. }
  502. // TraceTransaction returns the structured logs created during the execution of EVM
  503. // and returns them as a JSON object.
  504. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  505. // Retrieve the transaction and assemble its EVM context
  506. tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
  507. if tx == nil {
  508. return nil, fmt.Errorf("transaction %x not found", hash)
  509. }
  510. reexec := defaultTraceReexec
  511. if config != nil && config.Reexec != nil {
  512. reexec = *config.Reexec
  513. }
  514. msg, vmctx, statedb, err := api.computeTxEnv(blockHash, int(index), reexec)
  515. if err != nil {
  516. return nil, err
  517. }
  518. // Trace the transaction and return
  519. return api.traceTx(ctx, msg, vmctx, statedb, config)
  520. }
  521. // traceTx configures a new tracer according to the provided configuration, and
  522. // executes the given message in the provided environment. The return value will
  523. // be tracer dependent.
  524. func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, vmctx vm.Context, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  525. // Assemble the structured logger or the JavaScript tracer
  526. var (
  527. tracer vm.Tracer
  528. err error
  529. )
  530. switch {
  531. case config != nil && config.Tracer != nil:
  532. // Define a meaningful timeout of a single transaction trace
  533. timeout := defaultTraceTimeout
  534. if config.Timeout != nil {
  535. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  536. return nil, err
  537. }
  538. }
  539. // Constuct the JavaScript tracer to execute with
  540. if tracer, err = tracers.New(*config.Tracer); err != nil {
  541. return nil, err
  542. }
  543. // Handle timeouts and RPC cancellations
  544. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  545. go func() {
  546. <-deadlineCtx.Done()
  547. tracer.(*tracers.Tracer).Stop(errors.New("execution timeout"))
  548. }()
  549. defer cancel()
  550. case config == nil:
  551. tracer = vm.NewStructLogger(nil)
  552. default:
  553. tracer = vm.NewStructLogger(config.LogConfig)
  554. }
  555. // Run the transaction with tracing enabled.
  556. vmenv := vm.NewEVM(vmctx, statedb, api.config, vm.Config{Debug: true, Tracer: tracer})
  557. ret, gas, failed, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  558. if err != nil {
  559. return nil, fmt.Errorf("tracing failed: %v", err)
  560. }
  561. // Depending on the tracer type, format and return the output
  562. switch tracer := tracer.(type) {
  563. case *vm.StructLogger:
  564. return &ethapi.ExecutionResult{
  565. Gas: gas,
  566. Failed: failed,
  567. ReturnValue: fmt.Sprintf("%x", ret),
  568. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  569. }, nil
  570. case *tracers.Tracer:
  571. return tracer.GetResult()
  572. default:
  573. panic(fmt.Sprintf("bad tracer type %T", tracer))
  574. }
  575. }
  576. // computeTxEnv returns the execution environment of a certain transaction.
  577. func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.Context, *state.StateDB, error) {
  578. // Create the parent state database
  579. block := api.eth.blockchain.GetBlockByHash(blockHash)
  580. if block == nil {
  581. return nil, vm.Context{}, nil, fmt.Errorf("block %x not found", blockHash)
  582. }
  583. parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  584. if parent == nil {
  585. return nil, vm.Context{}, nil, fmt.Errorf("parent %x not found", block.ParentHash())
  586. }
  587. statedb, err := api.computeStateDB(parent, reexec)
  588. if err != nil {
  589. return nil, vm.Context{}, nil, err
  590. }
  591. // Recompute transactions up to the target index.
  592. signer := types.MakeSigner(api.config, block.Number())
  593. for idx, tx := range block.Transactions() {
  594. // Assemble the transaction call message and return if the requested offset
  595. msg, _ := tx.AsMessage(signer)
  596. context := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil)
  597. if idx == txIndex {
  598. return msg, context, statedb, nil
  599. }
  600. // Not yet the searched for transaction, execute on top of the current state
  601. vmenv := vm.NewEVM(context, statedb, api.config, vm.Config{})
  602. if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  603. return nil, vm.Context{}, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err)
  604. }
  605. // Ensure any modifications are committed to the state
  606. statedb.Finalise(true)
  607. }
  608. return nil, vm.Context{}, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash)
  609. }