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