api_tracer.go 28 KB

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