github.com/carter-ya/go-ethereum@v0.0.0-20230628080049-d2309be3983b/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(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(block, txIndex, 0) 415 if err != nil { 416 return StorageRangeResult{}, err 417 } 418 defer release() 419 420 st := statedb.StorageTrie(contractAddress) 421 if st == nil { 422 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 423 } 424 return storageRangeAt(st, keyStart, maxResult) 425 } 426 427 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 428 it := trie.NewIterator(st.NodeIterator(start)) 429 result := StorageRangeResult{Storage: storageMap{}} 430 for i := 0; i < maxResult && it.Next(); i++ { 431 _, content, _, err := rlp.Split(it.Value) 432 if err != nil { 433 return StorageRangeResult{}, err 434 } 435 e := storageEntry{Value: common.BytesToHash(content)} 436 if preimage := st.GetKey(it.Key); preimage != nil { 437 preimage := common.BytesToHash(preimage) 438 e.Key = &preimage 439 } 440 result.Storage[common.BytesToHash(it.Key)] = e 441 } 442 // Add the 'next key' so clients can continue downloading. 443 if it.Next() { 444 next := common.BytesToHash(it.Key) 445 result.NextKey = &next 446 } 447 return result, nil 448 } 449 450 // GetModifiedAccountsByNumber returns all accounts that have changed between the 451 // two blocks specified. A change is defined as a difference in nonce, balance, 452 // code hash, or storage hash. 453 // 454 // With one parameter, returns the list of accounts modified in the specified block. 455 func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 456 var startBlock, endBlock *types.Block 457 458 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 459 if startBlock == nil { 460 return nil, fmt.Errorf("start block %x not found", startNum) 461 } 462 463 if endNum == nil { 464 endBlock = startBlock 465 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 466 if startBlock == nil { 467 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 468 } 469 } else { 470 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 471 if endBlock == nil { 472 return nil, fmt.Errorf("end block %d not found", *endNum) 473 } 474 } 475 return api.getModifiedAccounts(startBlock, endBlock) 476 } 477 478 // GetModifiedAccountsByHash returns all accounts that have changed between the 479 // two blocks specified. A change is defined as a difference in nonce, balance, 480 // code hash, or storage hash. 481 // 482 // With one parameter, returns the list of accounts modified in the specified block. 483 func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 484 var startBlock, endBlock *types.Block 485 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 486 if startBlock == nil { 487 return nil, fmt.Errorf("start block %x not found", startHash) 488 } 489 490 if endHash == nil { 491 endBlock = startBlock 492 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 493 if startBlock == nil { 494 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 495 } 496 } else { 497 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 498 if endBlock == nil { 499 return nil, fmt.Errorf("end block %x not found", *endHash) 500 } 501 } 502 return api.getModifiedAccounts(startBlock, endBlock) 503 } 504 505 func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 506 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 507 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 508 } 509 triedb := api.eth.BlockChain().StateCache().TrieDB() 510 511 oldTrie, err := trie.NewStateTrie(trie.StateTrieID(startBlock.Root()), triedb) 512 if err != nil { 513 return nil, err 514 } 515 newTrie, err := trie.NewStateTrie(trie.StateTrieID(endBlock.Root()), triedb) 516 if err != nil { 517 return nil, err 518 } 519 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 520 iter := trie.NewIterator(diff) 521 522 var dirty []common.Address 523 for iter.Next() { 524 key := newTrie.GetKey(iter.Key) 525 if key == nil { 526 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 527 } 528 dirty = append(dirty, common.BytesToAddress(key)) 529 } 530 return dirty, nil 531 } 532 533 // GetAccessibleState returns the first number where the node has accessible 534 // state on disk. Note this being the post-state of that block and the pre-state 535 // of the next block. 536 // The (from, to) parameters are the sequence of blocks to search, which can go 537 // either forwards or backwards 538 func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { 539 db := api.eth.ChainDb() 540 var pivot uint64 541 if p := rawdb.ReadLastPivotNumber(db); p != nil { 542 pivot = *p 543 log.Info("Found fast-sync pivot marker", "number", pivot) 544 } 545 var resolveNum = func(num rpc.BlockNumber) (uint64, error) { 546 // We don't have state for pending (-2), so treat it as latest 547 if num.Int64() < 0 { 548 block := api.eth.blockchain.CurrentBlock() 549 if block == nil { 550 return 0, fmt.Errorf("current block missing") 551 } 552 return block.NumberU64(), nil 553 } 554 return uint64(num.Int64()), nil 555 } 556 var ( 557 start uint64 558 end uint64 559 delta = int64(1) 560 lastLog time.Time 561 err error 562 ) 563 if start, err = resolveNum(from); err != nil { 564 return 0, err 565 } 566 if end, err = resolveNum(to); err != nil { 567 return 0, err 568 } 569 if start == end { 570 return 0, fmt.Errorf("from and to needs to be different") 571 } 572 if start > end { 573 delta = -1 574 } 575 for i := int64(start); i != int64(end); i += delta { 576 if time.Since(lastLog) > 8*time.Second { 577 log.Info("Finding roots", "from", start, "to", end, "at", i) 578 lastLog = time.Now() 579 } 580 if i < int64(pivot) { 581 continue 582 } 583 h := api.eth.BlockChain().GetHeaderByNumber(uint64(i)) 584 if h == nil { 585 return 0, fmt.Errorf("missing header %d", i) 586 } 587 if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok { 588 return uint64(i), nil 589 } 590 } 591 return 0, errors.New("no state found") 592 }