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