api.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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. "math/big"
  25. "os"
  26. "runtime"
  27. "sync"
  28. "time"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/common/gopool"
  31. "github.com/ethereum/go-ethereum/common/hexutil"
  32. "github.com/ethereum/go-ethereum/consensus"
  33. "github.com/ethereum/go-ethereum/core"
  34. "github.com/ethereum/go-ethereum/core/rawdb"
  35. "github.com/ethereum/go-ethereum/core/state"
  36. "github.com/ethereum/go-ethereum/core/types"
  37. "github.com/ethereum/go-ethereum/core/vm"
  38. "github.com/ethereum/go-ethereum/ethdb"
  39. "github.com/ethereum/go-ethereum/internal/ethapi"
  40. "github.com/ethereum/go-ethereum/log"
  41. "github.com/ethereum/go-ethereum/params"
  42. "github.com/ethereum/go-ethereum/rlp"
  43. "github.com/ethereum/go-ethereum/rpc"
  44. )
  45. const (
  46. // defaultTraceTimeout is the amount of time a single transaction can execute
  47. // by default before being forcefully aborted.
  48. defaultTraceTimeout = 5 * time.Second
  49. // defaultTraceReexec is the number of blocks the tracer is willing to go back
  50. // and reexecute to produce missing historical state necessary to run a specific
  51. // trace.
  52. defaultTraceReexec = uint64(128)
  53. // defaultTracechainMemLimit is the size of the triedb, at which traceChain
  54. // switches over and tries to use a disk-backed database instead of building
  55. // on top of memory.
  56. // For non-archive nodes, this limit _will_ be overblown, as disk-backed tries
  57. // will only be found every ~15K blocks or so.
  58. defaultTracechainMemLimit = common.StorageSize(500 * 1024 * 1024)
  59. )
  60. // Backend interface provides the common API services (that are provided by
  61. // both full and light clients) with access to necessary functions.
  62. type Backend interface {
  63. HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error)
  64. HeaderByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Header, error)
  65. BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
  66. BlockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error)
  67. GetTransaction(ctx context.Context, txHash common.Hash) (*types.Transaction, common.Hash, uint64, uint64, error)
  68. RPCGasCap() uint64
  69. ChainConfig() *params.ChainConfig
  70. Engine() consensus.Engine
  71. ChainDb() ethdb.Database
  72. // StateAtBlock returns the state corresponding to the stateroot of the block.
  73. // N.B: For executing transactions on block N, the required stateRoot is block N-1,
  74. // so this method should be called with the parent.
  75. StateAtBlock(ctx context.Context, block *types.Block, reexec uint64, base *state.StateDB, checkLive, preferDisk bool) (*state.StateDB, error)
  76. StateAtTransaction(ctx context.Context, block *types.Block, txIndex int, reexec uint64) (core.Message, vm.BlockContext, *state.StateDB, error)
  77. }
  78. // API is the collection of tracing APIs exposed over the private debugging endpoint.
  79. type API struct {
  80. backend Backend
  81. }
  82. // NewAPI creates a new API definition for the tracing methods of the Ethereum service.
  83. func NewAPI(backend Backend) *API {
  84. return &API{backend: backend}
  85. }
  86. type chainContext struct {
  87. api *API
  88. ctx context.Context
  89. }
  90. func (context *chainContext) Engine() consensus.Engine {
  91. return context.api.backend.Engine()
  92. }
  93. func (context *chainContext) GetHeader(hash common.Hash, number uint64) *types.Header {
  94. header, err := context.api.backend.HeaderByNumber(context.ctx, rpc.BlockNumber(number))
  95. if err != nil {
  96. return nil
  97. }
  98. if header.Hash() == hash {
  99. return header
  100. }
  101. header, err = context.api.backend.HeaderByHash(context.ctx, hash)
  102. if err != nil {
  103. return nil
  104. }
  105. return header
  106. }
  107. // chainContext construts the context reader which is used by the evm for reading
  108. // the necessary chain context.
  109. func (api *API) chainContext(ctx context.Context) core.ChainContext {
  110. return &chainContext{api: api, ctx: ctx}
  111. }
  112. // blockByNumber is the wrapper of the chain access function offered by the backend.
  113. // It will return an error if the block is not found.
  114. func (api *API) blockByNumber(ctx context.Context, number rpc.BlockNumber) (*types.Block, error) {
  115. block, err := api.backend.BlockByNumber(ctx, number)
  116. if err != nil {
  117. return nil, err
  118. }
  119. if block == nil {
  120. return nil, fmt.Errorf("block #%d not found", number)
  121. }
  122. return block, nil
  123. }
  124. // blockByHash is the wrapper of the chain access function offered by the backend.
  125. // It will return an error if the block is not found.
  126. func (api *API) blockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) {
  127. block, err := api.backend.BlockByHash(ctx, hash)
  128. if err != nil {
  129. return nil, err
  130. }
  131. if block == nil {
  132. return nil, fmt.Errorf("block %s not found", hash.Hex())
  133. }
  134. return block, nil
  135. }
  136. // blockByNumberAndHash is the wrapper of the chain access function offered by
  137. // the backend. It will return an error if the block is not found.
  138. //
  139. // Note this function is friendly for the light client which can only retrieve the
  140. // historical(before the CHT) header/block by number.
  141. func (api *API) blockByNumberAndHash(ctx context.Context, number rpc.BlockNumber, hash common.Hash) (*types.Block, error) {
  142. block, err := api.blockByNumber(ctx, number)
  143. if err != nil {
  144. return nil, err
  145. }
  146. if block.Hash() == hash {
  147. return block, nil
  148. }
  149. return api.blockByHash(ctx, hash)
  150. }
  151. // TraceConfig holds extra parameters to trace functions.
  152. type TraceConfig struct {
  153. *vm.LogConfig
  154. Tracer *string
  155. Timeout *string
  156. Reexec *uint64
  157. }
  158. // TraceCallConfig is the config for traceCall API. It holds one more
  159. // field to override the state for tracing.
  160. type TraceCallConfig struct {
  161. *vm.LogConfig
  162. Tracer *string
  163. Timeout *string
  164. Reexec *uint64
  165. StateOverrides *ethapi.StateOverride
  166. }
  167. // StdTraceConfig holds extra parameters to standard-json trace functions.
  168. type StdTraceConfig struct {
  169. vm.LogConfig
  170. Reexec *uint64
  171. TxHash common.Hash
  172. }
  173. // txTraceResult is the result of a single transaction trace.
  174. type txTraceResult struct {
  175. Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer
  176. Error string `json:"error,omitempty"` // Trace failure produced by the tracer
  177. }
  178. // blockTraceTask represents a single block trace task when an entire chain is
  179. // being traced.
  180. type blockTraceTask struct {
  181. statedb *state.StateDB // Intermediate state prepped for tracing
  182. block *types.Block // Block to trace the transactions from
  183. rootref common.Hash // Trie root reference held for this task
  184. results []*txTraceResult // Trace results procudes by the task
  185. }
  186. // blockTraceResult represets the results of tracing a single block when an entire
  187. // chain is being traced.
  188. type blockTraceResult struct {
  189. Block hexutil.Uint64 `json:"block"` // Block number corresponding to this trace
  190. Hash common.Hash `json:"hash"` // Block hash corresponding to this trace
  191. Traces []*txTraceResult `json:"traces"` // Trace results produced by the task
  192. }
  193. // txTraceTask represents a single transaction trace task when an entire block
  194. // is being traced.
  195. type txTraceTask struct {
  196. statedb *state.StateDB // Intermediate state prepped for tracing
  197. index int // Transaction offset in the block
  198. }
  199. // TraceChain returns the structured logs created during the execution of EVM
  200. // between two blocks (excluding start) and returns them as a JSON object.
  201. 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
  202. from, err := api.blockByNumber(ctx, start)
  203. if err != nil {
  204. return nil, err
  205. }
  206. to, err := api.blockByNumber(ctx, end)
  207. if err != nil {
  208. return nil, err
  209. }
  210. if from.Number().Cmp(to.Number()) >= 0 {
  211. return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start)
  212. }
  213. return api.traceChain(ctx, from, to, config)
  214. }
  215. // traceChain configures a new tracer according to the provided configuration, and
  216. // executes all the transactions contained within. The return value will be one item
  217. // per transaction, dependent on the requested tracer.
  218. func (api *API) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) {
  219. // Tracing a chain is a **long** operation, only do with subscriptions
  220. notifier, supported := rpc.NotifierFromContext(ctx)
  221. if !supported {
  222. return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
  223. }
  224. sub := notifier.CreateSubscription()
  225. // Prepare all the states for tracing. Note this procedure can take very
  226. // long time. Timeout mechanism is necessary.
  227. reexec := defaultTraceReexec
  228. if config != nil && config.Reexec != nil {
  229. reexec = *config.Reexec
  230. }
  231. blocks := int(end.NumberU64() - start.NumberU64())
  232. threads := runtime.NumCPU()
  233. if threads > blocks {
  234. threads = blocks
  235. }
  236. var (
  237. pend = new(sync.WaitGroup)
  238. tasks = make(chan *blockTraceTask, threads)
  239. results = make(chan *blockTraceTask, threads)
  240. localctx = context.Background()
  241. )
  242. for th := 0; th < threads; th++ {
  243. pend.Add(1)
  244. gopool.Submit(func() {
  245. defer pend.Done()
  246. // Fetch and execute the next block trace tasks
  247. for task := range tasks {
  248. signer := types.MakeSigner(api.backend.ChainConfig(), task.block.Number())
  249. blockCtx := core.NewEVMBlockContext(task.block.Header(), api.chainContext(localctx), nil)
  250. // Trace all the transactions contained within
  251. for i, tx := range task.block.Transactions() {
  252. msg, _ := tx.AsMessage(signer)
  253. txctx := &Context{
  254. BlockHash: task.block.Hash(),
  255. TxIndex: i,
  256. TxHash: tx.Hash(),
  257. }
  258. res, err := api.traceTx(localctx, msg, txctx, blockCtx, task.statedb, config)
  259. if err != nil {
  260. task.results[i] = &txTraceResult{Error: err.Error()}
  261. log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err)
  262. break
  263. }
  264. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  265. task.statedb.Finalise(api.backend.ChainConfig().IsEIP158(task.block.Number()))
  266. task.results[i] = &txTraceResult{Result: res}
  267. }
  268. // Stream the result back to the user or abort on teardown
  269. select {
  270. case results <- task:
  271. case <-notifier.Closed():
  272. return
  273. }
  274. }
  275. })
  276. }
  277. // Start a goroutine to feed all the blocks into the tracers
  278. var (
  279. begin = time.Now()
  280. derefTodo []common.Hash // list of hashes to dereference from the db
  281. derefsMu sync.Mutex // mutex for the derefs
  282. )
  283. gopool.Submit(func() {
  284. var (
  285. logged time.Time
  286. number uint64
  287. traced uint64
  288. failed error
  289. parent common.Hash
  290. statedb *state.StateDB
  291. )
  292. // Ensure everything is properly cleaned up on any exit path
  293. defer func() {
  294. close(tasks)
  295. pend.Wait()
  296. switch {
  297. case failed != nil:
  298. log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed)
  299. case number < end.NumberU64():
  300. log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin))
  301. default:
  302. log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin))
  303. }
  304. close(results)
  305. }()
  306. var preferDisk bool
  307. // Feed all the blocks both into the tracer, as well as fast process concurrently
  308. for number = start.NumberU64(); number < end.NumberU64(); number++ {
  309. // Stop tracing if interruption was requested
  310. select {
  311. case <-notifier.Closed():
  312. return
  313. default:
  314. }
  315. // clean out any derefs
  316. derefsMu.Lock()
  317. for _, h := range derefTodo {
  318. statedb.Database().TrieDB().Dereference(h)
  319. }
  320. derefTodo = derefTodo[:0]
  321. derefsMu.Unlock()
  322. // Print progress logs if long enough time elapsed
  323. if time.Since(logged) > 8*time.Second {
  324. logged = time.Now()
  325. log.Info("Tracing chain segment", "start", start.NumberU64(), "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin))
  326. }
  327. // Retrieve the parent state to trace on top
  328. block, err := api.blockByNumber(localctx, rpc.BlockNumber(number))
  329. if err != nil {
  330. failed = err
  331. break
  332. }
  333. // Prepare the statedb for tracing. Don't use the live database for
  334. // tracing to avoid persisting state junks into the database.
  335. statedb, err = api.backend.StateAtBlock(localctx, block, reexec, statedb, false, preferDisk)
  336. if err != nil {
  337. failed = err
  338. break
  339. }
  340. if trieDb := statedb.Database().TrieDB(); trieDb != nil {
  341. // Hold the reference for tracer, will be released at the final stage
  342. trieDb.Reference(block.Root(), common.Hash{})
  343. // Release the parent state because it's already held by the tracer
  344. if parent != (common.Hash{}) {
  345. trieDb.Dereference(parent)
  346. }
  347. // Prefer disk if the trie db memory grows too much
  348. s1, s2 := trieDb.Size()
  349. if !preferDisk && (s1+s2) > defaultTracechainMemLimit {
  350. log.Info("Switching to prefer-disk mode for tracing", "size", s1+s2)
  351. preferDisk = true
  352. }
  353. }
  354. parent = block.Root()
  355. next, err := api.blockByNumber(localctx, rpc.BlockNumber(number+1))
  356. if err != nil {
  357. failed = err
  358. break
  359. }
  360. // Send the block over to the concurrent tracers (if not in the fast-forward phase)
  361. txs := next.Transactions()
  362. select {
  363. case tasks <- &blockTraceTask{statedb: statedb.Copy(), block: next, rootref: block.Root(), results: make([]*txTraceResult, len(txs))}:
  364. case <-notifier.Closed():
  365. return
  366. }
  367. traced += uint64(len(txs))
  368. }
  369. })
  370. // Keep reading the trace results and stream the to the user
  371. gopool.Submit(func() {
  372. var (
  373. done = make(map[uint64]*blockTraceResult)
  374. next = start.NumberU64() + 1
  375. )
  376. for res := range results {
  377. // Queue up next received result
  378. result := &blockTraceResult{
  379. Block: hexutil.Uint64(res.block.NumberU64()),
  380. Hash: res.block.Hash(),
  381. Traces: res.results,
  382. }
  383. // Schedule any parent tries held in memory by this task for dereferencing
  384. done[uint64(result.Block)] = result
  385. derefsMu.Lock()
  386. derefTodo = append(derefTodo, res.rootref)
  387. derefsMu.Unlock()
  388. // Stream completed traces to the user, aborting on the first error
  389. for result, ok := done[next]; ok; result, ok = done[next] {
  390. if len(result.Traces) > 0 || next == end.NumberU64() {
  391. notifier.Notify(sub.ID, result)
  392. }
  393. delete(done, next)
  394. next++
  395. }
  396. }
  397. })
  398. return sub, nil
  399. }
  400. // TraceBlockByNumber returns the structured logs created during the execution of
  401. // EVM and returns them as a JSON object.
  402. func (api *API) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) {
  403. block, err := api.blockByNumber(ctx, number)
  404. if err != nil {
  405. return nil, err
  406. }
  407. return api.traceBlock(ctx, block, config)
  408. }
  409. // TraceBlockByHash returns the structured logs created during the execution of
  410. // EVM and returns them as a JSON object.
  411. func (api *API) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  412. block, err := api.blockByHash(ctx, hash)
  413. if err != nil {
  414. return nil, err
  415. }
  416. return api.traceBlock(ctx, block, config)
  417. }
  418. // TraceBlock returns the structured logs created during the execution of EVM
  419. // and returns them as a JSON object.
  420. func (api *API) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) {
  421. block := new(types.Block)
  422. if err := rlp.Decode(bytes.NewReader(blob), block); err != nil {
  423. return nil, fmt.Errorf("could not decode block: %v", err)
  424. }
  425. return api.traceBlock(ctx, block, config)
  426. }
  427. // TraceBlockFromFile returns the structured logs created during the execution of
  428. // EVM and returns them as a JSON object.
  429. func (api *API) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) {
  430. blob, err := ioutil.ReadFile(file)
  431. if err != nil {
  432. return nil, fmt.Errorf("could not read file: %v", err)
  433. }
  434. return api.TraceBlock(ctx, blob, config)
  435. }
  436. // TraceBadBlock returns the structured logs created during the execution of
  437. // EVM against a block pulled from the pool of bad ones and returns them as a JSON
  438. // object.
  439. func (api *API) TraceBadBlock(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) {
  440. block := rawdb.ReadBadBlock(api.backend.ChainDb(), hash)
  441. if block == nil {
  442. return nil, fmt.Errorf("bad block %#x not found", hash)
  443. }
  444. return api.traceBlock(ctx, block, config)
  445. }
  446. // StandardTraceBlockToFile dumps the structured logs created during the
  447. // execution of EVM to the local file system and returns a list of files
  448. // to the caller.
  449. func (api *API) StandardTraceBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  450. block, err := api.blockByHash(ctx, hash)
  451. if err != nil {
  452. return nil, err
  453. }
  454. return api.standardTraceBlockToFile(ctx, block, config)
  455. }
  456. // IntermediateRoots executes a block (bad- or canon- or side-), and returns a list
  457. // of intermediate roots: the stateroot after each transaction.
  458. func (api *API) IntermediateRoots(ctx context.Context, hash common.Hash, config *TraceConfig) ([]common.Hash, error) {
  459. block, _ := api.blockByHash(ctx, hash)
  460. if block == nil {
  461. // Check in the bad blocks
  462. block = rawdb.ReadBadBlock(api.backend.ChainDb(), hash)
  463. }
  464. if block == nil {
  465. return nil, fmt.Errorf("block %#x not found", hash)
  466. }
  467. if block.NumberU64() == 0 {
  468. return nil, errors.New("genesis is not traceable")
  469. }
  470. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  471. if err != nil {
  472. return nil, err
  473. }
  474. reexec := defaultTraceReexec
  475. if config != nil && config.Reexec != nil {
  476. reexec = *config.Reexec
  477. }
  478. statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true, false)
  479. if err != nil {
  480. return nil, err
  481. }
  482. var (
  483. roots []common.Hash
  484. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  485. chainConfig = api.backend.ChainConfig()
  486. vmctx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  487. deleteEmptyObjects = chainConfig.IsEIP158(block.Number())
  488. )
  489. for i, tx := range block.Transactions() {
  490. var (
  491. msg, _ = tx.AsMessage(signer)
  492. txContext = core.NewEVMTxContext(msg)
  493. vmenv = vm.NewEVM(vmctx, txContext, statedb, chainConfig, vm.Config{})
  494. )
  495. if posa, ok := api.backend.Engine().(consensus.PoSA); ok {
  496. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  497. balance := statedb.GetBalance(consensus.SystemAddress)
  498. if balance.Cmp(common.Big0) > 0 {
  499. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  500. statedb.AddBalance(vmctx.Coinbase, balance)
  501. }
  502. }
  503. }
  504. statedb.Prepare(tx.Hash(), block.Hash(), i)
  505. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  506. log.Warn("Tracing intermediate roots did not complete", "txindex", i, "txhash", tx.Hash(), "err", err)
  507. // We intentionally don't return the error here: if we do, then the RPC server will not
  508. // return the roots. Most likely, the caller already knows that a certain transaction fails to
  509. // be included, but still want the intermediate roots that led to that point.
  510. // It may happen the tx_N causes an erroneous state, which in turn causes tx_N+M to not be
  511. // executable.
  512. // N.B: This should never happen while tracing canon blocks, only when tracing bad blocks.
  513. return roots, nil
  514. }
  515. // calling IntermediateRoot will internally call Finalize on the state
  516. // so any modifications are written to the trie
  517. root := statedb.IntermediateRoot(deleteEmptyObjects)
  518. roots = append(roots, root)
  519. }
  520. return roots, nil
  521. }
  522. // StandardTraceBadBlockToFile dumps the structured logs created during the
  523. // execution of EVM against a block pulled from the pool of bad ones to the
  524. // local file system and returns a list of files to the caller.
  525. func (api *API) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  526. block := rawdb.ReadBadBlock(api.backend.ChainDb(), hash)
  527. if block == nil {
  528. return nil, fmt.Errorf("bad block %#x not found", hash)
  529. }
  530. return api.standardTraceBlockToFile(ctx, block, config)
  531. }
  532. // traceBlock configures a new tracer according to the provided configuration, and
  533. // executes all the transactions contained within. The return value will be one item
  534. // per transaction, dependent on the requestd tracer.
  535. func (api *API) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
  536. if block.NumberU64() == 0 {
  537. return nil, errors.New("genesis is not traceable")
  538. }
  539. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  540. if err != nil {
  541. return nil, err
  542. }
  543. reexec := defaultTraceReexec
  544. if config != nil && config.Reexec != nil {
  545. reexec = *config.Reexec
  546. }
  547. statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true, false)
  548. if err != nil {
  549. return nil, err
  550. }
  551. // Execute all the transaction contained within the block concurrently
  552. var (
  553. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  554. txs = block.Transactions()
  555. results = make([]*txTraceResult, len(txs))
  556. pend = new(sync.WaitGroup)
  557. jobs = make(chan *txTraceTask, len(txs))
  558. )
  559. threads := runtime.NumCPU()
  560. if threads > len(txs) {
  561. threads = len(txs)
  562. }
  563. blockCtx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  564. blockHash := block.Hash()
  565. for th := 0; th < threads; th++ {
  566. blockCtx := blockCtx
  567. pend.Add(1)
  568. gopool.Submit(func() {
  569. defer pend.Done()
  570. // Fetch and execute the next transaction trace tasks
  571. for task := range jobs {
  572. msg, _ := txs[task.index].AsMessage(signer)
  573. txctx := &Context{
  574. BlockHash: blockHash,
  575. TxIndex: task.index,
  576. TxHash: txs[task.index].Hash(),
  577. }
  578. res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
  579. if err != nil {
  580. results[task.index] = &txTraceResult{Error: err.Error()}
  581. continue
  582. }
  583. results[task.index] = &txTraceResult{Result: res}
  584. }
  585. })
  586. }
  587. // Feed the transactions into the tracers and return
  588. var failed error
  589. blockCtx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  590. for i, tx := range txs {
  591. // Send the trace task over for execution
  592. jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  593. // Generate the next state snapshot fast without tracing
  594. msg, _ := tx.AsMessage(signer)
  595. if posa, ok := api.backend.Engine().(consensus.PoSA); ok {
  596. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  597. balance := statedb.GetBalance(consensus.SystemAddress)
  598. if balance.Cmp(common.Big0) > 0 {
  599. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  600. statedb.AddBalance(block.Header().Coinbase, balance)
  601. }
  602. }
  603. }
  604. statedb.Prepare(tx.Hash(), block.Hash(), i)
  605. vmenv := vm.NewEVM(blockCtx, core.NewEVMTxContext(msg), statedb, api.backend.ChainConfig(), vm.Config{})
  606. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  607. failed = err
  608. break
  609. }
  610. // Finalize the state so any modifications are written to the trie
  611. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  612. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  613. }
  614. close(jobs)
  615. pend.Wait()
  616. // If execution failed in between, abort
  617. if failed != nil {
  618. return nil, failed
  619. }
  620. return results, nil
  621. }
  622. // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
  623. // and traces either a full block or an individual transaction. The return value will
  624. // be one filename per transaction traced.
  625. func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
  626. // If we're tracing a single transaction, make sure it's present
  627. if config != nil && config.TxHash != (common.Hash{}) {
  628. if !containsTx(block, config.TxHash) {
  629. return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
  630. }
  631. }
  632. if block.NumberU64() == 0 {
  633. return nil, errors.New("genesis is not traceable")
  634. }
  635. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  636. if err != nil {
  637. return nil, err
  638. }
  639. reexec := defaultTraceReexec
  640. if config != nil && config.Reexec != nil {
  641. reexec = *config.Reexec
  642. }
  643. statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true, false)
  644. if err != nil {
  645. return nil, err
  646. }
  647. // Retrieve the tracing configurations, or use default values
  648. var (
  649. logConfig vm.LogConfig
  650. txHash common.Hash
  651. )
  652. if config != nil {
  653. logConfig = config.LogConfig
  654. txHash = config.TxHash
  655. }
  656. logConfig.Debug = true
  657. // Execute transaction, either tracing all or just the requested one
  658. var (
  659. dumps []string
  660. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  661. chainConfig = api.backend.ChainConfig()
  662. vmctx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  663. canon = true
  664. )
  665. // Check if there are any overrides: the caller may wish to enable a future
  666. // fork when executing this block. Note, such overrides are only applicable to the
  667. // actual specified block, not any preceding blocks that we have to go through
  668. // in order to obtain the state.
  669. // Therefore, it's perfectly valid to specify `"futureForkBlock": 0`, to enable `futureFork`
  670. if config != nil && config.Overrides != nil {
  671. // Copy the config, to not screw up the main config
  672. // Note: the Clique-part is _not_ deep copied
  673. chainConfigCopy := new(params.ChainConfig)
  674. *chainConfigCopy = *chainConfig
  675. chainConfig = chainConfigCopy
  676. if berlin := config.LogConfig.Overrides.BerlinBlock; berlin != nil {
  677. chainConfig.BerlinBlock = berlin
  678. canon = false
  679. }
  680. }
  681. for i, tx := range block.Transactions() {
  682. // Prepare the trasaction for un-traced execution
  683. var (
  684. msg, _ = tx.AsMessage(signer)
  685. txContext = core.NewEVMTxContext(msg)
  686. vmConf vm.Config
  687. dump *os.File
  688. writer *bufio.Writer
  689. err error
  690. )
  691. // If the transaction needs tracing, swap out the configs
  692. if tx.Hash() == txHash || txHash == (common.Hash{}) {
  693. // Generate a unique temporary file to dump it into
  694. prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
  695. if !canon {
  696. prefix = fmt.Sprintf("%valt-", prefix)
  697. }
  698. dump, err = ioutil.TempFile(os.TempDir(), prefix)
  699. if err != nil {
  700. return nil, err
  701. }
  702. dumps = append(dumps, dump.Name())
  703. // Swap out the noop logger to the standard tracer
  704. writer = bufio.NewWriter(dump)
  705. vmConf = vm.Config{
  706. Debug: true,
  707. Tracer: vm.NewJSONLogger(&logConfig, writer),
  708. EnablePreimageRecording: true,
  709. }
  710. }
  711. // Execute the transaction and flush any traces to disk
  712. vmenv := vm.NewEVM(vmctx, txContext, statedb, chainConfig, vmConf)
  713. if posa, ok := api.backend.Engine().(consensus.PoSA); ok {
  714. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  715. balance := statedb.GetBalance(consensus.SystemAddress)
  716. if balance.Cmp(common.Big0) > 0 {
  717. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  718. statedb.AddBalance(vmctx.Coinbase, balance)
  719. }
  720. }
  721. }
  722. statedb.Prepare(tx.Hash(), block.Hash(), i)
  723. _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  724. if writer != nil {
  725. writer.Flush()
  726. }
  727. if dump != nil {
  728. dump.Close()
  729. log.Info("Wrote standard trace", "file", dump.Name())
  730. }
  731. if err != nil {
  732. return dumps, err
  733. }
  734. // Finalize the state so any modifications are written to the trie
  735. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  736. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  737. // If we've traced the transaction we were looking for, abort
  738. if tx.Hash() == txHash {
  739. break
  740. }
  741. }
  742. return dumps, nil
  743. }
  744. // containsTx reports whether the transaction with a certain hash
  745. // is contained within the specified block.
  746. func containsTx(block *types.Block, hash common.Hash) bool {
  747. for _, tx := range block.Transactions() {
  748. if tx.Hash() == hash {
  749. return true
  750. }
  751. }
  752. return false
  753. }
  754. // TraceTransaction returns the structured logs created during the execution of EVM
  755. // and returns them as a JSON object.
  756. func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  757. _, blockHash, blockNumber, index, err := api.backend.GetTransaction(ctx, hash)
  758. if err != nil {
  759. return nil, err
  760. }
  761. // It shouldn't happen in practice.
  762. if blockNumber == 0 {
  763. return nil, errors.New("genesis is not traceable")
  764. }
  765. reexec := defaultTraceReexec
  766. if config != nil && config.Reexec != nil {
  767. reexec = *config.Reexec
  768. }
  769. block, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(blockNumber), blockHash)
  770. if err != nil {
  771. return nil, err
  772. }
  773. msg, vmctx, statedb, err := api.backend.StateAtTransaction(ctx, block, int(index), reexec)
  774. if err != nil {
  775. return nil, err
  776. }
  777. txctx := &Context{
  778. BlockHash: blockHash,
  779. TxIndex: int(index),
  780. TxHash: hash,
  781. }
  782. return api.traceTx(ctx, msg, txctx, vmctx, statedb, config)
  783. }
  784. // TraceCall lets you trace a given eth_call. It collects the structured logs
  785. // created during the execution of EVM if the given transaction was added on
  786. // top of the provided block and returns them as a JSON object.
  787. // You can provide -2 as a block number to trace on top of the pending block.
  788. func (api *API) TraceCall(ctx context.Context, args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) {
  789. // Try to retrieve the specified block
  790. var (
  791. err error
  792. block *types.Block
  793. )
  794. if hash, ok := blockNrOrHash.Hash(); ok {
  795. block, err = api.blockByHash(ctx, hash)
  796. } else if number, ok := blockNrOrHash.Number(); ok {
  797. block, err = api.blockByNumber(ctx, number)
  798. } else {
  799. return nil, errors.New("invalid arguments; neither block nor hash specified")
  800. }
  801. if err != nil {
  802. return nil, err
  803. }
  804. // try to recompute the state
  805. reexec := defaultTraceReexec
  806. if config != nil && config.Reexec != nil {
  807. reexec = *config.Reexec
  808. }
  809. statedb, err := api.backend.StateAtBlock(ctx, block, reexec, nil, true, false)
  810. if err != nil {
  811. return nil, err
  812. }
  813. // Apply the customized state rules if required.
  814. if config != nil {
  815. if err := config.StateOverrides.Apply(statedb); err != nil {
  816. return nil, err
  817. }
  818. }
  819. // Execute the trace
  820. msg := args.ToMessage(api.backend.RPCGasCap())
  821. vmctx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  822. var traceConfig *TraceConfig
  823. if config != nil {
  824. traceConfig = &TraceConfig{
  825. LogConfig: config.LogConfig,
  826. Tracer: config.Tracer,
  827. Timeout: config.Timeout,
  828. Reexec: config.Reexec,
  829. }
  830. }
  831. return api.traceTx(ctx, msg, new(Context), vmctx, statedb, traceConfig)
  832. }
  833. // traceTx configures a new tracer according to the provided configuration, and
  834. // executes the given message in the provided environment. The return value will
  835. // be tracer dependent.
  836. func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  837. // Assemble the structured logger or the JavaScript tracer
  838. var (
  839. tracer vm.EVMLogger
  840. err error
  841. txContext = core.NewEVMTxContext(message)
  842. )
  843. switch {
  844. case config == nil:
  845. tracer = vm.NewStructLogger(nil)
  846. case config.Tracer != nil:
  847. // Define a meaningful timeout of a single transaction trace
  848. timeout := defaultTraceTimeout
  849. if config.Timeout != nil {
  850. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  851. return nil, err
  852. }
  853. }
  854. if t, err := New(*config.Tracer, txctx); err != nil {
  855. return nil, err
  856. } else {
  857. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  858. go func() {
  859. <-deadlineCtx.Done()
  860. if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
  861. t.Stop(errors.New("execution timeout"))
  862. }
  863. }()
  864. defer cancel()
  865. tracer = t
  866. }
  867. default:
  868. tracer = vm.NewStructLogger(config.LogConfig)
  869. }
  870. // Run the transaction with tracing enabled.
  871. vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer})
  872. if posa, ok := api.backend.Engine().(consensus.PoSA); ok && message.From() == vmctx.Coinbase &&
  873. posa.IsSystemContract(message.To()) && message.GasPrice().Cmp(big.NewInt(0)) == 0 {
  874. balance := statedb.GetBalance(consensus.SystemAddress)
  875. if balance.Cmp(common.Big0) > 0 {
  876. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  877. statedb.AddBalance(vmctx.Coinbase, balance)
  878. }
  879. }
  880. // Call Prepare to clear out the statedb access list
  881. statedb.Prepare(txctx.TxHash, txctx.BlockHash, txctx.TxIndex)
  882. result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  883. if err != nil {
  884. return nil, fmt.Errorf("tracing failed: %w", err)
  885. }
  886. // Depending on the tracer type, format and return the output.
  887. switch tracer := tracer.(type) {
  888. case *vm.StructLogger:
  889. // If the result contains a revert reason, return it.
  890. returnVal := fmt.Sprintf("%x", result.Return())
  891. if len(result.Revert()) > 0 {
  892. returnVal = fmt.Sprintf("%x", result.Revert())
  893. }
  894. return &ethapi.ExecutionResult{
  895. Gas: result.UsedGas,
  896. Failed: result.Failed(),
  897. ReturnValue: returnVal,
  898. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  899. }, nil
  900. case Tracer:
  901. return tracer.GetResult()
  902. default:
  903. panic(fmt.Sprintf("bad tracer type %T", tracer))
  904. }
  905. }
  906. // APIs return the collection of RPC services the tracer package offers.
  907. func APIs(backend Backend) []rpc.API {
  908. // Append all the local APIs and return
  909. return []rpc.API{
  910. {
  911. Namespace: "debug",
  912. Version: "1.0",
  913. Service: NewAPI(backend),
  914. Public: false,
  915. },
  916. }
  917. }