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