api.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. // txTraceContext is the contextual infos about a transaction before it gets run.
  155. type txTraceContext struct {
  156. index int // Index of the transaction within the block
  157. hash common.Hash // Hash of the transaction
  158. block common.Hash // Hash of the block containing the transaction
  159. }
  160. // txTraceResult is the result of a single transaction trace.
  161. type txTraceResult struct {
  162. Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
  163. Error string `json:"error,omitempty"` // Trace failure produced by the tracer
  164. }
  165. // blockTraceTask represents a single block trace task when an entire chain is
  166. // being traced.
  167. type blockTraceTask struct {
  168. statedb *state.StateDB // Intermediate state prepped for tracing
  169. block *types.Block // Block to trace the transactions from
  170. results []*txTraceResult // Trace results procudes by the task
  171. }
  172. // blockTraceResult represets the results of tracing a single block when an entire
  173. // chain is being traced.
  174. type blockTraceResult struct {
  175. Block hexutil.Uint64 `json:"block"` // Block number corresponding to this trace
  176. Hash common.Hash `json:"hash"` // Block hash corresponding to this trace
  177. Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
  178. }
  179. // txTraceTask represents a single transaction trace task when an entire block
  180. // is being traced.
  181. type txTraceTask struct {
  182. statedb *state.StateDB // Intermediate state prepped for tracing
  183. index int // Transaction offset in the block
  184. }
  185. // TraceChain returns the structured logs created during the execution of EVM
  186. // between two blocks (excluding start) and returns them as a JSON object.
  187. 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
  188. from, err := api.blockByNumber(ctx, start)
  189. if err != nil {
  190. return nil, err
  191. }
  192. to, err := api.blockByNumber(ctx, end)
  193. if err != nil {
  194. return nil, err
  195. }
  196. if from.Number().Cmp(to.Number()) >= 0 {
  197. return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
  198. }
  199. return api.traceChain(ctx, from, to, config)
  200. }
  201. // traceChain configures a new tracer according to the provided configuration, and
  202. // executes all the transactions contained within. The return value will be one item
  203. // per transaction, dependent on the requested tracer.
  204. func (api *API) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
  205. // Tracing a chain is a **long** operation, only do with subscriptions
  206. notifier, supported := rpc.NotifierFromContext(ctx)
  207. if !supported {
  208. return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
  209. }
  210. sub := notifier.CreateSubscription()
  211. // Shift the border to a block ahead in order to get the states
  212. // before these blocks.
  213. endBlock, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(end.NumberU64()-1), end.ParentHash())
  214. if err != nil {
  215. return nil, err
  216. }
  217. // Prepare all the states for tracing. Note this procedure can take very
  218. // long time. Timeout mechanism is necessary.
  219. reexec := defaultTraceReexec
  220. if config != nil && config.Reexec != nil {
  221. reexec = *config.Reexec
  222. }
  223. states, release, err := api.backend.StatesInRange(ctx, start, endBlock, reexec)
  224. if err != nil {
  225. return nil, err
  226. }
  227. defer release() // Release all the resources in the last step.
  228. blocks := int(end.NumberU64() - start.NumberU64())
  229. threads := runtime.NumCPU()
  230. if threads > blocks {
  231. threads = blocks
  232. }
  233. var (
  234. pend = new(sync.WaitGroup)
  235. tasks = make(chan *blockTraceTask, threads)
  236. results = make(chan *blockTraceTask, threads)
  237. )
  238. for th := 0; th < threads; th++ {
  239. pend.Add(1)
  240. go func() {
  241. defer pend.Done()
  242. // Fetch and execute the next block trace tasks
  243. for task := range tasks {
  244. signer := types.MakeSigner(api.backend.ChainConfig(), task.block.Number())
  245. blockCtx := core.NewEVMBlockContext(task.block.Header(), api.chainContext(ctx), nil)
  246. // Trace all the transactions contained within
  247. for i, tx := range task.block.Transactions() {
  248. msg, _ := tx.AsMessage(signer)
  249. txctx := &txTraceContext{
  250. index: i,
  251. hash: tx.Hash(),
  252. block: task.block.Hash(),
  253. }
  254. res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
  255. if err != nil {
  256. task.results[i] = &txTraceResult{Error: err.Error()}
  257. log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
  258. break
  259. }
  260. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  261. task.statedb.Finalise(api.backend.ChainConfig().IsEIP158(task.block.Number()))
  262. task.results[i] = &txTraceResult{Result: res}
  263. }
  264. // Stream the result back to the user or abort on teardown
  265. select {
  266. case results <- task:
  267. case <-notifier.Closed():
  268. return
  269. }
  270. }
  271. }()
  272. }
  273. // Start a goroutine to feed all the blocks into the tracers
  274. begin := time.Now()
  275. go func() {
  276. var (
  277. logged time.Time
  278. number uint64
  279. traced uint64
  280. failed error
  281. )
  282. // Ensure everything is properly cleaned up on any exit path
  283. defer func() {
  284. close(tasks)
  285. pend.Wait()
  286. switch {
  287. case failed != nil:
  288. log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
  289. case number < end.NumberU64():
  290. log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
  291. default:
  292. log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
  293. }
  294. close(results)
  295. }()
  296. // Feed all the blocks both into the tracer, as well as fast process concurrently
  297. for number = start.NumberU64() + 1; number <= end.NumberU64(); number++ {
  298. // Stop tracing if interruption was requested
  299. select {
  300. case <-notifier.Closed():
  301. return
  302. default:
  303. }
  304. // Print progress logs if long enough time elapsed
  305. if time.Since(logged) > 8*time.Second {
  306. logged = time.Now()
  307. log.Info("Tracing chain segment", "start", start.NumberU64(), "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin))
  308. }
  309. // Retrieve the next block to trace
  310. block, err := api.blockByNumber(ctx, rpc.BlockNumber(number))
  311. if err != nil {
  312. failed = err
  313. break
  314. }
  315. // Send the block over to the concurrent tracers (if not in the fast-forward phase)
  316. txs := block.Transactions()
  317. select {
  318. case tasks <- &blockTraceTask{statedb: states[int(number-start.NumberU64()-1)], block: block, results: make([]*txTraceResult, len(txs))}:
  319. case <-notifier.Closed():
  320. return
  321. }
  322. traced += uint64(len(txs))
  323. }
  324. }()
  325. // Keep reading the trace results and stream the to the user
  326. go func() {
  327. var (
  328. done = make(map[uint64]*blockTraceResult)
  329. next = start.NumberU64() + 1
  330. )
  331. for res := range results {
  332. // Queue up next received result
  333. result := &blockTraceResult{
  334. Block: hexutil.Uint64(res.block.NumberU64()),
  335. Hash: res.block.Hash(),
  336. Traces: res.results,
  337. }
  338. done[uint64(result.Block)] = result
  339. // Stream completed traces to the user, aborting on the first error
  340. for result, ok := done[next]; ok; result, ok = done[next] {
  341. if len(result.Traces) > 0 || next == end.NumberU64() {
  342. notifier.Notify(sub.ID, result)
  343. }
  344. delete(done, next)
  345. next++
  346. }
  347. }
  348. }()
  349. return sub, nil
  350. }
  351. // TraceBlockByNumber returns the structured logs created during the execution of
  352. // EVM and returns them as a JSON object.
  353. func (api *API) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  354. block, err := api.blockByNumber(ctx, number)
  355. if err != nil {
  356. return nil, err
  357. }
  358. return api.traceBlock(ctx, block, config)
  359. }
  360. // TraceBlockByHash returns the structured logs created during the execution of
  361. // EVM and returns them as a JSON object.
  362. func (api *API) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  363. block, err := api.blockByHash(ctx, hash)
  364. if err != nil {
  365. return nil, err
  366. }
  367. return api.traceBlock(ctx, block, config)
  368. }
  369. // TraceBlock returns the structured logs created during the execution of EVM
  370. // and returns them as a JSON object.
  371. func (api *API) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
  372. block := new(types.Block)
  373. if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
  374. return nil, fmt.Errorf("could not decode block: %v", err)
  375. }
  376. return api.traceBlock(ctx, block, config)
  377. }
  378. // TraceBlockFromFile returns the structured logs created during the execution of
  379. // EVM and returns them as a JSON object.
  380. func (api *API) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
  381. blob, err := ioutil.ReadFile(file)
  382. if err != nil {
  383. return nil, fmt.Errorf("could not read file: %v", err)
  384. }
  385. return api.TraceBlock(ctx, blob, config)
  386. }
  387. // TraceBadBlock returns the structured logs created during the execution of
  388. // EVM against a block pulled from the pool of bad ones and returns them as a JSON
  389. // object.
  390. func (api *API) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  391. for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
  392. if block.Hash() == hash {
  393. return api.traceBlock(ctx, block, config)
  394. }
  395. }
  396. return nil, fmt.Errorf("bad block %#x not found", hash)
  397. }
  398. // StandardTraceBlockToFile dumps the structured logs created during the
  399. // execution of EVM to the local file system and returns a list of files
  400. // to the caller.
  401. func (api *API) StandardTraceBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  402. block, err := api.blockByHash(ctx, hash)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return api.standardTraceBlockToFile(ctx, block, config)
  407. }
  408. // StandardTraceBadBlockToFile dumps the structured logs created during the
  409. // execution of EVM against a block pulled from the pool of bad ones to the
  410. // local file system and returns a list of files to the caller.
  411. func (api *API) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  412. for _, block := range rawdb.ReadAllBadBlocks(api.backend.ChainDb()) {
  413. if block.Hash() == hash {
  414. return api.standardTraceBlockToFile(ctx, block, config)
  415. }
  416. }
  417. return nil, fmt.Errorf("bad block %#x not found", hash)
  418. }
  419. // traceBlock configures a new tracer according to the provided configuration, and
  420. // executes all the transactions contained within. The return value will be one item
  421. // per transaction, dependent on the requestd tracer.
  422. func (api *API) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
  423. if block.NumberU64() == 0 {
  424. return nil, errors.New("genesis is not traceable")
  425. }
  426. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  427. if err != nil {
  428. return nil, err
  429. }
  430. reexec := defaultTraceReexec
  431. if config != nil && config.Reexec != nil {
  432. reexec = *config.Reexec
  433. }
  434. statedb, release, err := api.backend.StateAtBlock(ctx, parent, reexec)
  435. if err != nil {
  436. return nil, err
  437. }
  438. defer release()
  439. // Execute all the transaction contained within the block concurrently
  440. var (
  441. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  442. txs = block.Transactions()
  443. results = make([]*txTraceResult, len(txs))
  444. pend = new(sync.WaitGroup)
  445. jobs = make(chan *txTraceTask, len(txs))
  446. )
  447. threads := runtime.NumCPU()
  448. if threads > len(txs) {
  449. threads = len(txs)
  450. }
  451. blockCtx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  452. blockHash := block.Hash()
  453. for th := 0; th < threads; th++ {
  454. pend.Add(1)
  455. go func() {
  456. defer pend.Done()
  457. // Fetch and execute the next transaction trace tasks
  458. for task := range jobs {
  459. msg, _ := txs[task.index].AsMessage(signer)
  460. txctx := &txTraceContext{
  461. index: task.index,
  462. hash: txs[task.index].Hash(),
  463. block: blockHash,
  464. }
  465. res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
  466. if err != nil {
  467. results[task.index] = &txTraceResult{Error: err.Error()}
  468. continue
  469. }
  470. results[task.index] = &txTraceResult{Result: res}
  471. }
  472. }()
  473. }
  474. // Feed the transactions into the tracers and return
  475. var failed error
  476. for i, tx := range txs {
  477. // Send the trace task over for execution
  478. jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  479. // Generate the next state snapshot fast without tracing
  480. msg, _ := tx.AsMessage(signer)
  481. statedb.Prepare(tx.Hash(), block.Hash(), i)
  482. vmenv := vm.NewEVM(blockCtx, core.NewEVMTxContext(msg), statedb, api.backend.ChainConfig(), vm.Config{})
  483. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  484. failed = err
  485. break
  486. }
  487. // Finalize the state so any modifications are written to the trie
  488. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  489. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  490. }
  491. close(jobs)
  492. pend.Wait()
  493. // If execution failed in between, abort
  494. if failed != nil {
  495. return nil, failed
  496. }
  497. return results, nil
  498. }
  499. // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
  500. // and traces either a full block or an individual transaction. The return value will
  501. // be one filename per transaction traced.
  502. func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
  503. // If we're tracing a single transaction, make sure it's present
  504. if config != nil && config.TxHash != (common.Hash{}) {
  505. if !containsTx(block, config.TxHash) {
  506. return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
  507. }
  508. }
  509. if block.NumberU64() == 0 {
  510. return nil, errors.New("genesis is not traceable")
  511. }
  512. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  513. if err != nil {
  514. return nil, err
  515. }
  516. reexec := defaultTraceReexec
  517. if config != nil && config.Reexec != nil {
  518. reexec = *config.Reexec
  519. }
  520. statedb, release, err := api.backend.StateAtBlock(ctx, parent, reexec)
  521. if err != nil {
  522. return nil, err
  523. }
  524. defer release()
  525. // Retrieve the tracing configurations, or use default values
  526. var (
  527. logConfig vm.LogConfig
  528. txHash common.Hash
  529. )
  530. if config != nil {
  531. logConfig = config.LogConfig
  532. txHash = config.TxHash
  533. }
  534. logConfig.Debug = true
  535. // Execute transaction, either tracing all or just the requested one
  536. var (
  537. dumps []string
  538. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  539. chainConfig = api.backend.ChainConfig()
  540. vmctx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  541. canon = true
  542. )
  543. // Check if there are any overrides: the caller may wish to enable a future
  544. // fork when executing this block. Note, such overrides are only applicable to the
  545. // actual specified block, not any preceding blocks that we have to go through
  546. // in order to obtain the state.
  547. // Therefore, it's perfectly valid to specify `"futureForkBlock": 0`, to enable `futureFork`
  548. if config != nil && config.Overrides != nil {
  549. // Copy the config, to not screw up the main config
  550. // Note: the Clique-part is _not_ deep copied
  551. chainConfigCopy := new(params.ChainConfig)
  552. *chainConfigCopy = *chainConfig
  553. chainConfig = chainConfigCopy
  554. if berlin := config.LogConfig.Overrides.BerlinBlock; berlin != nil {
  555. chainConfig.BerlinBlock = berlin
  556. canon = false
  557. }
  558. }
  559. for i, tx := range block.Transactions() {
  560. // Prepare the trasaction for un-traced execution
  561. var (
  562. msg, _ = tx.AsMessage(signer)
  563. txContext = core.NewEVMTxContext(msg)
  564. vmConf vm.Config
  565. dump *os.File
  566. writer *bufio.Writer
  567. err error
  568. )
  569. // If the transaction needs tracing, swap out the configs
  570. if tx.Hash() == txHash || txHash == (common.Hash{}) {
  571. // Generate a unique temporary file to dump it into
  572. prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
  573. if !canon {
  574. prefix = fmt.Sprintf("%valt-", prefix)
  575. }
  576. dump, err = ioutil.TempFile(os.TempDir(), prefix)
  577. if err != nil {
  578. return nil, err
  579. }
  580. dumps = append(dumps, dump.Name())
  581. // Swap out the noop logger to the standard tracer
  582. writer = bufio.NewWriter(dump)
  583. vmConf = vm.Config{
  584. Debug: true,
  585. Tracer: vm.NewJSONLogger(&logConfig, writer),
  586. EnablePreimageRecording: true,
  587. }
  588. }
  589. // Execute the transaction and flush any traces to disk
  590. vmenv := vm.NewEVM(vmctx, txContext, statedb, chainConfig, vmConf)
  591. statedb.Prepare(tx.Hash(), block.Hash(), i)
  592. _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  593. if writer != nil {
  594. writer.Flush()
  595. }
  596. if dump != nil {
  597. dump.Close()
  598. log.Info("Wrote standard trace", "file", dump.Name())
  599. }
  600. if err != nil {
  601. return dumps, err
  602. }
  603. // Finalize the state so any modifications are written to the trie
  604. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  605. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  606. // If we've traced the transaction we were looking for, abort
  607. if tx.Hash() == txHash {
  608. break
  609. }
  610. }
  611. return dumps, nil
  612. }
  613. // containsTx reports whether the transaction with a certain hash
  614. // is contained within the specified block.
  615. func containsTx(block *types.Block, hash common.Hash) bool {
  616. for _, tx := range block.Transactions() {
  617. if tx.Hash() == hash {
  618. return true
  619. }
  620. }
  621. return false
  622. }
  623. // TraceTransaction returns the structured logs created during the execution of EVM
  624. // and returns them as a JSON object.
  625. func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  626. _, blockHash, blockNumber, index, err := api.backend.GetTransaction(ctx, hash)
  627. if err != nil {
  628. return nil, err
  629. }
  630. // It shouldn't happen in practice.
  631. if blockNumber == 0 {
  632. return nil, errors.New("genesis is not traceable")
  633. }
  634. reexec := defaultTraceReexec
  635. if config != nil && config.Reexec != nil {
  636. reexec = *config.Reexec
  637. }
  638. block, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(blockNumber), blockHash)
  639. if err != nil {
  640. return nil, err
  641. }
  642. msg, vmctx, statedb, release, err := api.backend.StateAtTransaction(ctx, block, int(index), reexec)
  643. if err != nil {
  644. return nil, err
  645. }
  646. defer release()
  647. txctx := &txTraceContext{
  648. index: int(index),
  649. hash: hash,
  650. block: blockHash,
  651. }
  652. return api.traceTx(ctx, msg, txctx, vmctx, statedb, config)
  653. }
  654. // TraceCall lets you trace a given eth_call. It collects the structured logs
  655. // created during the execution of EVM if the given transaction was added on
  656. // top of the provided block and returns them as a JSON object.
  657. // You can provide -2 as a block number to trace on top of the pending block.
  658. func (api *API) TraceCall(ctx context.Context, args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceConfig) (interface{}, error) {
  659. // Try to retrieve the specified block
  660. var (
  661. err error
  662. block *types.Block
  663. )
  664. if hash, ok := blockNrOrHash.Hash(); ok {
  665. block, err = api.blockByHash(ctx, hash)
  666. } else if number, ok := blockNrOrHash.Number(); ok {
  667. block, err = api.blockByNumber(ctx, number)
  668. }
  669. if err != nil {
  670. return nil, err
  671. }
  672. // try to recompute the state
  673. reexec := defaultTraceReexec
  674. if config != nil && config.Reexec != nil {
  675. reexec = *config.Reexec
  676. }
  677. statedb, release, err := api.backend.StateAtBlock(ctx, block, reexec)
  678. if err != nil {
  679. return nil, err
  680. }
  681. defer release()
  682. // Execute the trace
  683. msg := args.ToMessage(api.backend.RPCGasCap())
  684. vmctx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  685. return api.traceTx(ctx, msg, new(txTraceContext), vmctx, statedb, config)
  686. }
  687. // traceTx configures a new tracer according to the provided configuration, and
  688. // executes the given message in the provided environment. The return value will
  689. // be tracer dependent.
  690. func (api *API) traceTx(ctx context.Context, message core.Message, txctx *txTraceContext, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  691. // Assemble the structured logger or the JavaScript tracer
  692. var (
  693. tracer vm.Tracer
  694. err error
  695. txContext = core.NewEVMTxContext(message)
  696. )
  697. switch {
  698. case config != nil && config.Tracer != nil:
  699. // Define a meaningful timeout of a single transaction trace
  700. timeout := defaultTraceTimeout
  701. if config.Timeout != nil {
  702. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  703. return nil, err
  704. }
  705. }
  706. // Constuct the JavaScript tracer to execute with
  707. if tracer, err = New(*config.Tracer, txContext); err != nil {
  708. return nil, err
  709. }
  710. // Handle timeouts and RPC cancellations
  711. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  712. go func() {
  713. <-deadlineCtx.Done()
  714. tracer.(*Tracer).Stop(errors.New("execution timeout"))
  715. }()
  716. defer cancel()
  717. case config == nil:
  718. tracer = vm.NewStructLogger(nil)
  719. default:
  720. tracer = vm.NewStructLogger(config.LogConfig)
  721. }
  722. // Run the transaction with tracing enabled.
  723. vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer})
  724. // Call Prepare to clear out the statedb access list
  725. statedb.Prepare(txctx.hash, txctx.block, txctx.index)
  726. result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  727. if err != nil {
  728. return nil, fmt.Errorf("tracing failed: %v", err)
  729. }
  730. // Depending on the tracer type, format and return the output.
  731. switch tracer := tracer.(type) {
  732. case *vm.StructLogger:
  733. // If the result contains a revert reason, return it.
  734. returnVal := fmt.Sprintf("%x", result.Return())
  735. if len(result.Revert()) > 0 {
  736. returnVal = fmt.Sprintf("%x", result.Revert())
  737. }
  738. return &ethapi.ExecutionResult{
  739. Gas: result.UsedGas,
  740. Failed: result.Failed(),
  741. ReturnValue: returnVal,
  742. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  743. }, nil
  744. case *Tracer:
  745. return tracer.GetResult()
  746. default:
  747. panic(fmt.Sprintf("bad tracer type %T", tracer))
  748. }
  749. }
  750. // APIs return the collection of RPC services the tracer package offers.
  751. func APIs(backend Backend) []rpc.API {
  752. // Append all the local APIs and return
  753. return []rpc.API{
  754. {
  755. Namespace: "debug",
  756. Version: "1.0",
  757. Service: NewAPI(backend),
  758. Public: false,
  759. },
  760. }
  761. }