api.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // Copyright 2021 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 tracers
  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/consensus"
  31. "github.com/ethereum/go-ethereum/core"
  32. "github.com/ethereum/go-ethereum/core/rawdb"
  33. "github.com/ethereum/go-ethereum/core/state"
  34. "github.com/ethereum/go-ethereum/core/types"
  35. "github.com/ethereum/go-ethereum/core/vm"
  36. "github.com/ethereum/go-ethereum/ethdb"
  37. "github.com/ethereum/go-ethereum/internal/ethapi"
  38. "github.com/ethereum/go-ethereum/log"
  39. "github.com/ethereum/go-ethereum/params"
  40. "github.com/ethereum/go-ethereum/rlp"
  41. "github.com/ethereum/go-ethereum/rpc"
  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. // Backend interface provides the common API services (that are provided by
  53. // both full and light clients) with access to necessary functions.
  54. type Backend interface {
  55. HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
  56. HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
  57. BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
  58. BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
  59. GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error)
  60. RPCGasCap() uint64
  61. ChainConfig() *params.ChainConfig
  62. Engine() consensus.Engine
  63. ChainDb() ethdb.Database
  64. StateAtBlock(ctx context.Context, block *types.Block, reexec uint64) (*state.StateDB, func(), error)
  65. StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, func(), error)
  66. StatesInRange(ctx context.Context, fromBlock *types.Block, toBlock *types.Block, reexec uint64) ([]*state.StateDB, func(), error)
  67. }
  68. // API is the collection of tracing APIs exposed over the private debugging endpoint.
  69. type API struct {
  70. backend Backend
  71. }
  72. // NewAPI creates a new API definition for the tracing methods of the Ethereum service.
  73. func NewAPI(backend Backend) *API {
  74. return &API{backend: backend}
  75. }
  76. type chainContext struct {
  77. api *API
  78. ctx context.Context
  79. }
  80. func (context *chainContext) Engine() consensus.Engine {
  81. return context.api.backend.Engine()
  82. }
  83. func (context *chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  84. header, err := context.api.backend.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
  85. if err != nil {
  86. return nil
  87. }
  88. if header.Hash() == hash {
  89. return header
  90. }
  91. header, err = context.api.backend.HeaderByHash(context.ctx, hash)
  92. if err != nil {
  93. return nil
  94. }
  95. return header
  96. }
  97. // chainContext construts the context reader which is used by the evm for reading
  98. // the necessary chain context.
  99. func (api *API) chainContext(ctx context.Context) core.ChainContext {
  100. return &chainContext{api: api, ctx: ctx}
  101. }
  102. // blockByNumber is the wrapper of the chain access function offered by the backend.
  103. // It will return an error if the block is not found.
  104. func (api *API) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
  105. block, err := api.backend.BlockByNumber(ctx, number)
  106. if err != nil {
  107. return nil, err
  108. }
  109. if block == nil {
  110. return nil, fmt.Errorf("block #%d not found", number)
  111. }
  112. return block, nil
  113. }
  114. // blockByHash is the wrapper of the chain access function offered by the backend.
  115. // It will return an error if the block is not found.
  116. func (api *API) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  117. block, err := api.backend.BlockByHash(ctx, hash)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if block == nil {
  122. return nil, fmt.Errorf("block %s not found", hash.Hex())
  123. }
  124. return block, nil
  125. }
  126. // blockByNumberAndHash is the wrapper of the chain access function offered by
  127. // the backend. It will return an error if the block is not found.
  128. //
  129. // Note this function is friendly for the light client which can only retrieve the
  130. // historical(before the CHT) header/block by number.
  131. func (api *API) blockByNumberAndHash(ctx context.Context, number rpc.BlockNumber, hash common.Hash) (*types.Block, error) {
  132. block, err := api.blockByNumber(ctx, number)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if block.Hash() == hash {
  137. return block, nil
  138. }
  139. return api.blockByHash(ctx, hash)
  140. }
  141. // TraceConfig holds extra parameters to trace functions.
  142. type TraceConfig struct {
  143. *vm.LogConfig
  144. Tracer *string
  145. Timeout *string
  146. Reexec *uint64
  147. }
  148. // StdTraceConfig holds extra parameters to standard-json trace functions.
  149. type StdTraceConfig struct {
  150. vm.LogConfig
  151. Reexec *uint64
  152. TxHash common.Hash
  153. }
  154. // txTraceResult is the result of a single transaction trace.
  155. type txTraceResult struct {
  156. Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
  157. Error string `json:"error,omitempty"` // Trace failure produced by the tracer
  158. }
  159. // blockTraceTask represents a single block trace task when an entire chain is
  160. // being traced.
  161. type blockTraceTask struct {
  162. statedb *state.StateDB // Intermediate state prepped for tracing
  163. block *types.Block // Block to trace the transactions from
  164. results []*txTraceResult // Trace results procudes by the task
  165. }
  166. // blockTraceResult represets the results of tracing a single block when an entire
  167. // chain is being traced.
  168. type blockTraceResult struct {
  169. Block hexutil.Uint64 `json:"block"` // Block number corresponding to this trace
  170. Hash common.Hash `json:"hash"` // Block hash corresponding to this trace
  171. Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
  172. }
  173. // txTraceTask represents a single transaction trace task when an entire block
  174. // is being traced.
  175. type txTraceTask struct {
  176. statedb *state.StateDB // Intermediate state prepped for tracing
  177. index int // Transaction offset in the block
  178. }
  179. // TraceChain returns the structured logs created during the execution of EVM
  180. // between two blocks (excluding start) and returns them as a JSON object.
  181. func (api *API) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) { // Fetch the block interval that we want to trace
  182. from, err := api.blockByNumber(ctx, start)
  183. if err != nil {
  184. return nil, err
  185. }
  186. to, err := api.blockByNumber(ctx, end)
  187. if err != nil {
  188. return nil, err
  189. }
  190. if from.Number().Cmp(to.Number()) >= 0 {
  191. return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
  192. }
  193. return api.traceChain(ctx, from, to, config)
  194. }
  195. // traceChain configures a new tracer according to the provided configuration, and
  196. // executes all the transactions contained within. The return value will be one item
  197. // per transaction, dependent on the requested tracer.
  198. func (api *API) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
  199. // Tracing a chain is a **long** operation, only do with subscriptions
  200. notifier, supported := rpc.NotifierFromContext(ctx)
  201. if !supported {
  202. return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
  203. }
  204. sub := notifier.CreateSubscription()
  205. // Shift the border to a block ahead in order to get the states
  206. // before these blocks.
  207. endBlock, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(end.NumberU64()-1), end.ParentHash())
  208. if err != nil {
  209. return nil, err
  210. }
  211. // Prepare all the states for tracing. Note this procedure can take very
  212. // long time. Timeout mechanism is necessary.
  213. reexec := defaultTraceReexec
  214. if config != nil && config.Reexec != nil {
  215. reexec = *config.Reexec
  216. }
  217. states, release, err := api.backend.StatesInRange(ctx, start, endBlock, reexec)
  218. if err != nil {
  219. return nil, err
  220. }
  221. defer release() // Release all the resources in the last step.
  222. blocks := int(end.NumberU64() - start.NumberU64())
  223. threads := runtime.NumCPU()
  224. if threads > blocks {
  225. threads = blocks
  226. }
  227. var (
  228. pend = new(sync.WaitGroup)
  229. tasks = make(chan *blockTraceTask, threads)
  230. results = make(chan *blockTraceTask, threads)
  231. )
  232. for th := 0; th < threads; th++ {
  233. pend.Add(1)
  234. go func() {
  235. defer pend.Done()
  236. // Fetch and execute the next block trace tasks
  237. for task := range tasks {
  238. signer := types.MakeSigner(api.backend.ChainConfig(), task.block.Number())
  239. blockCtx := core.NewEVMBlockContext(task.block.Header(), api.chainContext(ctx), nil)
  240. // Trace all the transactions contained within
  241. for i, tx := range task.block.Transactions() {
  242. msg, _ := tx.AsMessage(signer)
  243. res, err := api.traceTx(ctx, msg, blockCtx, task.statedb, config)
  244. if err != nil {
  245. task.results[i] = &txTraceResult{Error: err.Error()}
  246. log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
  247. break
  248. }
  249. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  250. task.statedb.Finalise(api.backend.ChainConfig().IsEIP158(task.block.Number()))
  251. task.results[i] = &txTraceResult{Result: res}
  252. }
  253. // Stream the result back to the user or abort on teardown
  254. select {
  255. case results <- task:
  256. case <-notifier.Closed():
  257. return
  258. }
  259. }
  260. }()
  261. }
  262. // Start a goroutine to feed all the blocks into the tracers
  263. begin := time.Now()
  264. go func() {
  265. var (
  266. logged time.Time
  267. number uint64
  268. traced uint64
  269. failed error
  270. )
  271. // Ensure everything is properly cleaned up on any exit path
  272. defer func() {
  273. close(tasks)
  274. pend.Wait()
  275. switch {
  276. case failed != nil:
  277. log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
  278. case number < end.NumberU64():
  279. log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
  280. default:
  281. log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
  282. }
  283. close(results)
  284. }()
  285. // Feed all the blocks both into the tracer, as well as fast process concurrently
  286. for number = start.NumberU64() + 1; number <= end.NumberU64(); number++ {
  287. // Stop tracing if interruption was requested
  288. select {
  289. case <-notifier.Closed():
  290. return
  291. default:
  292. }
  293. // Print progress logs if long enough time elapsed
  294. if time.Since(logged) > 8*time.Second {
  295. logged = time.Now()
  296. log.Info("Tracing chain segment", "start", start.NumberU64(), "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin))
  297. }
  298. // Retrieve the next block to trace
  299. block, err := api.blockByNumber(ctx, rpc.BlockNumber(number))
  300. if err != nil {
  301. failed = err
  302. break
  303. }
  304. // Send the block over to the concurrent tracers (if not in the fast-forward phase)
  305. txs := block.Transactions()
  306. select {
  307. case tasks <- &blockTraceTask{statedb: states[int(number-start.NumberU64()-1)], block: block, results: make([]*txTraceResult, len(txs))}:
  308. case <-notifier.Closed():
  309. return
  310. }
  311. traced += uint64(len(txs))
  312. }
  313. }()
  314. // Keep reading the trace results and stream the to the user
  315. go func() {
  316. var (
  317. done = make(map[uint64]*blockTraceResult)
  318. next = start.NumberU64() + 1
  319. )
  320. for res := range results {
  321. // Queue up next received result
  322. result := &blockTraceResult{
  323. Block: hexutil.Uint64(res.block.NumberU64()),
  324. Hash: res.block.Hash(),
  325. Traces: res.results,
  326. }
  327. done[uint64(result.Block)] = result
  328. // Stream completed traces to the user, aborting on the first error
  329. for result, ok := done[next]; ok; result, ok = done[next] {
  330. if len(result.Traces) > 0 || next == end.NumberU64() {
  331. notifier.Notify(sub.ID, result)
  332. }
  333. delete(done, next)
  334. next++
  335. }
  336. }
  337. }()
  338. return sub, nil
  339. }
  340. // TraceBlockByNumber returns the structured logs created during the execution of
  341. // EVM and returns them as a JSON object.
  342. func (api *API) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  343. block, err := api.blockByNumber(ctx, number)
  344. if err != nil {
  345. return nil, err
  346. }
  347. return api.traceBlock(ctx, block, config)
  348. }
  349. // TraceBlockByHash returns the structured logs created during the execution of
  350. // EVM and returns them as a JSON object.
  351. func (api *API) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  352. block, err := api.blockByHash(ctx, hash)
  353. if err != nil {
  354. return nil, err
  355. }
  356. return api.traceBlock(ctx, block, config)
  357. }
  358. // TraceBlock returns the structured logs created during the execution of EVM
  359. // and returns them as a JSON object.
  360. func (api *API) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
  361. block := new(types.Block)
  362. if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
  363. return nil, fmt.Errorf("could not decode block: %v", err)
  364. }
  365. return api.traceBlock(ctx, block, config)
  366. }
  367. // TraceBlockFromFile returns the structured logs created during the execution of
  368. // EVM and returns them as a JSON object.
  369. func (api *API) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
  370. blob, err := ioutil.ReadFile(file)
  371. if err != nil {
  372. return nil, fmt.Errorf("could not read file: %v", err)
  373. }
  374. return api.TraceBlock(ctx, blob, config)
  375. }
  376. // TraceBadBlock returns the structured logs created during the execution of
  377. // EVM against a block pulled from the pool of bad ones and returns them as a JSON
  378. // object.
  379. func (api *API) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  380. for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
  381. if block.Hash() == hash {
  382. return api.traceBlock(ctx, block, config)
  383. }
  384. }
  385. return nil, fmt.Errorf("bad block %#x not found", hash)
  386. }
  387. // StandardTraceBlockToFile dumps the structured logs created during the
  388. // execution of EVM to the local file system and returns a list of files
  389. // to the caller.
  390. func (api *API) StandardTraceBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  391. block, err := api.blockByHash(ctx, hash)
  392. if err != nil {
  393. return nil, err
  394. }
  395. return api.standardTraceBlockToFile(ctx, block, config)
  396. }
  397. // StandardTraceBadBlockToFile dumps the structured logs created during the
  398. // execution of EVM against a block pulled from the pool of bad ones to the
  399. // local file system and returns a list of files to the caller.
  400. func (api *API) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  401. for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
  402. if block.Hash() == hash {
  403. return api.standardTraceBlockToFile(ctx, block, config)
  404. }
  405. }
  406. return nil, fmt.Errorf("bad block %#x not found", hash)
  407. }
  408. // traceBlock configures a new tracer according to the provided configuration, and
  409. // executes all the transactions contained within. The return value will be one item
  410. // per transaction, dependent on the requestd tracer.
  411. func (api *API) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
  412. if block.NumberU64() == 0 {
  413. return nil, errors.New("genesis is not traceable")
  414. }
  415. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  416. if err != nil {
  417. return nil, err
  418. }
  419. reexec := defaultTraceReexec
  420. if config != nil && config.Reexec != nil {
  421. reexec = *config.Reexec
  422. }
  423. statedb, release, err := api.backend.StateAtBlock(ctx, parent, reexec)
  424. if err != nil {
  425. return nil, err
  426. }
  427. defer release()
  428. // Execute all the transaction contained within the block concurrently
  429. var (
  430. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  431. txs = block.Transactions()
  432. results = make([]*txTraceResult, len(txs))
  433. pend = new(sync.WaitGroup)
  434. jobs = make(chan *txTraceTask, len(txs))
  435. )
  436. threads := runtime.NumCPU()
  437. if threads > len(txs) {
  438. threads = len(txs)
  439. }
  440. blockCtx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  441. for th := 0; th < threads; th++ {
  442. pend.Add(1)
  443. go func() {
  444. defer pend.Done()
  445. // Fetch and execute the next transaction trace tasks
  446. for task := range jobs {
  447. msg, _ := txs[task.index].AsMessage(signer)
  448. res, err := api.traceTx(ctx, msg, blockCtx, task.statedb, config)
  449. if err != nil {
  450. results[task.index] = &txTraceResult{Error: err.Error()}
  451. continue
  452. }
  453. results[task.index] = &txTraceResult{Result: res}
  454. }
  455. }()
  456. }
  457. // Feed the transactions into the tracers and return
  458. var failed error
  459. for i, tx := range txs {
  460. // Send the trace task over for execution
  461. jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  462. // Generate the next state snapshot fast without tracing
  463. msg, _ := tx.AsMessage(signer)
  464. txContext := core.NewEVMTxContext(msg)
  465. vmenv := vm.NewEVM(blockCtx, txContext, statedb, api.backend.ChainConfig(), vm.Config{})
  466. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  467. failed = err
  468. break
  469. }
  470. // Finalize the state so any modifications are written to the trie
  471. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  472. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  473. }
  474. close(jobs)
  475. pend.Wait()
  476. // If execution failed in between, abort
  477. if failed != nil {
  478. return nil, failed
  479. }
  480. return results, nil
  481. }
  482. // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
  483. // and traces either a full block or an individual transaction. The return value will
  484. // be one filename per transaction traced.
  485. func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
  486. // If we're tracing a single transaction, make sure it's present
  487. if config != nil && config.TxHash != (common.Hash{}) {
  488. if !containsTx(block, config.TxHash) {
  489. return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
  490. }
  491. }
  492. if block.NumberU64() == 0 {
  493. return nil, errors.New("genesis is not traceable")
  494. }
  495. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  496. if err != nil {
  497. return nil, err
  498. }
  499. reexec := defaultTraceReexec
  500. if config != nil && config.Reexec != nil {
  501. reexec = *config.Reexec
  502. }
  503. statedb, release, err := api.backend.StateAtBlock(ctx, parent, reexec)
  504. if err != nil {
  505. return nil, err
  506. }
  507. defer release()
  508. // Retrieve the tracing configurations, or use default values
  509. var (
  510. logConfig vm.LogConfig
  511. txHash common.Hash
  512. )
  513. if config != nil {
  514. logConfig = config.LogConfig
  515. txHash = config.TxHash
  516. }
  517. logConfig.Debug = true
  518. // Execute transaction, either tracing all or just the requested one
  519. var (
  520. dumps []string
  521. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  522. chainConfig = api.backend.ChainConfig()
  523. vmctx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), 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 yolov3 := config.LogConfig.Overrides.YoloV3Block; yolov3 != nil {
  538. chainConfig.YoloV3Block = yolov3
  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. // TraceTransaction returns the structured logs created during the execution of EVM
  606. // and returns them as a JSON object.
  607. func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  608. _, blockHash, blockNumber, index, err := api.backend.GetTransaction(ctx, hash)
  609. if err != nil {
  610. return nil, err
  611. }
  612. // It shouldn't happen in practice.
  613. if blockNumber == 0 {
  614. return nil, errors.New("genesis is not traceable")
  615. }
  616. reexec := defaultTraceReexec
  617. if config != nil && config.Reexec != nil {
  618. reexec = *config.Reexec
  619. }
  620. block, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(blockNumber), blockHash)
  621. if err != nil {
  622. return nil, err
  623. }
  624. msg, vmctx, statedb, release, err := api.backend.StateAtTransaction(ctx, block, int(index), reexec)
  625. if err != nil {
  626. return nil, err
  627. }
  628. defer release()
  629. return api.traceTx(ctx, msg, vmctx, statedb, config)
  630. }
  631. // TraceCall lets you trace a given eth_call. It collects the structured logs
  632. // created during the execution of EVM if the given transaction was added on
  633. // top of the provided block and returns them as a JSON object.
  634. // You can provide -2 as a block number to trace on top of the pending block.
  635. func (api *API) TraceCall(ctx context.Context, args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceConfig) (interface{}, error) {
  636. // Try to retrieve the specified block
  637. var (
  638. err error
  639. block *types.Block
  640. )
  641. if hash, ok := blockNrOrHash.Hash(); ok {
  642. block, err = api.blockByHash(ctx, hash)
  643. } else if number, ok := blockNrOrHash.Number(); ok {
  644. block, err = api.blockByNumber(ctx, number)
  645. }
  646. if err != nil {
  647. return nil, err
  648. }
  649. // try to recompute the state
  650. reexec := defaultTraceReexec
  651. if config != nil && config.Reexec != nil {
  652. reexec = *config.Reexec
  653. }
  654. statedb, release, err := api.backend.StateAtBlock(ctx, block, reexec)
  655. if err != nil {
  656. return nil, err
  657. }
  658. defer release()
  659. // Execute the trace
  660. msg := args.ToMessage(api.backend.RPCGasCap())
  661. vmctx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  662. return api.traceTx(ctx, msg, vmctx, statedb, config)
  663. }
  664. // traceTx configures a new tracer according to the provided configuration, and
  665. // executes the given message in the provided environment. The return value will
  666. // be tracer dependent.
  667. func (api *API) traceTx(ctx context.Context, message core.Message, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  668. // Assemble the structured logger or the JavaScript tracer
  669. var (
  670. tracer vm.Tracer
  671. err error
  672. txContext = core.NewEVMTxContext(message)
  673. )
  674. switch {
  675. case config != nil && config.Tracer != nil:
  676. // Define a meaningful timeout of a single transaction trace
  677. timeout := defaultTraceTimeout
  678. if config.Timeout != nil {
  679. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  680. return nil, err
  681. }
  682. }
  683. // Constuct the JavaScript tracer to execute with
  684. if tracer, err = New(*config.Tracer, txContext); err != nil {
  685. return nil, err
  686. }
  687. // Handle timeouts and RPC cancellations
  688. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  689. go func() {
  690. <-deadlineCtx.Done()
  691. tracer.(*Tracer).Stop(errors.New("execution timeout"))
  692. }()
  693. defer cancel()
  694. case config == nil:
  695. tracer = vm.NewStructLogger(nil)
  696. default:
  697. tracer = vm.NewStructLogger(config.LogConfig)
  698. }
  699. // Run the transaction with tracing enabled.
  700. vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer})
  701. result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  702. if err != nil {
  703. return nil, fmt.Errorf("tracing failed: %v", err)
  704. }
  705. // Depending on the tracer type, format and return the output
  706. switch tracer := tracer.(type) {
  707. case *vm.StructLogger:
  708. // If the result contains a revert reason, return it.
  709. returnVal := fmt.Sprintf("%x", result.Return())
  710. if len(result.Revert()) > 0 {
  711. returnVal = fmt.Sprintf("%x", result.Revert())
  712. }
  713. return &ethapi.ExecutionResult{
  714. Gas: result.UsedGas,
  715. Failed: result.Failed(),
  716. ReturnValue: returnVal,
  717. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  718. }, nil
  719. case *Tracer:
  720. return tracer.GetResult()
  721. default:
  722. panic(fmt.Sprintf("bad tracer type %T", tracer))
  723. }
  724. }
  725. // APIs return the collection of RPC services the tracer package offers.
  726. func APIs(backend Backend) []rpc.API {
  727. // Append all the local APIs and return
  728. return []rpc.API{
  729. {
  730. Namespace: "debug",
  731. Version: "1.0",
  732. Service: NewAPI(backend),
  733. Public: false,
  734. },
  735. }
  736. }