github.com/tacshi/go-ethereum@v0.0.0-20230616113857-84a434e20921/eth/api.go (about) 1 // Copyright 2015 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 "compress/gzip" 21 "context" 22 "errors" 23 "fmt" 24 "io" 25 "math/big" 26 "os" 27 "runtime" 28 "strings" 29 "time" 30 31 "github.com/tacshi/go-ethereum/common" 32 "github.com/tacshi/go-ethereum/common/hexutil" 33 "github.com/tacshi/go-ethereum/core" 34 "github.com/tacshi/go-ethereum/core/rawdb" 35 "github.com/tacshi/go-ethereum/core/state" 36 "github.com/tacshi/go-ethereum/core/types" 37 "github.com/tacshi/go-ethereum/internal/ethapi" 38 "github.com/tacshi/go-ethereum/log" 39 "github.com/tacshi/go-ethereum/rlp" 40 "github.com/tacshi/go-ethereum/rpc" 41 "github.com/tacshi/go-ethereum/trie" 42 ) 43 44 // EthereumAPI provides an API to access Ethereum full node-related information. 45 type EthereumAPI struct { 46 e *Ethereum 47 } 48 49 // NewEthereumAPI creates a new Ethereum protocol API for full nodes. 50 func NewEthereumAPI(e *Ethereum) *EthereumAPI { 51 return &EthereumAPI{e} 52 } 53 54 // Etherbase is the address that mining rewards will be send to. 55 func (api *EthereumAPI) Etherbase() (common.Address, error) { 56 return api.e.Etherbase() 57 } 58 59 // Coinbase is the address that mining rewards will be send to (alias for Etherbase). 60 func (api *EthereumAPI) Coinbase() (common.Address, error) { 61 return api.Etherbase() 62 } 63 64 // Hashrate returns the POW hashrate. 65 func (api *EthereumAPI) Hashrate() hexutil.Uint64 { 66 return hexutil.Uint64(api.e.Miner().Hashrate()) 67 } 68 69 // Mining returns an indication if this node is currently mining. 70 func (api *EthereumAPI) Mining() bool { 71 return api.e.IsMining() 72 } 73 74 // MinerAPI provides an API to control the miner. 75 type MinerAPI struct { 76 e *Ethereum 77 } 78 79 // NewMinerAPI create a new MinerAPI instance. 80 func NewMinerAPI(e *Ethereum) *MinerAPI { 81 return &MinerAPI{e} 82 } 83 84 // Start starts the miner with the given number of threads. If threads is nil, 85 // the number of workers started is equal to the number of logical CPUs that are 86 // usable by this process. If mining is already running, this method adjust the 87 // number of threads allowed to use and updates the minimum price required by the 88 // transaction pool. 89 func (api *MinerAPI) Start(threads *int) error { 90 if threads == nil { 91 return api.e.StartMining(runtime.NumCPU()) 92 } 93 return api.e.StartMining(*threads) 94 } 95 96 // Stop terminates the miner, both at the consensus engine level as well as at 97 // the block creation level. 98 func (api *MinerAPI) Stop() { 99 api.e.StopMining() 100 } 101 102 // SetExtra sets the extra data string that is included when this miner mines a block. 103 func (api *MinerAPI) SetExtra(extra string) (bool, error) { 104 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 105 return false, err 106 } 107 return true, nil 108 } 109 110 // SetGasPrice sets the minimum accepted gas price for the miner. 111 func (api *MinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 112 api.e.lock.Lock() 113 api.e.gasPrice = (*big.Int)(&gasPrice) 114 api.e.lock.Unlock() 115 116 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 117 return true 118 } 119 120 // SetGasLimit sets the gaslimit to target towards during mining. 121 func (api *MinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool { 122 api.e.Miner().SetGasCeil(uint64(gasLimit)) 123 return true 124 } 125 126 // SetEtherbase sets the etherbase of the miner. 127 func (api *MinerAPI) SetEtherbase(etherbase common.Address) bool { 128 api.e.SetEtherbase(etherbase) 129 return true 130 } 131 132 // SetRecommitInterval updates the interval for miner sealing work recommitting. 133 func (api *MinerAPI) SetRecommitInterval(interval int) { 134 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 135 } 136 137 // AdminAPI is the collection of Ethereum full node related APIs for node 138 // administration. 139 type AdminAPI struct { 140 eth *Ethereum 141 } 142 143 // NewAdminAPI creates a new instance of AdminAPI. 144 func NewAdminAPI(eth *Ethereum) *AdminAPI { 145 return &AdminAPI{eth: eth} 146 } 147 148 // ExportChain exports the current blockchain into a local file, 149 // or a range of blocks if first and last are non-nil. 150 func (api *AdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { 151 if first == nil && last != nil { 152 return false, errors.New("last cannot be specified without first") 153 } 154 if first != nil && last == nil { 155 head := api.eth.BlockChain().CurrentHeader().Number.Uint64() 156 last = &head 157 } 158 if _, err := os.Stat(file); err == nil { 159 // File already exists. Allowing overwrite could be a DoS vector, 160 // since the 'file' may point to arbitrary paths on the drive. 161 return false, errors.New("location would overwrite an existing file") 162 } 163 // Make sure we can create the file to export into 164 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 165 if err != nil { 166 return false, err 167 } 168 defer out.Close() 169 170 var writer io.Writer = out 171 if strings.HasSuffix(file, ".gz") { 172 writer = gzip.NewWriter(writer) 173 defer writer.(*gzip.Writer).Close() 174 } 175 176 // Export the blockchain 177 if first != nil { 178 if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil { 179 return false, err 180 } 181 } else if err := api.eth.BlockChain().Export(writer); err != nil { 182 return false, err 183 } 184 return true, nil 185 } 186 187 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 188 for _, b := range bs { 189 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 190 return false 191 } 192 } 193 194 return true 195 } 196 197 // ImportChain imports a blockchain from a local file. 198 func (api *AdminAPI) ImportChain(file string) (bool, error) { 199 // Make sure the can access the file to import 200 in, err := os.Open(file) 201 if err != nil { 202 return false, err 203 } 204 defer in.Close() 205 206 var reader io.Reader = in 207 if strings.HasSuffix(file, ".gz") { 208 if reader, err = gzip.NewReader(reader); err != nil { 209 return false, err 210 } 211 } 212 213 // Run actual the import in pre-configured batches 214 stream := rlp.NewStream(reader, 0) 215 216 blocks, index := make([]*types.Block, 0, 2500), 0 217 for batch := 0; ; batch++ { 218 // Load a batch of blocks from the input file 219 for len(blocks) < cap(blocks) { 220 block := new(types.Block) 221 if err := stream.Decode(block); err == io.EOF { 222 break 223 } else if err != nil { 224 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 225 } 226 blocks = append(blocks, block) 227 index++ 228 } 229 if len(blocks) == 0 { 230 break 231 } 232 233 if hasAllBlocks(api.eth.BlockChain(), blocks) { 234 blocks = blocks[:0] 235 continue 236 } 237 // Import the batch and reset the buffer 238 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 239 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 240 } 241 blocks = blocks[:0] 242 } 243 return true, nil 244 } 245 246 // DebugAPI is the collection of Ethereum full node APIs for debugging the 247 // protocol. 248 type DebugAPI struct { 249 eth *Ethereum 250 } 251 252 // NewDebugAPI creates a new DebugAPI instance. 253 func NewDebugAPI(eth *Ethereum) *DebugAPI { 254 return &DebugAPI{eth: eth} 255 } 256 257 // DumpBlock retrieves the entire state of the database at a given block. 258 func (api *DebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { 259 opts := &state.DumpConfig{ 260 OnlyWithAddresses: true, 261 Max: AccountRangeMaxResults, // Sanity limit over RPC 262 } 263 // arbitrum: in case of ArbEthereum, miner in not available here 264 // use current block instead of pending 265 if blockNr == rpc.PendingBlockNumber && api.eth.miner == nil { 266 blockNr = rpc.LatestBlockNumber 267 } 268 if blockNr == rpc.PendingBlockNumber { 269 // If we're dumping the pending state, we need to request 270 // both the pending block as well as the pending state from 271 // the miner and operate on those 272 _, stateDb := api.eth.miner.Pending() 273 return stateDb.RawDump(opts), nil 274 } 275 var header *types.Header 276 if blockNr == rpc.LatestBlockNumber { 277 header = api.eth.blockchain.CurrentBlock() 278 } else if blockNr == rpc.FinalizedBlockNumber { 279 header = api.eth.blockchain.CurrentFinalBlock() 280 } else if blockNr == rpc.SafeBlockNumber { 281 header = api.eth.blockchain.CurrentSafeBlock() 282 } else { 283 block := api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 284 if block == nil { 285 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 286 } 287 header = block.Header() 288 } 289 if header == nil { 290 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 291 } 292 stateDb, err := api.eth.BlockChain().StateAt(header.Root) 293 if err != nil { 294 return state.Dump{}, err 295 } 296 return stateDb.RawDump(opts), nil 297 } 298 299 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 300 func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 301 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 302 return preimage, nil 303 } 304 return nil, errors.New("unknown preimage") 305 } 306 307 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 308 type BadBlockArgs struct { 309 Hash common.Hash `json:"hash"` 310 Block map[string]interface{} `json:"block"` 311 RLP string `json:"rlp"` 312 } 313 314 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 315 // and returns them as a JSON list of block hashes. 316 func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 317 var ( 318 err error 319 blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb) 320 results = make([]*BadBlockArgs, 0, len(blocks)) 321 ) 322 for _, block := range blocks { 323 var ( 324 blockRlp string 325 blockJSON map[string]interface{} 326 ) 327 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 328 blockRlp = err.Error() // Hacky, but hey, it works 329 } else { 330 blockRlp = fmt.Sprintf("%#x", rlpBytes) 331 } 332 if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true, api.eth.blockchain.Config()); err != nil { 333 blockJSON = map[string]interface{}{"error": err.Error()} 334 } 335 results = append(results, &BadBlockArgs{ 336 Hash: block.Hash(), 337 RLP: blockRlp, 338 Block: blockJSON, 339 }) 340 } 341 return results, nil 342 } 343 344 // AccountRangeMaxResults is the maximum number of results to be returned per call 345 const AccountRangeMaxResults = 256 346 347 // AccountRange enumerates all accounts in the given block and start point in paging request 348 func (api *DebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 349 var stateDb *state.StateDB 350 var err error 351 352 if number, ok := blockNrOrHash.Number(); ok { 353 // arbitrum: in case of ArbEthereum, miner in not available here 354 // use current block instead of pending 355 if number == rpc.PendingBlockNumber && api.eth.miner == nil { 356 number = rpc.LatestBlockNumber 357 } 358 if number == rpc.PendingBlockNumber { 359 // If we're dumping the pending state, we need to request 360 // both the pending block as well as the pending state from 361 // the miner and operate on those 362 _, stateDb = api.eth.miner.Pending() 363 } else { 364 var header *types.Header 365 if number == rpc.LatestBlockNumber { 366 header = api.eth.blockchain.CurrentBlock() 367 } else if number == rpc.FinalizedBlockNumber { 368 header = api.eth.blockchain.CurrentFinalBlock() 369 } else if number == rpc.SafeBlockNumber { 370 header = api.eth.blockchain.CurrentSafeBlock() 371 } else { 372 block := api.eth.blockchain.GetBlockByNumber(uint64(number)) 373 if block == nil { 374 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 375 } 376 header = block.Header() 377 } 378 if header == nil { 379 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 380 } 381 stateDb, err = api.eth.BlockChain().StateAt(header.Root) 382 if err != nil { 383 return state.IteratorDump{}, err 384 } 385 } 386 } else if hash, ok := blockNrOrHash.Hash(); ok { 387 block := api.eth.blockchain.GetBlockByHash(hash) 388 if block == nil { 389 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 390 } 391 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 392 if err != nil { 393 return state.IteratorDump{}, err 394 } 395 } else { 396 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 397 } 398 399 opts := &state.DumpConfig{ 400 SkipCode: nocode, 401 SkipStorage: nostorage, 402 OnlyWithAddresses: !incompletes, 403 Start: start, 404 Max: uint64(maxResults), 405 } 406 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 407 opts.Max = AccountRangeMaxResults 408 } 409 return stateDb.IteratorDump(opts), nil 410 } 411 412 // StorageRangeResult is the result of a debug_storageRangeAt API call. 413 type StorageRangeResult struct { 414 Storage storageMap `json:"storage"` 415 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 416 } 417 418 type storageMap map[common.Hash]storageEntry 419 420 type storageEntry struct { 421 Key *common.Hash `json:"key"` 422 Value common.Hash `json:"value"` 423 } 424 425 // StorageRangeAt returns the storage at the given block height and transaction index. 426 func (api *DebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 427 // Retrieve the block 428 block := api.eth.blockchain.GetBlockByHash(blockHash) 429 if block == nil { 430 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 431 } 432 _, _, statedb, release, err := api.eth.stateAtTransaction(ctx, block, txIndex, 0) 433 if err != nil { 434 return StorageRangeResult{}, err 435 } 436 defer release() 437 438 st, err := statedb.StorageTrie(contractAddress) 439 if err != nil { 440 return StorageRangeResult{}, err 441 } 442 if st == nil { 443 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 444 } 445 return storageRangeAt(st, keyStart, maxResult) 446 } 447 448 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 449 it := trie.NewIterator(st.NodeIterator(start)) 450 result := StorageRangeResult{Storage: storageMap{}} 451 for i := 0; i < maxResult && it.Next(); i++ { 452 _, content, _, err := rlp.Split(it.Value) 453 if err != nil { 454 return StorageRangeResult{}, err 455 } 456 e := storageEntry{Value: common.BytesToHash(content)} 457 if preimage := st.GetKey(it.Key); preimage != nil { 458 preimage := common.BytesToHash(preimage) 459 e.Key = &preimage 460 } 461 result.Storage[common.BytesToHash(it.Key)] = e 462 } 463 // Add the 'next key' so clients can continue downloading. 464 if it.Next() { 465 next := common.BytesToHash(it.Key) 466 result.NextKey = &next 467 } 468 return result, nil 469 } 470 471 // GetModifiedAccountsByNumber returns all accounts that have changed between the 472 // two blocks specified. A change is defined as a difference in nonce, balance, 473 // code hash, or storage hash. 474 // 475 // With one parameter, returns the list of accounts modified in the specified block. 476 func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 477 var startBlock, endBlock *types.Block 478 479 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 480 if startBlock == nil { 481 return nil, fmt.Errorf("start block %x not found", startNum) 482 } 483 484 if endNum == nil { 485 endBlock = startBlock 486 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 487 if startBlock == nil { 488 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 489 } 490 } else { 491 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 492 if endBlock == nil { 493 return nil, fmt.Errorf("end block %d not found", *endNum) 494 } 495 } 496 return api.getModifiedAccounts(startBlock, endBlock) 497 } 498 499 // GetModifiedAccountsByHash returns all accounts that have changed between the 500 // two blocks specified. A change is defined as a difference in nonce, balance, 501 // code hash, or storage hash. 502 // 503 // With one parameter, returns the list of accounts modified in the specified block. 504 func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 505 var startBlock, endBlock *types.Block 506 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 507 if startBlock == nil { 508 return nil, fmt.Errorf("start block %x not found", startHash) 509 } 510 511 if endHash == nil { 512 endBlock = startBlock 513 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 514 if startBlock == nil { 515 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 516 } 517 } else { 518 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 519 if endBlock == nil { 520 return nil, fmt.Errorf("end block %x not found", *endHash) 521 } 522 } 523 return api.getModifiedAccounts(startBlock, endBlock) 524 } 525 526 func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 527 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 528 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 529 } 530 triedb := api.eth.BlockChain().StateCache().TrieDB() 531 532 oldTrie, err := trie.NewStateTrie(trie.StateTrieID(startBlock.Root()), triedb) 533 if err != nil { 534 return nil, err 535 } 536 newTrie, err := trie.NewStateTrie(trie.StateTrieID(endBlock.Root()), triedb) 537 if err != nil { 538 return nil, err 539 } 540 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 541 iter := trie.NewIterator(diff) 542 543 var dirty []common.Address 544 for iter.Next() { 545 key := newTrie.GetKey(iter.Key) 546 if key == nil { 547 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 548 } 549 dirty = append(dirty, common.BytesToAddress(key)) 550 } 551 return dirty, nil 552 } 553 554 // GetAccessibleState returns the first number where the node has accessible 555 // state on disk. Note this being the post-state of that block and the pre-state 556 // of the next block. 557 // The (from, to) parameters are the sequence of blocks to search, which can go 558 // either forwards or backwards 559 func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { 560 db := api.eth.ChainDb() 561 var pivot uint64 562 if p := rawdb.ReadLastPivotNumber(db); p != nil { 563 pivot = *p 564 log.Info("Found fast-sync pivot marker", "number", pivot) 565 } 566 var resolveNum = func(num rpc.BlockNumber) (uint64, error) { 567 // We don't have state for pending (-2), so treat it as latest 568 if num.Int64() < 0 { 569 block := api.eth.blockchain.CurrentBlock() 570 if block == nil { 571 return 0, fmt.Errorf("current block missing") 572 } 573 return block.Number.Uint64(), nil 574 } 575 return uint64(num.Int64()), nil 576 } 577 var ( 578 start uint64 579 end uint64 580 delta = int64(1) 581 lastLog time.Time 582 err error 583 ) 584 if start, err = resolveNum(from); err != nil { 585 return 0, err 586 } 587 if end, err = resolveNum(to); err != nil { 588 return 0, err 589 } 590 if start == end { 591 return 0, fmt.Errorf("from and to needs to be different") 592 } 593 if start > end { 594 delta = -1 595 } 596 for i := int64(start); i != int64(end); i += delta { 597 if time.Since(lastLog) > 8*time.Second { 598 log.Info("Finding roots", "from", start, "to", end, "at", i) 599 lastLog = time.Now() 600 } 601 if i < int64(pivot) { 602 continue 603 } 604 h := api.eth.BlockChain().GetHeaderByNumber(uint64(i)) 605 if h == nil { 606 return 0, fmt.Errorf("missing header %d", i) 607 } 608 if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok { 609 return uint64(i), nil 610 } 611 } 612 return 0, errors.New("no state found") 613 } 614 615 // SetTrieFlushInterval configures how often in-memory tries are persisted 616 // to disk. The value is in terms of block processing time, not wall clock. 617 func (api *DebugAPI) SetTrieFlushInterval(interval string) error { 618 t, err := time.ParseDuration(interval) 619 if err != nil { 620 return err 621 } 622 api.eth.blockchain.SetTrieFlushInterval(t) 623 return nil 624 }