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