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