api_tracer.go 31 KB

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