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