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