github.com/jimmyx0x/go-ethereum@v1.10.28/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/ethereum/go-ethereum/common" 32 "github.com/ethereum/go-ethereum/common/hexutil" 33 "github.com/ethereum/go-ethereum/core" 34 "github.com/ethereum/go-ethereum/core/rawdb" 35 "github.com/ethereum/go-ethereum/core/state" 36 "github.com/ethereum/go-ethereum/core/types" 37 "github.com/ethereum/go-ethereum/internal/ethapi" 38 "github.com/ethereum/go-ethereum/log" 39 "github.com/ethereum/go-ethereum/rlp" 40 "github.com/ethereum/go-ethereum/rpc" 41 "github.com/ethereum/go-ethereum/trie" 42 ) 43 44 // 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 if blockNr == rpc.PendingBlockNumber { 264 // If we're dumping the pending state, we need to request 265 // both the pending block as well as the pending state from 266 // the miner and operate on those 267 _, stateDb := api.eth.miner.Pending() 268 return stateDb.RawDump(opts), nil 269 } 270 var block *types.Block 271 if blockNr == rpc.LatestBlockNumber { 272 block = api.eth.blockchain.CurrentBlock() 273 } else if blockNr == rpc.FinalizedBlockNumber { 274 block = api.eth.blockchain.CurrentFinalizedBlock() 275 } else if blockNr == rpc.SafeBlockNumber { 276 block = api.eth.blockchain.CurrentSafeBlock() 277 } else { 278 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 279 } 280 if block == nil { 281 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 282 } 283 stateDb, err := api.eth.BlockChain().StateAt(block.Root()) 284 if err != nil { 285 return state.Dump{}, err 286 } 287 return stateDb.RawDump(opts), nil 288 } 289 290 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 291 func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 292 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 293 return preimage, nil 294 } 295 return nil, errors.New("unknown preimage") 296 } 297 298 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 299 type BadBlockArgs struct { 300 Hash common.Hash `json:"hash"` 301 Block map[string]interface{} `json:"block"` 302 RLP string `json:"rlp"` 303 } 304 305 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 306 // and returns them as a JSON list of block hashes. 307 func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 308 var ( 309 err error 310 blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb) 311 results = make([]*BadBlockArgs, 0, len(blocks)) 312 ) 313 for _, block := range blocks { 314 var ( 315 blockRlp string 316 blockJSON map[string]interface{} 317 ) 318 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 319 blockRlp = err.Error() // Hacky, but hey, it works 320 } else { 321 blockRlp = fmt.Sprintf("%#x", rlpBytes) 322 } 323 if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true, api.eth.APIBackend.ChainConfig()); err != nil { 324 blockJSON = map[string]interface{}{"error": err.Error()} 325 } 326 results = append(results, &BadBlockArgs{ 327 Hash: block.Hash(), 328 RLP: blockRlp, 329 Block: blockJSON, 330 }) 331 } 332 return results, nil 333 } 334 335 // AccountRangeMaxResults is the maximum number of results to be returned per call 336 const AccountRangeMaxResults = 256 337 338 // AccountRange enumerates all accounts in the given block and start point in paging request 339 func (api *DebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 340 var stateDb *state.StateDB 341 var err error 342 343 if number, ok := blockNrOrHash.Number(); ok { 344 if number == rpc.PendingBlockNumber { 345 // If we're dumping the pending state, we need to request 346 // both the pending block as well as the pending state from 347 // the miner and operate on those 348 _, stateDb = api.eth.miner.Pending() 349 } else { 350 var block *types.Block 351 if number == rpc.LatestBlockNumber { 352 block = api.eth.blockchain.CurrentBlock() 353 } else if number == rpc.FinalizedBlockNumber { 354 block = api.eth.blockchain.CurrentFinalizedBlock() 355 } else if number == rpc.SafeBlockNumber { 356 block = api.eth.blockchain.CurrentSafeBlock() 357 } else { 358 block = api.eth.blockchain.GetBlockByNumber(uint64(number)) 359 } 360 if block == nil { 361 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 362 } 363 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 364 if err != nil { 365 return state.IteratorDump{}, err 366 } 367 } 368 } else if hash, ok := blockNrOrHash.Hash(); ok { 369 block := api.eth.blockchain.GetBlockByHash(hash) 370 if block == nil { 371 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 372 } 373 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 374 if err != nil { 375 return state.IteratorDump{}, err 376 } 377 } else { 378 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 379 } 380 381 opts := &state.DumpConfig{ 382 SkipCode: nocode, 383 SkipStorage: nostorage, 384 OnlyWithAddresses: !incompletes, 385 Start: start, 386 Max: uint64(maxResults), 387 } 388 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 389 opts.Max = AccountRangeMaxResults 390 } 391 return stateDb.IteratorDump(opts), nil 392 } 393 394 // StorageRangeResult is the result of a debug_storageRangeAt API call. 395 type StorageRangeResult struct { 396 Storage storageMap `json:"storage"` 397 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 398 } 399 400 type storageMap map[common.Hash]storageEntry 401 402 type storageEntry struct { 403 Key *common.Hash `json:"key"` 404 Value common.Hash `json:"value"` 405 } 406 407 // StorageRangeAt returns the storage at the given block height and transaction index. 408 func (api *DebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 409 // Retrieve the block 410 block := api.eth.blockchain.GetBlockByHash(blockHash) 411 if block == nil { 412 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 413 } 414 _, _, statedb, release, err := api.eth.stateAtTransaction(ctx, block, txIndex, 0) 415 if err != nil { 416 return StorageRangeResult{}, err 417 } 418 defer release() 419 420 st, err := statedb.StorageTrie(contractAddress) 421 if err != nil { 422 return StorageRangeResult{}, err 423 } 424 if st == nil { 425 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 426 } 427 return storageRangeAt(st, keyStart, maxResult) 428 } 429 430 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 431 it := trie.NewIterator(st.NodeIterator(start)) 432 result := StorageRangeResult{Storage: storageMap{}} 433 for i := 0; i < maxResult && it.Next(); i++ { 434 _, content, _, err := rlp.Split(it.Value) 435 if err != nil { 436 return StorageRangeResult{}, err 437 } 438 e := storageEntry{Value: common.BytesToHash(content)} 439 if preimage := st.GetKey(it.Key); preimage != nil { 440 preimage := common.BytesToHash(preimage) 441 e.Key = &preimage 442 } 443 result.Storage[common.BytesToHash(it.Key)] = e 444 } 445 // Add the 'next key' so clients can continue downloading. 446 if it.Next() { 447 next := common.BytesToHash(it.Key) 448 result.NextKey = &next 449 } 450 return result, nil 451 } 452 453 // GetModifiedAccountsByNumber returns all accounts that have changed between the 454 // two blocks specified. A change is defined as a difference in nonce, balance, 455 // code hash, or storage hash. 456 // 457 // With one parameter, returns the list of accounts modified in the specified block. 458 func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 459 var startBlock, endBlock *types.Block 460 461 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 462 if startBlock == nil { 463 return nil, fmt.Errorf("start block %x not found", startNum) 464 } 465 466 if endNum == nil { 467 endBlock = startBlock 468 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 469 if startBlock == nil { 470 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 471 } 472 } else { 473 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 474 if endBlock == nil { 475 return nil, fmt.Errorf("end block %d not found", *endNum) 476 } 477 } 478 return api.getModifiedAccounts(startBlock, endBlock) 479 } 480 481 // GetModifiedAccountsByHash returns all accounts that have changed between the 482 // two blocks specified. A change is defined as a difference in nonce, balance, 483 // code hash, or storage hash. 484 // 485 // With one parameter, returns the list of accounts modified in the specified block. 486 func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 487 var startBlock, endBlock *types.Block 488 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 489 if startBlock == nil { 490 return nil, fmt.Errorf("start block %x not found", startHash) 491 } 492 493 if endHash == nil { 494 endBlock = startBlock 495 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 496 if startBlock == nil { 497 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 498 } 499 } else { 500 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 501 if endBlock == nil { 502 return nil, fmt.Errorf("end block %x not found", *endHash) 503 } 504 } 505 return api.getModifiedAccounts(startBlock, endBlock) 506 } 507 508 func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 509 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 510 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 511 } 512 triedb := api.eth.BlockChain().StateCache().TrieDB() 513 514 oldTrie, err := trie.NewStateTrie(trie.StateTrieID(startBlock.Root()), triedb) 515 if err != nil { 516 return nil, err 517 } 518 newTrie, err := trie.NewStateTrie(trie.StateTrieID(endBlock.Root()), triedb) 519 if err != nil { 520 return nil, err 521 } 522 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 523 iter := trie.NewIterator(diff) 524 525 var dirty []common.Address 526 for iter.Next() { 527 key := newTrie.GetKey(iter.Key) 528 if key == nil { 529 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 530 } 531 dirty = append(dirty, common.BytesToAddress(key)) 532 } 533 return dirty, nil 534 } 535 536 // GetAccessibleState returns the first number where the node has accessible 537 // state on disk. Note this being the post-state of that block and the pre-state 538 // of the next block. 539 // The (from, to) parameters are the sequence of blocks to search, which can go 540 // either forwards or backwards 541 func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { 542 db := api.eth.ChainDb() 543 var pivot uint64 544 if p := rawdb.ReadLastPivotNumber(db); p != nil { 545 pivot = *p 546 log.Info("Found fast-sync pivot marker", "number", pivot) 547 } 548 var resolveNum = func(num rpc.BlockNumber) (uint64, error) { 549 // We don't have state for pending (-2), so treat it as latest 550 if num.Int64() < 0 { 551 block := api.eth.blockchain.CurrentBlock() 552 if block == nil { 553 return 0, fmt.Errorf("current block missing") 554 } 555 return block.NumberU64(), nil 556 } 557 return uint64(num.Int64()), nil 558 } 559 var ( 560 start uint64 561 end uint64 562 delta = int64(1) 563 lastLog time.Time 564 err error 565 ) 566 if start, err = resolveNum(from); err != nil { 567 return 0, err 568 } 569 if end, err = resolveNum(to); err != nil { 570 return 0, err 571 } 572 if start == end { 573 return 0, fmt.Errorf("from and to needs to be different") 574 } 575 if start > end { 576 delta = -1 577 } 578 for i := int64(start); i != int64(end); i += delta { 579 if time.Since(lastLog) > 8*time.Second { 580 log.Info("Finding roots", "from", start, "to", end, "at", i) 581 lastLog = time.Now() 582 } 583 if i < int64(pivot) { 584 continue 585 } 586 h := api.eth.BlockChain().GetHeaderByNumber(uint64(i)) 587 if h == nil { 588 return 0, fmt.Errorf("missing header %d", i) 589 } 590 if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok { 591 return uint64(i), nil 592 } 593 } 594 return 0, errors.New("no state found") 595 } 596 597 // SetTrieFlushInterval configures how often in-memory tries are persisted 598 // to disk. The value is in terms of block processing time, not wall clock. 599 func (api *DebugAPI) SetTrieFlushInterval(interval string) error { 600 t, err := time.ParseDuration(interval) 601 if err != nil { 602 return err 603 } 604 api.eth.blockchain.SetTrieFlushInterval(t) 605 return nil 606 }