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