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