api.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. roots = append(roots, statedb.IntermediateRoot(deleteEmptyObjects))
  518. }
  519. return roots, nil
  520. }
  521. // StandardTraceBadBlockToFile dumps the structured logs created during the
  522. // execution of EVM against a block pulled from the pool of bad ones to the
  523. // local file system and returns a list of files to the caller.
  524. func (api *API) StandardTraceBadBlockToFile(ctx context.Context, hash common.Hash, config *StdTraceConfig) ([]string, error) {
  525. block := rawdb.ReadBadBlock(api.backend.ChainDb(), hash)
  526. if block == nil {
  527. return nil, fmt.Errorf("bad block %#x not found", hash)
  528. }
  529. return api.standardTraceBlockToFile(ctx, block, config)
  530. }
  531. // traceBlock configures a new tracer according to the provided configuration, and
  532. // executes all the transactions contained within. The return value will be one item
  533. // per transaction, dependent on the requestd tracer.
  534. func (api *API) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) {
  535. if block.NumberU64() == 0 {
  536. return nil, errors.New("genesis is not traceable")
  537. }
  538. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  539. if err != nil {
  540. return nil, err
  541. }
  542. reexec := defaultTraceReexec
  543. if config != nil && config.Reexec != nil {
  544. reexec = *config.Reexec
  545. }
  546. statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true, false)
  547. if err != nil {
  548. return nil, err
  549. }
  550. // Execute all the transaction contained within the block concurrently
  551. var (
  552. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  553. txs = block.Transactions()
  554. results = make([]*txTraceResult, len(txs))
  555. pend = new(sync.WaitGroup)
  556. jobs = make(chan *txTraceTask, len(txs))
  557. )
  558. threads := runtime.NumCPU()
  559. if threads > len(txs) {
  560. threads = len(txs)
  561. }
  562. blockCtx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  563. blockHash := block.Hash()
  564. for th := 0; th < threads; th++ {
  565. blockCtx := blockCtx
  566. pend.Add(1)
  567. gopool.Submit(func() {
  568. defer pend.Done()
  569. // Fetch and execute the next transaction trace tasks
  570. for task := range jobs {
  571. msg, _ := txs[task.index].AsMessage(signer)
  572. txctx := &Context{
  573. BlockHash: blockHash,
  574. TxIndex: task.index,
  575. TxHash: txs[task.index].Hash(),
  576. }
  577. res, err := api.traceTx(ctx, msg, txctx, blockCtx, task.statedb, config)
  578. if err != nil {
  579. results[task.index] = &txTraceResult{Error: err.Error()}
  580. continue
  581. }
  582. results[task.index] = &txTraceResult{Result: res}
  583. }
  584. })
  585. }
  586. // Feed the transactions into the tracers and return
  587. var failed error
  588. blockCtx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  589. for i, tx := range txs {
  590. // Send the trace task over for execution
  591. jobs <- &txTraceTask{statedb: statedb.Copy(), index: i}
  592. // Generate the next state snapshot fast without tracing
  593. msg, _ := tx.AsMessage(signer)
  594. if posa, ok := api.backend.Engine().(consensus.PoSA); ok {
  595. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  596. balance := statedb.GetBalance(consensus.SystemAddress)
  597. if balance.Cmp(common.Big0) > 0 {
  598. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  599. statedb.AddBalance(block.Header().Coinbase, balance)
  600. }
  601. }
  602. }
  603. statedb.Prepare(tx.Hash(), block.Hash(), i)
  604. vmenv := vm.NewEVM(blockCtx, core.NewEVMTxContext(msg), statedb, api.backend.ChainConfig(), vm.Config{})
  605. if _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil {
  606. failed = err
  607. break
  608. }
  609. // Finalize the state so any modifications are written to the trie
  610. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  611. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  612. }
  613. close(jobs)
  614. pend.Wait()
  615. // If execution failed in between, abort
  616. if failed != nil {
  617. return nil, failed
  618. }
  619. return results, nil
  620. }
  621. // standardTraceBlockToFile configures a new tracer which uses standard JSON output,
  622. // and traces either a full block or an individual transaction. The return value will
  623. // be one filename per transaction traced.
  624. func (api *API) standardTraceBlockToFile(ctx context.Context, block *types.Block, config *StdTraceConfig) ([]string, error) {
  625. // If we're tracing a single transaction, make sure it's present
  626. if config != nil && config.TxHash != (common.Hash{}) {
  627. if !containsTx(block, config.TxHash) {
  628. return nil, fmt.Errorf("transaction %#x not found in block", config.TxHash)
  629. }
  630. }
  631. if block.NumberU64() == 0 {
  632. return nil, errors.New("genesis is not traceable")
  633. }
  634. parent, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(block.NumberU64()-1), block.ParentHash())
  635. if err != nil {
  636. return nil, err
  637. }
  638. reexec := defaultTraceReexec
  639. if config != nil && config.Reexec != nil {
  640. reexec = *config.Reexec
  641. }
  642. statedb, err := api.backend.StateAtBlock(ctx, parent, reexec, nil, true, false)
  643. if err != nil {
  644. return nil, err
  645. }
  646. // Retrieve the tracing configurations, or use default values
  647. var (
  648. logConfig vm.LogConfig
  649. txHash common.Hash
  650. )
  651. if config != nil {
  652. logConfig = config.LogConfig
  653. txHash = config.TxHash
  654. }
  655. logConfig.Debug = true
  656. // Execute transaction, either tracing all or just the requested one
  657. var (
  658. dumps []string
  659. signer = types.MakeSigner(api.backend.ChainConfig(), block.Number())
  660. chainConfig = api.backend.ChainConfig()
  661. vmctx = core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  662. canon = true
  663. )
  664. // Check if there are any overrides: the caller may wish to enable a future
  665. // fork when executing this block. Note, such overrides are only applicable to the
  666. // actual specified block, not any preceding blocks that we have to go through
  667. // in order to obtain the state.
  668. // Therefore, it's perfectly valid to specify `"futureForkBlock": 0`, to enable `futureFork`
  669. if config != nil && config.Overrides != nil {
  670. // Copy the config, to not screw up the main config
  671. // Note: the Clique-part is _not_ deep copied
  672. chainConfigCopy := new(params.ChainConfig)
  673. *chainConfigCopy = *chainConfig
  674. chainConfig = chainConfigCopy
  675. if berlin := config.LogConfig.Overrides.BerlinBlock; berlin != nil {
  676. chainConfig.BerlinBlock = berlin
  677. canon = false
  678. }
  679. }
  680. for i, tx := range block.Transactions() {
  681. // Prepare the trasaction for un-traced execution
  682. var (
  683. msg, _ = tx.AsMessage(signer)
  684. txContext = core.NewEVMTxContext(msg)
  685. vmConf vm.Config
  686. dump *os.File
  687. writer *bufio.Writer
  688. err error
  689. )
  690. // If the transaction needs tracing, swap out the configs
  691. if tx.Hash() == txHash || txHash == (common.Hash{}) {
  692. // Generate a unique temporary file to dump it into
  693. prefix := fmt.Sprintf("block_%#x-%d-%#x-", block.Hash().Bytes()[:4], i, tx.Hash().Bytes()[:4])
  694. if !canon {
  695. prefix = fmt.Sprintf("%valt-", prefix)
  696. }
  697. dump, err = ioutil.TempFile(os.TempDir(), prefix)
  698. if err != nil {
  699. return nil, err
  700. }
  701. dumps = append(dumps, dump.Name())
  702. // Swap out the noop logger to the standard tracer
  703. writer = bufio.NewWriter(dump)
  704. vmConf = vm.Config{
  705. Debug: true,
  706. Tracer: vm.NewJSONLogger(&logConfig, writer),
  707. EnablePreimageRecording: true,
  708. }
  709. }
  710. // Execute the transaction and flush any traces to disk
  711. vmenv := vm.NewEVM(vmctx, txContext, statedb, chainConfig, vmConf)
  712. if posa, ok := api.backend.Engine().(consensus.PoSA); ok {
  713. if isSystem, _ := posa.IsSystemTransaction(tx, block.Header()); isSystem {
  714. balance := statedb.GetBalance(consensus.SystemAddress)
  715. if balance.Cmp(common.Big0) > 0 {
  716. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  717. statedb.AddBalance(vmctx.Coinbase, balance)
  718. }
  719. }
  720. }
  721. statedb.Prepare(tx.Hash(), block.Hash(), i)
  722. _, err = core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()))
  723. if writer != nil {
  724. writer.Flush()
  725. }
  726. if dump != nil {
  727. dump.Close()
  728. log.Info("Wrote standard trace", "file", dump.Name())
  729. }
  730. if err != nil {
  731. return dumps, err
  732. }
  733. // Finalize the state so any modifications are written to the trie
  734. // Only delete empty objects if EIP158/161 (a.k.a Spurious Dragon) is in effect
  735. statedb.Finalise(vmenv.ChainConfig().IsEIP158(block.Number()))
  736. // If we've traced the transaction we were looking for, abort
  737. if tx.Hash() == txHash {
  738. break
  739. }
  740. }
  741. return dumps, nil
  742. }
  743. // containsTx reports whether the transaction with a certain hash
  744. // is contained within the specified block.
  745. func containsTx(block *types.Block, hash common.Hash) bool {
  746. for _, tx := range block.Transactions() {
  747. if tx.Hash() == hash {
  748. return true
  749. }
  750. }
  751. return false
  752. }
  753. // TraceTransaction returns the structured logs created during the execution of EVM
  754. // and returns them as a JSON object.
  755. func (api *API) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) {
  756. _, blockHash, blockNumber, index, err := api.backend.GetTransaction(ctx, hash)
  757. if err != nil {
  758. return nil, err
  759. }
  760. // It shouldn't happen in practice.
  761. if blockNumber == 0 {
  762. return nil, errors.New("genesis is not traceable")
  763. }
  764. reexec := defaultTraceReexec
  765. if config != nil && config.Reexec != nil {
  766. reexec = *config.Reexec
  767. }
  768. block, err := api.blockByNumberAndHash(ctx, rpc.BlockNumber(blockNumber), blockHash)
  769. if err != nil {
  770. return nil, err
  771. }
  772. msg, vmctx, statedb, err := api.backend.StateAtTransaction(ctx, block, int(index), reexec)
  773. if err != nil {
  774. return nil, err
  775. }
  776. txctx := &Context{
  777. BlockHash: blockHash,
  778. TxIndex: int(index),
  779. TxHash: hash,
  780. }
  781. return api.traceTx(ctx, msg, txctx, vmctx, statedb, config)
  782. }
  783. // TraceCall lets you trace a given eth_call. It collects the structured logs
  784. // created during the execution of EVM if the given transaction was added on
  785. // top of the provided block and returns them as a JSON object.
  786. // You can provide -2 as a block number to trace on top of the pending block.
  787. func (api *API) TraceCall(ctx context.Context, args ethapi.CallArgs, blockNrOrHash rpc.BlockNumberOrHash, config *TraceCallConfig) (interface{}, error) {
  788. // Try to retrieve the specified block
  789. var (
  790. err error
  791. block *types.Block
  792. )
  793. if hash, ok := blockNrOrHash.Hash(); ok {
  794. block, err = api.blockByHash(ctx, hash)
  795. } else if number, ok := blockNrOrHash.Number(); ok {
  796. block, err = api.blockByNumber(ctx, number)
  797. } else {
  798. return nil, errors.New("invalid arguments; neither block nor hash specified")
  799. }
  800. if err != nil {
  801. return nil, err
  802. }
  803. // try to recompute the state
  804. reexec := defaultTraceReexec
  805. if config != nil && config.Reexec != nil {
  806. reexec = *config.Reexec
  807. }
  808. statedb, err := api.backend.StateAtBlock(ctx, block, reexec, nil, true, false)
  809. if err != nil {
  810. return nil, err
  811. }
  812. // Apply the customized state rules if required.
  813. if config != nil {
  814. if err := config.StateOverrides.Apply(statedb); err != nil {
  815. return nil, err
  816. }
  817. }
  818. // Execute the trace
  819. msg := args.ToMessage(api.backend.RPCGasCap())
  820. vmctx := core.NewEVMBlockContext(block.Header(), api.chainContext(ctx), nil)
  821. var traceConfig *TraceConfig
  822. if config != nil {
  823. traceConfig = &TraceConfig{
  824. LogConfig: config.LogConfig,
  825. Tracer: config.Tracer,
  826. Timeout: config.Timeout,
  827. Reexec: config.Reexec,
  828. }
  829. }
  830. return api.traceTx(ctx, msg, new(Context), vmctx, statedb, traceConfig)
  831. }
  832. // traceTx configures a new tracer according to the provided configuration, and
  833. // executes the given message in the provided environment. The return value will
  834. // be tracer dependent.
  835. func (api *API) traceTx(ctx context.Context, message core.Message, txctx *Context, vmctx vm.BlockContext, statedb *state.StateDB, config *TraceConfig) (interface{}, error) {
  836. // Assemble the structured logger or the JavaScript tracer
  837. var (
  838. tracer vm.EVMLogger
  839. err error
  840. txContext = core.NewEVMTxContext(message)
  841. )
  842. switch {
  843. case config == nil:
  844. tracer = vm.NewStructLogger(nil)
  845. case config.Tracer != nil:
  846. // Define a meaningful timeout of a single transaction trace
  847. timeout := defaultTraceTimeout
  848. if config.Timeout != nil {
  849. if timeout, err = time.ParseDuration(*config.Timeout); err != nil {
  850. return nil, err
  851. }
  852. }
  853. if t, err := New(*config.Tracer, txctx); err != nil {
  854. return nil, err
  855. } else {
  856. deadlineCtx, cancel := context.WithTimeout(ctx, timeout)
  857. go func() {
  858. <-deadlineCtx.Done()
  859. if errors.Is(deadlineCtx.Err(), context.DeadlineExceeded) {
  860. t.Stop(errors.New("execution timeout"))
  861. }
  862. }()
  863. defer cancel()
  864. tracer = t
  865. }
  866. default:
  867. tracer = vm.NewStructLogger(config.LogConfig)
  868. }
  869. // Run the transaction with tracing enabled.
  870. vmenv := vm.NewEVM(vmctx, txContext, statedb, api.backend.ChainConfig(), vm.Config{Debug: true, Tracer: tracer})
  871. if posa, ok := api.backend.Engine().(consensus.PoSA); ok && message.From() == vmctx.Coinbase &&
  872. posa.IsSystemContract(message.To()) && message.GasPrice().Cmp(big.NewInt(0)) == 0 {
  873. balance := statedb.GetBalance(consensus.SystemAddress)
  874. if balance.Cmp(common.Big0) > 0 {
  875. statedb.SetBalance(consensus.SystemAddress, big.NewInt(0))
  876. statedb.AddBalance(vmctx.Coinbase, balance)
  877. }
  878. }
  879. // Call Prepare to clear out the statedb access list
  880. statedb.Prepare(txctx.TxHash, txctx.BlockHash, txctx.TxIndex)
  881. result, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas()))
  882. if err != nil {
  883. return nil, fmt.Errorf("tracing failed: %w", err)
  884. }
  885. // Depending on the tracer type, format and return the output.
  886. switch tracer := tracer.(type) {
  887. case *vm.StructLogger:
  888. // If the result contains a revert reason, return it.
  889. returnVal := fmt.Sprintf("%x", result.Return())
  890. if len(result.Revert()) > 0 {
  891. returnVal = fmt.Sprintf("%x", result.Revert())
  892. }
  893. return &ethapi.ExecutionResult{
  894. Gas: result.UsedGas,
  895. Failed: result.Failed(),
  896. ReturnValue: returnVal,
  897. StructLogs: ethapi.FormatLogs(tracer.StructLogs()),
  898. }, nil
  899. case Tracer:
  900. return tracer.GetResult()
  901. default:
  902. panic(fmt.Sprintf("bad tracer type %T", tracer))
  903. }
  904. }
  905. // APIs return the collection of RPC services the tracer package offers.
  906. func APIs(backend Backend) []rpc.API {
  907. // Append all the local APIs and return
  908. return []rpc.API{
  909. {
  910. Namespace: "debug",
  911. Version: "1.0",
  912. Service: NewAPI(backend),
  913. Public: false,
  914. },
  915. }
  916. }