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