github.com/coltonfike/e2c@v21.1.0+incompatible/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/rlp" 39 "github.com/ethereum/go-ethereum/rpc" 40 "github.com/ethereum/go-ethereum/trie" 41 ) 42 43 // PublicEthereumAPI provides an API to access Ethereum full node-related 44 // information. 45 type PublicEthereumAPI struct { 46 e *Ethereum 47 } 48 49 // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. 50 func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { 51 return &PublicEthereumAPI{e} 52 } 53 54 // Etherbase is the address that mining rewards will be send to 55 func (api *PublicEthereumAPI) 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 *PublicEthereumAPI) Coinbase() (common.Address, error) { 61 return api.Etherbase() 62 } 63 64 // Quorum 65 // StorageRoot returns the storage root of an account on the the given (optional) block height. 66 // If block number is not given the latest block is used. 67 func (s *PublicEthereumAPI) StorageRoot(addr common.Address, blockNr *rpc.BlockNumber) (common.Hash, error) { 68 var ( 69 pub, priv *state.StateDB 70 err error 71 ) 72 73 if blockNr == nil || blockNr.Int64() == rpc.LatestBlockNumber.Int64() { 74 pub, priv, err = s.e.blockchain.State() 75 } else { 76 if ch := s.e.blockchain.GetHeaderByNumber(uint64(blockNr.Int64())); ch != nil { 77 pub, priv, err = s.e.blockchain.StateAt(ch.Root) 78 } else { 79 return common.Hash{}, fmt.Errorf("invalid block number") 80 } 81 } 82 83 if err != nil { 84 return common.Hash{}, err 85 } 86 87 if priv.Exist(addr) { 88 return priv.GetStorageRoot(addr) 89 } 90 return pub.GetStorageRoot(addr) 91 } 92 93 // Hashrate returns the POW hashrate 94 func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 { 95 return hexutil.Uint64(api.e.Miner().HashRate()) 96 } 97 98 // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config. 99 func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 { 100 chainID := new(big.Int) 101 if config := api.e.blockchain.Config(); config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) { 102 chainID = config.ChainID 103 } 104 return (hexutil.Uint64)(chainID.Uint64()) 105 } 106 107 // PublicMinerAPI provides an API to control the miner. 108 // It offers only methods that operate on data that pose no security risk when it is publicly accessible. 109 type PublicMinerAPI struct { 110 e *Ethereum 111 } 112 113 // NewPublicMinerAPI create a new PublicMinerAPI instance. 114 func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI { 115 return &PublicMinerAPI{e} 116 } 117 118 // Mining returns an indication if this node is currently mining. 119 func (api *PublicMinerAPI) Mining() bool { 120 return api.e.IsMining() 121 } 122 123 // PrivateMinerAPI provides private RPC methods to control the miner. 124 // These methods can be abused by external users and must be considered insecure for use by untrusted users. 125 type PrivateMinerAPI struct { 126 e *Ethereum 127 } 128 129 // NewPrivateMinerAPI create a new RPC service which controls the miner of this node. 130 func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { 131 return &PrivateMinerAPI{e: e} 132 } 133 134 // Start starts the miner with the given number of threads. If threads is nil, 135 // the number of workers started is equal to the number of logical CPUs that are 136 // usable by this process. If mining is already running, this method adjust the 137 // number of threads allowed to use and updates the minimum price required by the 138 // transaction pool. 139 func (api *PrivateMinerAPI) Start(threads *int) error { 140 if threads == nil { 141 return api.e.StartMining(runtime.NumCPU()) 142 } 143 return api.e.StartMining(*threads) 144 } 145 146 // Stop terminates the miner, both at the consensus engine level as well as at 147 // the block creation level. 148 func (api *PrivateMinerAPI) Stop() { 149 api.e.StopMining() 150 } 151 152 // SetExtra sets the extra data string that is included when this miner mines a block. 153 func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) { 154 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 155 return false, err 156 } 157 return true, nil 158 } 159 160 // SetGasPrice sets the minimum accepted gas price for the miner. 161 func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 162 api.e.lock.Lock() 163 api.e.gasPrice = (*big.Int)(&gasPrice) 164 api.e.lock.Unlock() 165 166 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 167 return true 168 } 169 170 // SetEtherbase sets the etherbase of the miner 171 func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool { 172 api.e.SetEtherbase(etherbase) 173 return true 174 } 175 176 // SetRecommitInterval updates the interval for miner sealing work recommitting. 177 func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { 178 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 179 } 180 181 // GetHashrate returns the current hashrate of the miner. 182 func (api *PrivateMinerAPI) GetHashrate() uint64 { 183 return api.e.miner.HashRate() 184 } 185 186 // PrivateAdminAPI is the collection of Ethereum full node-related APIs 187 // exposed over the private admin endpoint. 188 type PrivateAdminAPI struct { 189 eth *Ethereum 190 } 191 192 // NewPrivateAdminAPI creates a new API definition for the full node private 193 // admin methods of the Ethereum service. 194 func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { 195 return &PrivateAdminAPI{eth: eth} 196 } 197 198 // ExportChain exports the current blockchain into a local file. 199 func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) { 200 if _, err := os.Stat(file); err == nil { 201 // File already exists. Allowing overwrite could be a DoS vecotor, 202 // since the 'file' may point to arbitrary paths on the drive 203 return false, errors.New("location would overwrite an existing file") 204 } 205 // Make sure we can create the file to export into 206 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 207 if err != nil { 208 return false, err 209 } 210 defer out.Close() 211 212 var writer io.Writer = out 213 if strings.HasSuffix(file, ".gz") { 214 writer = gzip.NewWriter(writer) 215 defer writer.(*gzip.Writer).Close() 216 } 217 218 // Export the blockchain 219 if err := api.eth.BlockChain().Export(writer); err != nil { 220 return false, err 221 } 222 return true, nil 223 } 224 225 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 226 for _, b := range bs { 227 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 228 return false 229 } 230 } 231 232 return true 233 } 234 235 // ImportChain imports a blockchain from a local file. 236 func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) { 237 // Make sure the can access the file to import 238 in, err := os.Open(file) 239 if err != nil { 240 return false, err 241 } 242 defer in.Close() 243 244 var reader io.Reader = in 245 if strings.HasSuffix(file, ".gz") { 246 if reader, err = gzip.NewReader(reader); err != nil { 247 return false, err 248 } 249 } 250 251 // Run actual the import in pre-configured batches 252 stream := rlp.NewStream(reader, 0) 253 254 blocks, index := make([]*types.Block, 0, 2500), 0 255 for batch := 0; ; batch++ { 256 // Load a batch of blocks from the input file 257 for len(blocks) < cap(blocks) { 258 block := new(types.Block) 259 if err := stream.Decode(block); err == io.EOF { 260 break 261 } else if err != nil { 262 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 263 } 264 blocks = append(blocks, block) 265 index++ 266 } 267 if len(blocks) == 0 { 268 break 269 } 270 271 if hasAllBlocks(api.eth.BlockChain(), blocks) { 272 blocks = blocks[:0] 273 continue 274 } 275 // Import the batch and reset the buffer 276 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 277 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 278 } 279 blocks = blocks[:0] 280 } 281 return true, nil 282 } 283 284 // PublicDebugAPI is the collection of Ethereum full node APIs exposed 285 // over the public debugging endpoint. 286 type PublicDebugAPI struct { 287 eth *Ethereum 288 } 289 290 // NewPublicDebugAPI creates a new API definition for the full node- 291 // related public debug methods of the Ethereum service. 292 func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { 293 return &PublicDebugAPI{eth: eth} 294 } 295 296 // DumpBlock retrieves the entire state of the database at a given block. 297 // Quorum adds an additional parameter to support private state dump 298 func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber, typ *string) (state.Dump, error) { 299 publicState, privateState, err := api.getStateDbsFromBlockNumber(blockNr) 300 if err != nil { 301 return state.Dump{}, err 302 } 303 304 if typ != nil && *typ == "private" { 305 return privateState.RawDump(false, false, true), nil 306 } 307 return publicState.RawDump(false, false, true), nil 308 } 309 310 // Quorum 311 // DumpAddress retrieves the state of an address at a given block. 312 // Quorum adds an additional parameter to support private state dump 313 func (api *PublicDebugAPI) DumpAddress(address common.Address, blockNr rpc.BlockNumber) (state.DumpAccount, error) { 314 publicState, privateState, err := api.getStateDbsFromBlockNumber(blockNr) 315 if err != nil { 316 return state.DumpAccount{}, err 317 } 318 319 if accountDump, ok := privateState.DumpAddress(address); ok { 320 return accountDump, nil 321 } 322 if accountDump, ok := publicState.DumpAddress(address); ok { 323 return accountDump, nil 324 } 325 return state.DumpAccount{}, errors.New("error retrieving state") 326 } 327 328 //Quorum 329 //Taken from DumpBlock, as it was reused in DumpAddress. 330 //Contains modifications from the original to return the private state db, as well as public. 331 func (api *PublicDebugAPI) getStateDbsFromBlockNumber(blockNr rpc.BlockNumber) (*state.StateDB, *state.StateDB, error) { 332 if blockNr == rpc.PendingBlockNumber { 333 // If we're dumping the pending state, we need to request 334 // both the pending block as well as the pending state from 335 // the miner and operate on those 336 _, publicState, privateState := api.eth.miner.Pending() 337 return publicState, privateState, nil 338 } 339 340 var block *types.Block 341 if blockNr == rpc.LatestBlockNumber { 342 block = api.eth.blockchain.CurrentBlock() 343 } else { 344 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 345 } 346 if block == nil { 347 return nil, nil, fmt.Errorf("block #%d not found", blockNr) 348 } 349 return api.eth.BlockChain().StateAt(block.Root()) 350 } 351 352 // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over 353 // the private debugging endpoint. 354 type PrivateDebugAPI struct { 355 eth *Ethereum 356 } 357 358 // NewPrivateDebugAPI creates a new API definition for the full node-related 359 // private debug methods of the Ethereum service. 360 func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI { 361 return &PrivateDebugAPI{eth: eth} 362 } 363 364 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 365 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 366 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 367 return preimage, nil 368 } 369 return nil, errors.New("unknown preimage") 370 } 371 372 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 373 type BadBlockArgs struct { 374 Hash common.Hash `json:"hash"` 375 Block map[string]interface{} `json:"block"` 376 RLP string `json:"rlp"` 377 } 378 379 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 380 // and returns them as a JSON list of block-hashes 381 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 382 blocks := api.eth.BlockChain().BadBlocks() 383 results := make([]*BadBlockArgs, len(blocks)) 384 385 var err error 386 for i, block := range blocks { 387 results[i] = &BadBlockArgs{ 388 Hash: block.Hash(), 389 } 390 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 391 results[i].RLP = err.Error() // Hacky, but hey, it works 392 } else { 393 results[i].RLP = fmt.Sprintf("0x%x", rlpBytes) 394 } 395 if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil { 396 results[i].Block = map[string]interface{}{"error": err.Error()} 397 } 398 } 399 return results, nil 400 } 401 402 // AccountRangeResult returns a mapping from the hash of an account addresses 403 // to its preimage. It will return the JSON null if no preimage is found. 404 // Since a query can return a limited amount of results, a "next" field is 405 // also present for paging. 406 type AccountRangeResult struct { 407 Accounts map[common.Hash]*common.Address `json:"accounts"` 408 Next common.Hash `json:"next"` 409 } 410 411 func accountRange(st state.Trie, start *common.Hash, maxResults int) (AccountRangeResult, error) { 412 if start == nil { 413 start = &common.Hash{0} 414 } 415 it := trie.NewIterator(st.NodeIterator(start.Bytes())) 416 result := AccountRangeResult{Accounts: make(map[common.Hash]*common.Address), Next: common.Hash{}} 417 418 if maxResults > AccountRangeMaxResults { 419 maxResults = AccountRangeMaxResults 420 } 421 422 for i := 0; i < maxResults && it.Next(); i++ { 423 if preimage := st.GetKey(it.Key); preimage != nil { 424 addr := &common.Address{} 425 addr.SetBytes(preimage) 426 result.Accounts[common.BytesToHash(it.Key)] = addr 427 } else { 428 result.Accounts[common.BytesToHash(it.Key)] = nil 429 } 430 } 431 432 if it.Next() { 433 result.Next = common.BytesToHash(it.Key) 434 } 435 436 return result, nil 437 } 438 439 // AccountRangeMaxResults is the maximum number of results to be returned per call 440 const AccountRangeMaxResults = 256 441 442 // AccountRange enumerates all accounts in the latest state 443 func (api *PrivateDebugAPI) AccountRange(ctx context.Context, start *common.Hash, maxResults int) (AccountRangeResult, error) { 444 var statedb *state.StateDB 445 var err error 446 block := api.eth.blockchain.CurrentBlock() 447 448 if len(block.Transactions()) == 0 { 449 statedb, _, err = api.computeStateDB(block, defaultTraceReexec) 450 if err != nil { 451 return AccountRangeResult{}, err 452 } 453 } else { 454 _, _, statedb, _, err = api.computeTxEnv(block.Hash(), len(block.Transactions())-1, 0) 455 if err != nil { 456 return AccountRangeResult{}, err 457 } 458 } 459 460 trie, err := statedb.Database().OpenTrie(block.Header().Root) 461 if err != nil { 462 return AccountRangeResult{}, err 463 } 464 465 return accountRange(trie, start, maxResults) 466 } 467 468 // StorageRangeResult is the result of a debug_storageRangeAt API call. 469 type StorageRangeResult struct { 470 Storage storageMap `json:"storage"` 471 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 472 } 473 474 type storageMap map[common.Hash]storageEntry 475 476 type storageEntry struct { 477 Key *common.Hash `json:"key"` 478 Value common.Hash `json:"value"` 479 } 480 481 // StorageRangeAt returns the storage at the given block height and transaction index. 482 func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 483 _, _, statedb, _, err := api.computeTxEnv(blockHash, txIndex, 0) 484 if err != nil { 485 return StorageRangeResult{}, err 486 } 487 st := statedb.StorageTrie(contractAddress) 488 if st == nil { 489 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 490 } 491 return storageRangeAt(st, keyStart, maxResult) 492 } 493 494 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 495 it := trie.NewIterator(st.NodeIterator(start)) 496 result := StorageRangeResult{Storage: storageMap{}} 497 for i := 0; i < maxResult && it.Next(); i++ { 498 _, content, _, err := rlp.Split(it.Value) 499 if err != nil { 500 return StorageRangeResult{}, err 501 } 502 e := storageEntry{Value: common.BytesToHash(content)} 503 if preimage := st.GetKey(it.Key); preimage != nil { 504 preimage := common.BytesToHash(preimage) 505 e.Key = &preimage 506 } 507 result.Storage[common.BytesToHash(it.Key)] = e 508 } 509 // Add the 'next key' so clients can continue downloading. 510 if it.Next() { 511 next := common.BytesToHash(it.Key) 512 result.NextKey = &next 513 } 514 return result, nil 515 } 516 517 // GetModifiedAccountsByNumber returns all accounts that have changed between the 518 // two blocks specified. A change is defined as a difference in nonce, balance, 519 // code hash, or storage hash. 520 // 521 // With one parameter, returns the list of accounts modified in the specified block. 522 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 523 var startBlock, endBlock *types.Block 524 525 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 526 if startBlock == nil { 527 return nil, fmt.Errorf("start block %x not found", startNum) 528 } 529 530 if endNum == nil { 531 endBlock = startBlock 532 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 533 if startBlock == nil { 534 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 535 } 536 } else { 537 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 538 if endBlock == nil { 539 return nil, fmt.Errorf("end block %d not found", *endNum) 540 } 541 } 542 return api.getModifiedAccounts(startBlock, endBlock) 543 } 544 545 // GetModifiedAccountsByHash returns all accounts that have changed between the 546 // two blocks specified. A change is defined as a difference in nonce, balance, 547 // code hash, or storage hash. 548 // 549 // With one parameter, returns the list of accounts modified in the specified block. 550 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 551 var startBlock, endBlock *types.Block 552 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 553 if startBlock == nil { 554 return nil, fmt.Errorf("start block %x not found", startHash) 555 } 556 557 if endHash == nil { 558 endBlock = startBlock 559 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 560 if startBlock == nil { 561 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 562 } 563 } else { 564 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 565 if endBlock == nil { 566 return nil, fmt.Errorf("end block %x not found", *endHash) 567 } 568 } 569 return api.getModifiedAccounts(startBlock, endBlock) 570 } 571 572 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 573 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 574 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 575 } 576 statedb, _ := api.eth.BlockChain().StateCache() 577 triedb := statedb.TrieDB() 578 579 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb) 580 if err != nil { 581 return nil, err 582 } 583 newTrie, err := trie.NewSecure(endBlock.Root(), triedb) 584 if err != nil { 585 return nil, err 586 } 587 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 588 iter := trie.NewIterator(diff) 589 590 var dirty []common.Address 591 for iter.Next() { 592 key := newTrie.GetKey(iter.Key) 593 if key == nil { 594 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 595 } 596 dirty = append(dirty, common.BytesToAddress(key)) 597 } 598 return dirty, nil 599 }