api_tracer.go 22 KB

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