api_tracer.go 22 KB

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