github.com/hyperion-hyn/go-ethereum@v2.4.0+incompatible/eth/api_tracer.go (about) 1 // Copyright 2017 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 eth 18 19 import ( 20 "bytes" 21 "context" 22 "errors" 23 "fmt" 24 "io/ioutil" 25 "runtime" 26 "sync" 27 "time" 28 29 "github.com/ethereum/go-ethereum/common" 30 "github.com/ethereum/go-ethereum/common/hexutil" 31 "github.com/ethereum/go-ethereum/core" 32 "github.com/ethereum/go-ethereum/core/rawdb" 33 "github.com/ethereum/go-ethereum/core/state" 34 "github.com/ethereum/go-ethereum/core/types" 35 "github.com/ethereum/go-ethereum/core/vm" 36 "github.com/ethereum/go-ethereum/eth/tracers" 37 "github.com/ethereum/go-ethereum/internal/ethapi" 38 "github.com/ethereum/go-ethereum/log" 39 "github.com/ethereum/go-ethereum/rlp" 40 "github.com/ethereum/go-ethereum/rpc" 41 "github.com/ethereum/go-ethereum/trie" 42 ) 43 44 const ( 45 // defaultTraceTimeout is the amount of time a single transaction can execute 46 // by default before being forcefully aborted. 47 defaultTraceTimeout = 5 * time.Second 48 49 // defaultTraceReexec is the number of blocks the tracer is willing to go back 50 // and reexecute to produce missing historical state necessary to run a specific 51 // trace. 52 defaultTraceReexec = uint64(128) 53 ) 54 55 // TraceConfig holds extra parameters to trace functions. 56 type TraceConfig struct { 57 *vm.LogConfig 58 Tracer *string 59 Timeout *string 60 Reexec *uint64 61 } 62 63 // txTraceResult is the result of a single transaction trace. 64 type txTraceResult struct { 65 Result interface{} `json:"result,omitempty"` // Trace results produced by the tracer 66 Error string `json:"error,omitempty"` // Trace failure produced by the tracer 67 } 68 69 // blockTraceTask represents a single block trace task when an entire chain is 70 // being traced. 71 type blockTraceTask struct { 72 statedb *state.StateDB // Intermediate state prepped for tracing 73 privateStateDb *state.StateDB // Quorum 74 block *types.Block // Block to trace the transactions from 75 rootref common.Hash // Trie root reference held for this task 76 results []*txTraceResult // Trace results procudes by the task 77 } 78 79 // blockTraceResult represets the results of tracing a single block when an entire 80 // chain is being traced. 81 type blockTraceResult struct { 82 Block hexutil.Uint64 `json:"block"` // Block number corresponding to this trace 83 Hash common.Hash `json:"hash"` // Block hash corresponding to this trace 84 Traces []*txTraceResult `json:"traces"` // Trace results produced by the task 85 } 86 87 // txTraceTask represents a single transaction trace task when an entire block 88 // is being traced. 89 type txTraceTask struct { 90 statedb *state.StateDB // Intermediate state prepped for tracing 91 privateStateDb *state.StateDB 92 index int // Transaction offset in the block 93 } 94 95 // TraceChain returns the structured logs created during the execution of EVM 96 // between two blocks (excluding start) and returns them as a JSON object. 97 func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) { 98 // Fetch the block interval that we want to trace 99 var from, to *types.Block 100 101 switch start { 102 case rpc.PendingBlockNumber: 103 from = api.eth.miner.PendingBlock() 104 case rpc.LatestBlockNumber: 105 from = api.eth.blockchain.CurrentBlock() 106 default: 107 from = api.eth.blockchain.GetBlockByNumber(uint64(start)) 108 } 109 switch end { 110 case rpc.PendingBlockNumber: 111 to = api.eth.miner.PendingBlock() 112 case rpc.LatestBlockNumber: 113 to = api.eth.blockchain.CurrentBlock() 114 default: 115 to = api.eth.blockchain.GetBlockByNumber(uint64(end)) 116 } 117 // Trace the chain if we've found all our blocks 118 if from == nil { 119 return nil, fmt.Errorf("starting block #%d not found", start) 120 } 121 if to == nil { 122 return nil, fmt.Errorf("end block #%d not found", end) 123 } 124 if from.Number().Cmp(to.Number()) >= 0 { 125 return nil, fmt.Errorf("end block (#%d) needs to come after start block (#%d)", end, start) 126 } 127 return api.traceChain(ctx, from, to, config) 128 } 129 130 // traceChain configures a new tracer according to the provided configuration, and 131 // executes all the transactions contained within. The return value will be one item 132 // per transaction, dependent on the requested tracer. 133 func (api *PrivateDebugAPI) traceChain(ctx context.Context, start, end *types.Block, config *TraceConfig) (*rpc.Subscription, error) { 134 // Tracing a chain is a **long** operation, only do with subscriptions 135 notifier, supported := rpc.NotifierFromContext(ctx) 136 if !supported { 137 return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported 138 } 139 sub := notifier.CreateSubscription() 140 141 // Ensure we have a valid starting state before doing any work 142 origin := start.NumberU64() 143 database := state.NewDatabase(api.eth.ChainDb()) 144 145 if number := start.NumberU64(); number > 0 { 146 start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1) 147 if start == nil { 148 return nil, fmt.Errorf("parent block #%d not found", number-1) 149 } 150 } 151 statedb, privateStateDb, err := api.eth.blockchain.StateAt(start.Root()) 152 if err != nil { 153 // If the starting state is missing, allow some number of blocks to be reexecuted 154 reexec := defaultTraceReexec 155 if config != nil && config.Reexec != nil { 156 reexec = *config.Reexec 157 } 158 // Find the most recent block that has the state available 159 for i := uint64(0); i < reexec; i++ { 160 start = api.eth.blockchain.GetBlock(start.ParentHash(), start.NumberU64()-1) 161 if start == nil { 162 break 163 } 164 statedb, privateStateDb, err = api.eth.blockchain.StateAt(start.Root()) 165 if err == nil { 166 break 167 } 168 } 169 // If we still don't have the state available, bail out 170 if err != nil { 171 switch err.(type) { 172 case *trie.MissingNodeError: 173 return nil, errors.New("required historical state unavailable") 174 default: 175 return nil, err 176 } 177 } 178 } 179 // Execute all the transaction contained within the chain concurrently for each block 180 blocks := int(end.NumberU64() - origin) 181 182 threads := runtime.NumCPU() 183 if threads > blocks { 184 threads = blocks 185 } 186 var ( 187 pend = new(sync.WaitGroup) 188 tasks = make(chan *blockTraceTask, threads) 189 results = make(chan *blockTraceTask, threads) 190 ) 191 for th := 0; th < threads; th++ { 192 pend.Add(1) 193 go func() { 194 defer pend.Done() 195 196 // Fetch and execute the next block trace tasks 197 for task := range tasks { 198 signer := types.MakeSigner(api.config, task.block.Number()) 199 200 // Trace all the transactions contained within 201 for i, tx := range task.block.Transactions() { 202 msg, _ := tx.AsMessage(signer) 203 vmctx := core.NewEVMContext(msg, task.block.Header(), api.eth.blockchain, nil) 204 205 res, err := api.traceTx(ctx, msg, vmctx, task.statedb, task.privateStateDb, config) 206 if err != nil { 207 task.results[i] = &txTraceResult{Error: err.Error()} 208 log.Warn("Tracing failed", "hash", tx.Hash(), "block", task.block.NumberU64(), "err", err) 209 break 210 } 211 task.statedb.Finalise(true) 212 task.privateStateDb.Finalise(true) 213 task.results[i] = &txTraceResult{Result: res} 214 } 215 // Stream the result back to the user or abort on teardown 216 select { 217 case results <- task: 218 case <-notifier.Closed(): 219 return 220 } 221 } 222 }() 223 } 224 // Start a goroutine to feed all the blocks into the tracers 225 begin := time.Now() 226 227 go func() { 228 var ( 229 logged time.Time 230 number uint64 231 traced uint64 232 failed error 233 proot common.Hash 234 ) 235 // Ensure everything is properly cleaned up on any exit path 236 defer func() { 237 close(tasks) 238 pend.Wait() 239 240 switch { 241 case failed != nil: 242 log.Warn("Chain tracing failed", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin), "err", failed) 243 case number < end.NumberU64(): 244 log.Warn("Chain tracing aborted", "start", start.NumberU64(), "end", end.NumberU64(), "abort", number, "transactions", traced, "elapsed", time.Since(begin)) 245 default: 246 log.Info("Chain tracing finished", "start", start.NumberU64(), "end", end.NumberU64(), "transactions", traced, "elapsed", time.Since(begin)) 247 } 248 close(results) 249 }() 250 // Feed all the blocks both into the tracer, as well as fast process concurrently 251 for number = start.NumberU64() + 1; number <= end.NumberU64(); number++ { 252 // Stop tracing if interruption was requested 253 select { 254 case <-notifier.Closed(): 255 return 256 default: 257 } 258 // Print progress logs if long enough time elapsed 259 if time.Since(logged) > 8*time.Second { 260 if number > origin { 261 nodes, imgs := database.TrieDB().Size() 262 log.Info("Tracing chain segment", "start", origin, "end", end.NumberU64(), "current", number, "transactions", traced, "elapsed", time.Since(begin), "memory", nodes+imgs) 263 } else { 264 log.Info("Preparing state for chain trace", "block", number, "start", origin, "elapsed", time.Since(begin)) 265 } 266 logged = time.Now() 267 } 268 // Retrieve the next block to trace 269 block := api.eth.blockchain.GetBlockByNumber(number) 270 if block == nil { 271 failed = fmt.Errorf("block #%d not found", number) 272 break 273 } 274 // Send the block over to the concurrent tracers (if not in the fast-forward phase) 275 if number > origin { 276 txs := block.Transactions() 277 278 select { 279 case tasks <- &blockTraceTask{statedb: statedb.Copy(), privateStateDb: privateStateDb.Copy(), block: block, rootref: proot, results: make([]*txTraceResult, len(txs))}: 280 case <-notifier.Closed(): 281 return 282 } 283 traced += uint64(len(txs)) 284 } 285 // Generate the next state snapshot fast without tracing 286 _, _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, privateStateDb, vm.Config{}) 287 if err != nil { 288 failed = err 289 break 290 } 291 // Finalize the state so any modifications are written to the trie 292 root, err := statedb.Commit(true) 293 if err != nil { 294 failed = err 295 break 296 } 297 if err := statedb.Reset(root); err != nil { 298 failed = err 299 break 300 } 301 302 privateStateRoot, err := privateStateDb.Commit(true) 303 if err != nil { 304 failed = err 305 break 306 } 307 if err := privateStateDb.Reset(privateStateRoot); err != nil { 308 failed = err 309 break 310 } 311 // Reference the trie twice, once for us, once for the tracer 312 database.TrieDB().Reference(root, common.Hash{}) 313 if number >= origin { 314 database.TrieDB().Reference(root, common.Hash{}) 315 } 316 // Dereference all past tries we ourselves are done working with 317 if proot != (common.Hash{}) { 318 database.TrieDB().Dereference(proot) 319 } 320 proot = root 321 322 // TODO(karalabe): Do we need the preimages? Won't they accumulate too much? 323 } 324 }() 325 326 // Keep reading the trace results and stream the to the user 327 go func() { 328 var ( 329 done = make(map[uint64]*blockTraceResult) 330 next = origin + 1 331 ) 332 for res := range results { 333 // Queue up next received result 334 result := &blockTraceResult{ 335 Block: hexutil.Uint64(res.block.NumberU64()), 336 Hash: res.block.Hash(), 337 Traces: res.results, 338 } 339 done[uint64(result.Block)] = result 340 341 // Dereference any paret tries held in memory by this task 342 database.TrieDB().Dereference(res.rootref) 343 344 // Stream completed traces to the user, aborting on the first error 345 for result, ok := done[next]; ok; result, ok = done[next] { 346 if len(result.Traces) > 0 || next == end.NumberU64() { 347 notifier.Notify(sub.ID, result) 348 } 349 delete(done, next) 350 next++ 351 } 352 } 353 }() 354 return sub, nil 355 } 356 357 // TraceBlockByNumber returns the structured logs created during the execution of 358 // EVM and returns them as a JSON object. 359 func (api *PrivateDebugAPI) TraceBlockByNumber(ctx context.Context, number rpc.BlockNumber, config *TraceConfig) ([]*txTraceResult, error) { 360 // Fetch the block that we want to trace 361 var block *types.Block 362 363 switch number { 364 case rpc.PendingBlockNumber: 365 block = api.eth.miner.PendingBlock() 366 case rpc.LatestBlockNumber: 367 block = api.eth.blockchain.CurrentBlock() 368 default: 369 block = api.eth.blockchain.GetBlockByNumber(uint64(number)) 370 } 371 // Trace the block if it was found 372 if block == nil { 373 return nil, fmt.Errorf("block #%d not found", number) 374 } 375 return api.traceBlock(ctx, block, config) 376 } 377 378 // TraceBlockByHash returns the structured logs created during the execution of 379 // EVM and returns them as a JSON object. 380 func (api *PrivateDebugAPI) TraceBlockByHash(ctx context.Context, hash common.Hash, config *TraceConfig) ([]*txTraceResult, error) { 381 block := api.eth.blockchain.GetBlockByHash(hash) 382 if block == nil { 383 return nil, fmt.Errorf("block #%x not found", hash) 384 } 385 return api.traceBlock(ctx, block, config) 386 } 387 388 // TraceBlock returns the structured logs created during the execution of EVM 389 // and returns them as a JSON object. 390 func (api *PrivateDebugAPI) TraceBlock(ctx context.Context, blob []byte, config *TraceConfig) ([]*txTraceResult, error) { 391 block := new(types.Block) 392 if err := rlp.Decode(bytes.NewReader(blob), block); err != nil { 393 return nil, fmt.Errorf("could not decode block: %v", err) 394 } 395 return api.traceBlock(ctx, block, config) 396 } 397 398 // TraceBlockFromFile returns the structured logs created during the execution of 399 // EVM and returns them as a JSON object. 400 func (api *PrivateDebugAPI) TraceBlockFromFile(ctx context.Context, file string, config *TraceConfig) ([]*txTraceResult, error) { 401 blob, err := ioutil.ReadFile(file) 402 if err != nil { 403 return nil, fmt.Errorf("could not read file: %v", err) 404 } 405 return api.TraceBlock(ctx, blob, config) 406 } 407 408 // TraceBadBlock returns the structured logs created during the execution of a block 409 // within the blockchain 'badblocks' cache 410 func (api *PrivateDebugAPI) TraceBadBlock(ctx context.Context, index int, config *TraceConfig) ([]*txTraceResult, error) { 411 if blocks := api.eth.blockchain.BadBlocks(); index < len(blocks) { 412 return api.traceBlock(ctx, blocks[index], config) 413 } 414 return nil, fmt.Errorf("index out of range") 415 } 416 417 // traceBlock configures a new tracer according to the provided configuration, and 418 // executes all the transactions contained within. The return value will be one item 419 // per transaction, dependent on the requestd tracer. 420 func (api *PrivateDebugAPI) traceBlock(ctx context.Context, block *types.Block, config *TraceConfig) ([]*txTraceResult, error) { 421 // Create the parent state database 422 if err := api.eth.engine.VerifyHeader(api.eth.blockchain, block.Header(), true); err != nil { 423 return nil, err 424 } 425 parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 426 if parent == nil { 427 return nil, fmt.Errorf("parent %x not found", block.ParentHash()) 428 } 429 reexec := defaultTraceReexec 430 if config != nil && config.Reexec != nil { 431 reexec = *config.Reexec 432 } 433 statedb, privateStateDb, err := api.computeStateDB(parent, reexec) 434 if err != nil { 435 return nil, err 436 } 437 // Execute all the transaction contained within the block concurrently 438 var ( 439 signer = types.MakeSigner(api.config, block.Number()) 440 441 txs = block.Transactions() 442 results = make([]*txTraceResult, len(txs)) 443 444 pend = new(sync.WaitGroup) 445 jobs = make(chan *txTraceTask, len(txs)) 446 ) 447 threads := runtime.NumCPU() 448 if threads > len(txs) { 449 threads = len(txs) 450 } 451 for th := 0; th < threads; th++ { 452 pend.Add(1) 453 go func() { 454 defer pend.Done() 455 456 // Fetch and execute the next transaction trace tasks 457 for task := range jobs { 458 msg, _ := txs[task.index].AsMessage(signer) 459 vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil) 460 461 res, err := api.traceTx(ctx, msg, vmctx, task.statedb, task.privateStateDb, config) 462 if err != nil { 463 results[task.index] = &txTraceResult{Error: err.Error()} 464 continue 465 } 466 results[task.index] = &txTraceResult{Result: res} 467 } 468 }() 469 } 470 // Feed the transactions into the tracers and return 471 var failed error 472 for i, tx := range txs { 473 // Send the trace task over for execution 474 jobs <- &txTraceTask{ 475 statedb: statedb.Copy(), 476 privateStateDb: privateStateDb.Copy(), 477 index: i, 478 } 479 480 // Generate the next state snapshot fast without tracing 481 msg, _ := tx.AsMessage(signer) 482 vmctx := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil) 483 484 vmenv := vm.NewEVM(vmctx, statedb, privateStateDb, api.config, vm.Config{}) 485 if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas())); err != nil { 486 failed = err 487 break 488 } 489 // Finalize the state so any modifications are written to the trie 490 statedb.Finalise(true) 491 privateStateDb.Finalise(true) 492 } 493 close(jobs) 494 pend.Wait() 495 496 // If execution failed in between, abort 497 if failed != nil { 498 return nil, failed 499 } 500 return results, nil 501 } 502 503 // computeStateDB retrieves the state database associated with a certain block. 504 // If no state is locally available for the given block, a number of blocks are 505 // attempted to be reexecuted to generate the desired state. 506 func (api *PrivateDebugAPI) computeStateDB(block *types.Block, reexec uint64) (*state.StateDB, *state.StateDB, error) { 507 // If we have the state fully available, use that 508 statedb, privateStateDb, err := api.eth.blockchain.StateAt(block.Root()) 509 if err == nil { 510 return statedb, privateStateDb, nil 511 } 512 // Otherwise try to reexec blocks until we find a state or reach our limit 513 origin := block.NumberU64() 514 database := state.NewDatabase(api.eth.ChainDb()) 515 516 for i := uint64(0); i < reexec; i++ { 517 block = api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 518 if block == nil { 519 break 520 } 521 statedb, privateStateDb, err = api.eth.blockchain.StateAt(block.Root()) 522 if err == nil { 523 break 524 } 525 } 526 if err != nil { 527 switch err.(type) { 528 case *trie.MissingNodeError: 529 return nil, nil, errors.New("required historical state unavailable") 530 default: 531 return nil, nil, err 532 } 533 } 534 // State was available at historical point, regenerate 535 var ( 536 start = time.Now() 537 logged time.Time 538 proot common.Hash 539 ) 540 for block.NumberU64() < origin { 541 // Print progress logs if long enough time elapsed 542 if time.Since(logged) > 8*time.Second { 543 log.Info("Regenerating historical state", "block", block.NumberU64()+1, "target", origin, "elapsed", time.Since(start)) 544 logged = time.Now() 545 } 546 // Retrieve the next block to regenerate and process it 547 if block = api.eth.blockchain.GetBlockByNumber(block.NumberU64() + 1); block == nil { 548 return nil, nil, fmt.Errorf("block #%d not found", block.NumberU64()+1) 549 } 550 _, _, _, _, err := api.eth.blockchain.Processor().Process(block, statedb, privateStateDb, vm.Config{}) 551 if err != nil { 552 return nil, nil, err 553 } 554 // Finalize the state so any modifications are written to the trie 555 root, err := statedb.Commit(true) 556 if err != nil { 557 return nil, nil, err 558 } 559 if err := statedb.Reset(root); err != nil { 560 return nil, nil, err 561 } 562 privateStateRoot, err := privateStateDb.Commit(api.eth.blockchain.Config().IsEIP158(block.Number())) 563 if err != nil { 564 return nil, nil, err 565 } 566 if err := privateStateDb.Reset(privateStateRoot); err != nil { 567 return nil, nil, err 568 } 569 database.TrieDB().Reference(root, common.Hash{}) 570 if proot != (common.Hash{}) { 571 database.TrieDB().Dereference(proot) 572 } 573 proot = root 574 } 575 nodes, imgs := database.TrieDB().Size() 576 log.Info("Historical state regenerated", "block", block.NumberU64(), "elapsed", time.Since(start), "nodes", nodes, "preimages", imgs) 577 return statedb, privateStateDb, nil 578 } 579 580 // TraceTransaction returns the structured logs created during the execution of EVM 581 // and returns them as a JSON object. 582 func (api *PrivateDebugAPI) TraceTransaction(ctx context.Context, hash common.Hash, config *TraceConfig) (interface{}, error) { 583 // Retrieve the transaction and assemble its EVM context 584 tx, blockHash, _, index := rawdb.ReadTransaction(api.eth.ChainDb(), hash) 585 if tx == nil { 586 return nil, fmt.Errorf("transaction %x not found", hash) 587 } 588 reexec := defaultTraceReexec 589 if config != nil && config.Reexec != nil { 590 reexec = *config.Reexec 591 } 592 msg, vmctx, statedb, privateStateDb, err := api.computeTxEnv(blockHash, int(index), reexec) 593 if err != nil { 594 return nil, err 595 } 596 // Trace the transaction and return 597 return api.traceTx(ctx, msg, vmctx, statedb, privateStateDb, config) 598 } 599 600 // traceTx configures a new tracer according to the provided configuration, and 601 // executes the given message in the provided environment. The return value will 602 // be tracer dependent. 603 func (api *PrivateDebugAPI) traceTx(ctx context.Context, message core.Message, vmctx vm.Context, statedb *state.StateDB, privateStateDb *state.StateDB, config *TraceConfig) (interface{}, error) { 604 // Assemble the structured logger or the JavaScript tracer 605 var ( 606 tracer vm.Tracer 607 err error 608 ) 609 switch { 610 case config != nil && config.Tracer != nil: 611 // Define a meaningful timeout of a single transaction trace 612 timeout := defaultTraceTimeout 613 if config.Timeout != nil { 614 if timeout, err = time.ParseDuration(*config.Timeout); err != nil { 615 return nil, err 616 } 617 } 618 // Constuct the JavaScript tracer to execute with 619 if tracer, err = tracers.New(*config.Tracer); err != nil { 620 return nil, err 621 } 622 // Handle timeouts and RPC cancellations 623 deadlineCtx, cancel := context.WithTimeout(ctx, timeout) 624 go func() { 625 <-deadlineCtx.Done() 626 tracer.(*tracers.Tracer).Stop(errors.New("execution timeout")) 627 }() 628 defer cancel() 629 630 case config == nil: 631 tracer = vm.NewStructLogger(nil) 632 633 default: 634 tracer = vm.NewStructLogger(config.LogConfig) 635 } 636 637 // Set the private state to public state if it is not a private message 638 if msg, ok := message.(core.PrivateMessage); !ok || !api.config.IsQuorum || !msg.IsPrivate() { 639 privateStateDb = statedb 640 } 641 642 // Run the transaction with tracing enabled. 643 vmenv := vm.NewEVM(vmctx, statedb, privateStateDb, api.config, vm.Config{Debug: true, Tracer: tracer}) 644 645 ret, gas, failed, err := core.ApplyMessage(vmenv, message, new(core.GasPool).AddGas(message.Gas())) 646 if err != nil { 647 return nil, fmt.Errorf("tracing failed: %v", err) 648 } 649 // Depending on the tracer type, format and return the output 650 switch tracer := tracer.(type) { 651 case *vm.StructLogger: 652 return ðapi.ExecutionResult{ 653 Gas: gas, 654 Failed: failed, 655 ReturnValue: fmt.Sprintf("%x", ret), 656 StructLogs: ethapi.FormatLogs(tracer.StructLogs()), 657 }, nil 658 659 case *tracers.Tracer: 660 return tracer.GetResult() 661 662 default: 663 panic(fmt.Sprintf("bad tracer type %T", tracer)) 664 } 665 } 666 667 // computeTxEnv returns the execution environment of a certain transaction. 668 func (api *PrivateDebugAPI) computeTxEnv(blockHash common.Hash, txIndex int, reexec uint64) (core.Message, vm.Context, *state.StateDB, *state.StateDB, error) { 669 // Create the parent state database 670 block := api.eth.blockchain.GetBlockByHash(blockHash) 671 if block == nil { 672 return nil, vm.Context{}, nil, nil, fmt.Errorf("block %x not found", blockHash) 673 } 674 parent := api.eth.blockchain.GetBlock(block.ParentHash(), block.NumberU64()-1) 675 if parent == nil { 676 return nil, vm.Context{}, nil, nil, fmt.Errorf("parent %x not found", block.ParentHash()) 677 } 678 statedb, privateStateDb, err := api.computeStateDB(parent, reexec) 679 if err != nil { 680 return nil, vm.Context{}, nil, nil, err 681 } 682 // Recompute transactions up to the target index. 683 signer := types.MakeSigner(api.config, block.Number()) 684 685 for idx, tx := range block.Transactions() { 686 // Assemble the transaction call message and return if the requested offset 687 msg, _ := tx.AsMessage(signer) 688 context := core.NewEVMContext(msg, block.Header(), api.eth.blockchain, nil) 689 if idx == txIndex { 690 return msg, context, statedb, privateStateDb, nil 691 } 692 // Not yet the searched for transaction, execute on top of the current state 693 vmenv := vm.NewEVM(context, statedb, privateStateDb, api.config, vm.Config{}) 694 if _, _, _, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(tx.Gas())); err != nil { 695 return nil, vm.Context{}, nil, nil, fmt.Errorf("tx %x failed: %v", tx.Hash(), err) 696 } 697 // Ensure any modifications are committed to the state 698 statedb.Finalise(true) 699 } 700 return nil, vm.Context{}, nil, nil, fmt.Errorf("tx index %d out of range for block %x", txIndex, blockHash) 701 }