api.go 28 KB

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