api_tracer.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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.NewDatabaseWithConfig(api.eth.ChainDb(), &trie.Config{Cache: 16, Preimages: true})
  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. statedb, err = state.New(root, database, nil)
  282. if err != nil {
  283. failed = err
  284. break
  285. }
  286. // Reference the trie twice, once for us, once for the tracer
  287. database.TrieDB().Reference(root, common.Hash{})
  288. if number >= origin {
  289. database.TrieDB().Reference(root, common.Hash{})
  290. }
  291. // Dereference all past tries we ourselves are done working with
  292. if proot != (common.Hash{}) {
  293. database.TrieDB().Dereference(proot)
  294. }
  295. proot = root
  296. // TODO(karalabe): Do we need the preimages? Won't they accumulate too much?
  297. }
  298. }()
  299. // Keep reading the trace results and stream the to the user
  300. go func() {
  301. var (
  302. done = make(map[uint64]*blockTraceResult)
  303. next = origin + 1
  304. )
  305. for res := range results {
  306. // Queue up next received result
  307. result := &blockTraceResult{
  308. Block: hexutil.Uint64(res.block.NumberU64()),
  309. Hash: res.block.Hash(),
  310. Traces: res.results,
  311. }
  312. done[uint64(result.Block)] = result
  313. // Dereference any paret tries held in memory by this task
  314. database.TrieDB().Dereference(res.rootref)
  315. // Stream completed traces to the user, aborting on the first error
  316. for result, ok := done[next]; ok; result, ok = done[next] {
  317. if len(result.Traces) > 0 || next == end.NumberU64() {
  318. notifier.Notify(sub.ID, result)
  319. }
  320. delete(done, next)
  321. next++
  322. }
  323. }
  324. }()
  325. return sub, nil
  326. }
  327. // TraceBlockByNumber returns the structured logs created during the execution of
  328. // EVM and returns them as a JSON object.
  329. func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  330. // Fetch the block that we want to trace
  331. var block *types.Block
  332. switch number {
  333. case rpc.PendingBlockNumber:
  334. block = api.eth.miner.PendingBlock()
  335. case rpc.LatestBlockNumber:
  336. block = api.eth.blockchain.CurrentBlock()
  337. default:
  338. block = api.eth.blockchain.GetBlockByNumber(uint64(number))
  339. }
  340. // Trace the block if it was found
  341. if block == nil {
  342. return nil, fmt.Errorf("block #%d not found", number)
  343. }
  344. return api.traceBlock(ctx, block, config)
  345. }
  346. // TraceBlockByHash returns the structured logs created during the execution of
  347. // EVM and returns them as a JSON object.
  348. func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  349. block := api.eth.blockchain.GetBlockByHash(hash)
  350. if block == nil {
  351. return nil, fmt.Errorf("block %#x not found", hash)
  352. }
  353. return api.traceBlock(ctx, block, config)
  354. }
  355. // TraceBlock returns the structured logs created during the execution of EVM
  356. // and returns them as a JSON object.
  357. func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
  358. block := new(types.Block)
  359. if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
  360. return nil, fmt.Errorf("could not decode block: %v", err)
  361. }
  362. return api.traceBlock(ctx, block, config)
  363. }
  364. // TraceBlockFromFile returns the structured logs created during the execution of
  365. // EVM and returns them as a JSON object.
  366. func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
  367. blob, err := ioutil.ReadFile(file)
  368. if err != nil {
  369. return nil, fmt.Errorf("could not read file: %v", err)
  370. }
  371. return api.TraceBlock(ctx, blob, config)
  372. }
  373. // TraceBadBlock returns the structured logs created during the execution of
  374. // EVM against a block pulled from the pool of bad ones and returns them as a JSON
  375. // object.
  376. func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  377. for _, block := range rawdb.ReadAllBadBlocks(api.eth.chainDb) {
  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. for _, block := range rawdb.ReadAllBadBlocks(api.eth.chainDb) {
  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. blockCtx := core.NewEVMBlockContext(block.Header(), api.eth.blockchain, nil)
  438. for th := 0; th < threads; th++ {
  439. pend.Add(1)
  440. go func() {
  441. defer pend.Done()
  442. // Fetch and execute the next transaction trace tasks
  443. for task := range jobs {
  444. msg, _ := txs[task.index].AsMessage(signer)
  445. res, err := api.traceTx(ctx, msg, blockCtx, 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. txContext := core.NewEVMTxContext(msg)
  462. vmenv := vm.NewEVM(blockCtx, txContext, 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. logConfig = config.LogConfig
  512. txHash = config.TxHash
  513. }
  514. logConfig.Debug = true
  515. // Execute transaction, either tracing all or just the requested one
  516. var (
  517. signer = types.MakeSigner(api.eth.blockchain.Config(), block.Number())
  518. dumps []string
  519. chainConfig = api.eth.blockchain.Config()
  520. vmctx = core.NewEVMBlockContext(block.Header(), api.eth.blockchain, nil)
  521. canon = true
  522. )
  523. // Check if there are any overrides: the caller may wish to enable a future
  524. // fork when executing this block. Note, such overrides are only applicable to the
  525. // actual specified block, not any preceding blocks that we have to go through
  526. // in order to obtain the state.
  527. // Therefore, it's perfectly valid to specify `"futureForkBlock": 0`, to enable `futureFork`
  528. if config != nil && config.Overrides != nil {
  529. // Copy the config, to not screw up the main config
  530. // Note: the Clique-part is _not_ deep copied
  531. chainConfigCopy := new(params.ChainConfig)
  532. *chainConfigCopy = *chainConfig
  533. chainConfig = chainConfigCopy
  534. if yolov2 := config.LogConfig.Overrides.YoloV2Block; yolov2 != nil {
  535. chainConfig.YoloV2Block = yolov2
  536. canon = false
  537. }
  538. }
  539. for i, tx := range block.Transactions() {
  540. // Prepare the trasaction for un-traced execution
  541. var (
  542. msg, _ = tx.AsMessage(signer)
  543. txContext = core.NewEVMTxContext(msg)
  544. vmConf vm.Config
  545. dump *os.File
  546. writer *bufio.Writer
  547. err error
  548. )
  549. // If the transaction needs tracing, swap out the configs
  550. if tx.Hash() == txHash || txHash == (common.Hash{}) {
  551. // Generate a unique temporary file to dump it into
  552. prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
  553. if !canon {
  554. prefix = fmt.Sprintf("%valt-", prefix)
  555. }
  556. dump, err = ioutil.TempFile(os.TempDir(), prefix)
  557. if err != nil {
  558. return nil, err
  559. }
  560. dumps = append(dumps, dump.Name())
  561. // Swap out the noop logger to the standard tracer
  562. writer = bufio.NewWriter(dump)
  563. vmConf = vm.Config{
  564. Debug: true,
  565. Tracer: vm.NewJSONLogger(&logConfig, writer),
  566. EnablePreimageRecording: true,
  567. }
  568. }
  569. // Execute the transaction and flush any traces to disk
  570. vmenv := vm.NewEVM(vmctx, txContext, statedb, chainConfig, vmConf)
  571. _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  572. if writer != nil {
  573. writer.Flush()
  574. }
  575. if dump != nil {
  576. dump.Close()
  577. log.Info("Wrote standard trace", "file", dump.Name())
  578. }
  579. if err != nil {
  580. return dumps, err
  581. }
  582. // Finalize the state so any modifications are written to the trie
  583. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  584. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  585. // If we've traced the transaction we were looking for, abort
  586. if tx.Hash() == txHash {
  587. break
  588. }
  589. }
  590. return dumps, nil
  591. }
  592. // containsTx reports whether the transaction with a certain hash
  593. // is contained within the specified block.
  594. func containsTx(block *types.Block, hash common.Hash) bool {
  595. for _, tx := range block.Transactions() {
  596. if tx.Hash() == hash {
  597. return true
  598. }
  599. }
  600. return false
  601. }
  602. // computeStateDB retrieves the state database associated with a certain block.
  603. // If no state is locally available for the given block, a number of blocks are
  604. // attempted to be reexecuted to generate the desired state.
  605. func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, error) {
  606. // If we have the state fully available, use that
  607. statedb, err := api.eth.blockchain.StateAt(block.Root())
  608. if err == nil {
  609. return statedb, nil
  610. }
  611. // Otherwise try to reexec blocks until we find a state or reach our limit
  612. origin := block.NumberU64()
  613. database := state.NewDatabaseWithConfig(api.eth.ChainDb(), &trie.Config{Cache: 16, Preimages: true})
  614. for i := uint64(0); i < reexec; i++ {
  615. block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  616. if block == nil {
  617. break
  618. }
  619. if statedb, err = state.New(block.Root(), database, nil); err == nil {
  620. break
  621. }
  622. }
  623. if err != nil {
  624. switch err.(type) {
  625. case *trie.MissingNodeError:
  626. return nil, fmt.Errorf("required historical state unavailable (reexec=%d)", reexec)
  627. default:
  628. return nil, err
  629. }
  630. }
  631. // State was available at historical point, regenerate
  632. var (
  633. start = time.Now()
  634. logged time.Time
  635. proot common.Hash
  636. )
  637. for block.NumberU64() < origin {
  638. // Print progress logs if long enough time elapsed
  639. if time.Since(logged) > 8*time.Second {
  640. log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "remaining", origin-block.NumberU64()-1, "elapsed", time.Since(start))
  641. logged = time.Now()
  642. }
  643. // Retrieve the next block to regenerate and process it
  644. if block = api.eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil {
  645. return nil, fmt.Errorf("block #%d not found", block.NumberU64()+1)
  646. }
  647. _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, vm.Config{})
  648. if err != nil {
  649. return nil, fmt.Errorf("processing block %d failed: %v", block.NumberU64(), err)
  650. }
  651. // Finalize the state so any modifications are written to the trie
  652. root, err := statedb.Commit(api.eth.blockchain.Config().IsEIP158(block.Number()))
  653. if err != nil {
  654. return nil, err
  655. }
  656. statedb, err = state.New(root, database, nil)
  657. if err != nil {
  658. return nil, fmt.Errorf("state reset after block %d failed: %v", block.NumberU64(), err)
  659. }
  660. database.TrieDB().Reference(root, common.Hash{})
  661. if proot != (common.Hash{}) {
  662. database.TrieDB().Dereference(proot)
  663. }
  664. proot = root
  665. }
  666. nodes, imgs := database.TrieDB().Size()
  667. log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs)
  668. return statedb, nil
  669. }
  670. // TraceTransaction returns the structured logs created during the execution of EVM
  671. // and returns them as a JSON object.
  672. func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  673. // Retrieve the transaction and assemble its EVM context
  674. tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash)
  675. if tx == nil {
  676. return nil, fmt.Errorf("transaction %#x not found", hash)
  677. }
  678. reexec := defaultTraceReexec
  679. if config != nil && config.Reexec != nil {
  680. reexec = *config.Reexec
  681. }
  682. // Retrieve the block
  683. block := api.eth.blockchain.GetBlockByHash(blockHash)
  684. if block == nil {
  685. return nil, fmt.Errorf("block %#x not found", blockHash)
  686. }
  687. msg, vmctx, statedb, err := api.computeTxEnv(block, int(index), reexec)
  688. if err != nil {
  689. return nil, err
  690. }
  691. // Trace the transaction and return
  692. return api.traceTx(ctx, msg, vmctx, statedb, config)
  693. }
  694. // TraceCall lets you trace a given eth_call. It collects the structured logs created during the execution of EVM
  695. // if the given transaction was added on top of the provided block and returns them as a JSON object.
  696. // You can provide -2 as a block number to trace on top of the pending block.
  697. func (api *PrivateDebugAPI) TraceCall(ctx context.Context, args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceConfig) (interface{}, error) {
  698. // First try to retrieve the state
  699. statedb, header, err := api.eth.APIBackend.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash)
  700. if err != nil {
  701. // Try to retrieve the specified block
  702. var block *types.Block
  703. if hash, ok := blockNrOrHash.Hash(); ok {
  704. block = api.eth.blockchain.GetBlockByHash(hash)
  705. } else if number, ok := blockNrOrHash.Number(); ok {
  706. block = api.eth.blockchain.GetBlockByNumber(uint64(number))
  707. }
  708. if block == nil {
  709. return nil, fmt.Errorf("block %v not found: %v", blockNrOrHash, err)
  710. }
  711. // try to recompute the state
  712. reexec := defaultTraceReexec
  713. if config != nil && config.Reexec != nil {
  714. reexec = *config.Reexec
  715. }
  716. _, _, statedb, err = api.computeTxEnv(block, 0, reexec)
  717. if err != nil {
  718. return nil, err
  719. }
  720. }
  721. // Execute the trace
  722. msg := args.ToMessage(api.eth.APIBackend.RPCGasCap())
  723. vmctx := core.NewEVMBlockContext(header, api.eth.blockchain, nil)
  724. return api.traceTx(ctx, msg, vmctx, statedb, config)
  725. }
  726. // traceTx configures a new tracer according to the provided configuration, and
  727. // executes the given message in the provided environment. The return value will
  728. // be tracer dependent.
  729. func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  730. // Assemble the structured logger or the JavaScript tracer
  731. var (
  732. tracer vm.Tracer
  733. err error
  734. txContext = core.NewEVMTxContext(message)
  735. )
  736. switch {
  737. case config != nil && config.Tracer != nil:
  738. // Define a meaningful timeout of a single transaction trace
  739. timeout := defaultTraceTimeout
  740. if config.Timeout != nil {
  741. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  742. return nil, err
  743. }
  744. }
  745. // Constuct the JavaScript tracer to execute with
  746. if tracer, err = tracers.New(*config.Tracer, txContext); err != nil {
  747. return nil, err
  748. }
  749. // Handle timeouts and RPC cancellations
  750. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  751. go func() {
  752. <-deadlineCtx.Done()
  753. tracer.(*tracers.Tracer).Stop(errors.New("execution timeout"))
  754. }()
  755. defer cancel()
  756. case config == nil:
  757. tracer = vm.NewStructLogger(nil)
  758. default:
  759. tracer = vm.NewStructLogger(config.LogConfig)
  760. }
  761. // Run the transaction with tracing enabled.
  762. vmenv := vm.NewEVM(vmctx, txContext, statedb, api.eth.blockchain.Config(), vm.Config{Debug: true, Tracer: tracer})
  763. result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  764. if err != nil {
  765. return nil, fmt.Errorf("tracing failed: %v", err)
  766. }
  767. // Depending on the tracer type, format and return the output
  768. switch tracer := tracer.(type) {
  769. case *vm.StructLogger:
  770. // If the result contains a revert reason, return it.
  771. returnVal := fmt.Sprintf("%x", result.Return())
  772. if len(result.Revert()) > 0 {
  773. returnVal = fmt.Sprintf("%x", result.Revert())
  774. }
  775. return &ethapi.ExecutionResult{
  776. Gas: result.UsedGas,
  777. Failed: result.Failed(),
  778. ReturnValue: returnVal,
  779. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  780. }, nil
  781. case *tracers.Tracer:
  782. return tracer.GetResult()
  783. default:
  784. panic(fmt.Sprintf("bad tracer type %T", tracer))
  785. }
  786. }
  787. // computeTxEnv returns the execution environment of a certain transaction.
  788. func (api *PrivateDebugAPI) computeTxEnv(block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error) {
  789. // Create the parent state database
  790. parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1)
  791. if parent == nil {
  792. return nil, vm.BlockContext{}, nil, fmt.Errorf("parent %#x not found", block.ParentHash())
  793. }
  794. statedb, err := api.computeStateDB(parent, reexec)
  795. if err != nil {
  796. return nil, vm.BlockContext{}, nil, err
  797. }
  798. if txIndex == 0 && len(block.Transactions()) == 0 {
  799. return nil, vm.BlockContext{}, statedb, nil
  800. }
  801. // Recompute transactions up to the target index.
  802. signer := types.MakeSigner(api.eth.blockchain.Config(), block.Number())
  803. for idx, tx := range block.Transactions() {
  804. // Assemble the transaction call message and return if the requested offset
  805. msg, _ := tx.AsMessage(signer)
  806. txContext := core.NewEVMTxContext(msg)
  807. context := core.NewEVMBlockContext(block.Header(), api.eth.blockchain, nil)
  808. if idx == txIndex {
  809. return msg, context, statedb, nil
  810. }
  811. // Not yet the searched for transaction, execute on top of the current state
  812. vmenv := vm.NewEVM(context, txContext, statedb, api.eth.blockchain.Config(), vm.Config{})
  813. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil {
  814. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction %#x failed: %v", tx.Hash(), err)
  815. }
  816. // Ensure any modifications are committed to the state
  817. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  818. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  819. }
  820. return nil, vm.BlockContext{}, nil, fmt.Errorf("transaction index %d out of range for block %#x", txIndex, block.Hash())
  821. }