github.com/MaynardMiner/ethereumprogpow@v1.8.23/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/ethereumprogpow/ethereumprogpow/common" 32 "github.com/ethereumprogpow/ethereumprogpow/common/hexutil" 33 "github.com/ethereumprogpow/ethereumprogpow/core" 34 "github.com/ethereumprogpow/ethereumprogpow/core/rawdb" 35 "github.com/ethereumprogpow/ethereumprogpow/core/state" 36 "github.com/ethereumprogpow/ethereumprogpow/core/types" 37 "github.com/ethereumprogpow/ethereumprogpow/internal/ethapi" 38 "github.com/ethereumprogpow/ethereumprogpow/params" 39 "github.com/ethereumprogpow/ethereumprogpow/rlp" 40 "github.com/ethereumprogpow/ethereumprogpow/rpc" 41 "github.com/ethereumprogpow/ethereumprogpow/trie" 42 ) 43 44 // PublicEthereumAPI provides an API to access Ethereum full node-related 45 // information. 46 type PublicEthereumAPI struct { 47 e *Ethereum 48 } 49 50 // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. 51 func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { 52 return &PublicEthereumAPI{e} 53 } 54 55 // Etherbase is the address that mining rewards will be send to 56 func (api *PublicEthereumAPI) Etherbase() (common.Address, error) { 57 return api.e.Etherbase() 58 } 59 60 // Coinbase is the address that mining rewards will be send to (alias for Etherbase) 61 func (api *PublicEthereumAPI) Coinbase() (common.Address, error) { 62 return api.Etherbase() 63 } 64 65 // Hashrate returns the POW hashrate 66 func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 { 67 return hexutil.Uint64(api.e.Miner().HashRate()) 68 } 69 70 // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config. 71 func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 { 72 chainID := new(big.Int) 73 if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) { 74 chainID = config.ChainID 75 } 76 return (hexutil.Uint64)(chainID.Uint64()) 77 } 78 79 // PublicMinerAPI provides an API to control the miner. 80 // It offers only methods that operate on data that pose no security risk when it is publicly accessible. 81 type PublicMinerAPI struct { 82 e *Ethereum 83 } 84 85 // NewPublicMinerAPI create a new PublicMinerAPI instance. 86 func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI { 87 return &PublicMinerAPI{e} 88 } 89 90 // Mining returns an indication if this node is currently mining. 91 func (api *PublicMinerAPI) Mining() bool { 92 return api.e.IsMining() 93 } 94 95 // PrivateMinerAPI provides private RPC methods to control the miner. 96 // These methods can be abused by external users and must be considered insecure for use by untrusted users. 97 type PrivateMinerAPI struct { 98 e *Ethereum 99 } 100 101 // NewPrivateMinerAPI create a new RPC service which controls the miner of this node. 102 func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { 103 return &PrivateMinerAPI{e: e} 104 } 105 106 // Start starts the miner with the given number of threads. If threads is nil, 107 // the number of workers started is equal to the number of logical CPUs that are 108 // usable by this process. If mining is already running, this method adjust the 109 // number of threads allowed to use and updates the minimum price required by the 110 // transaction pool. 111 func (api *PrivateMinerAPI) Start(threads *int) error { 112 if threads == nil { 113 return api.e.StartMining(runtime.NumCPU()) 114 } 115 return api.e.StartMining(*threads) 116 } 117 118 // Stop terminates the miner, both at the consensus engine level as well as at 119 // the block creation level. 120 func (api *PrivateMinerAPI) Stop() { 121 api.e.StopMining() 122 } 123 124 // SetExtra sets the extra data string that is included when this miner mines a block. 125 func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) { 126 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 127 return false, err 128 } 129 return true, nil 130 } 131 132 // SetGasPrice sets the minimum accepted gas price for the miner. 133 func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 134 api.e.lock.Lock() 135 api.e.gasPrice = (*big.Int)(&gasPrice) 136 api.e.lock.Unlock() 137 138 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 139 return true 140 } 141 142 // SetEtherbase sets the etherbase of the miner 143 func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool { 144 api.e.SetEtherbase(etherbase) 145 return true 146 } 147 148 // SetRecommitInterval updates the interval for miner sealing work recommitting. 149 func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { 150 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 151 } 152 153 // GetHashrate returns the current hashrate of the miner. 154 func (api *PrivateMinerAPI) GetHashrate() uint64 { 155 return api.e.miner.HashRate() 156 } 157 158 // PrivateAdminAPI is the collection of Ethereum full node-related APIs 159 // exposed over the private admin endpoint. 160 type PrivateAdminAPI struct { 161 eth *Ethereum 162 } 163 164 // NewPrivateAdminAPI creates a new API definition for the full node private 165 // admin methods of the Ethereum service. 166 func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { 167 return &PrivateAdminAPI{eth: eth} 168 } 169 170 // ExportChain exports the current blockchain into a local file. 171 func (api *PrivateAdminAPI) ExportChain(file string) (bool, error) { 172 // Make sure we can create the file to export into 173 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 174 if err != nil { 175 return false, err 176 } 177 defer out.Close() 178 179 var writer io.Writer = out 180 if strings.HasSuffix(file, ".gz") { 181 writer = gzip.NewWriter(writer) 182 defer writer.(*gzip.Writer).Close() 183 } 184 185 // Export the blockchain 186 if err := api.eth.BlockChain().Export(writer); err != nil { 187 return false, err 188 } 189 return true, nil 190 } 191 192 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 193 for _, b := range bs { 194 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 195 return false 196 } 197 } 198 199 return true 200 } 201 202 // ImportChain imports a blockchain from a local file. 203 func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) { 204 // Make sure the can access the file to import 205 in, err := os.Open(file) 206 if err != nil { 207 return false, err 208 } 209 defer in.Close() 210 211 var reader io.Reader = in 212 if strings.HasSuffix(file, ".gz") { 213 if reader, err = gzip.NewReader(reader); err != nil { 214 return false, err 215 } 216 } 217 218 // Run actual the import in pre-configured batches 219 stream := rlp.NewStream(reader, 0) 220 221 blocks, index := make([]*types.Block, 0, 2500), 0 222 for batch := 0; ; batch++ { 223 // Load a batch of blocks from the input file 224 for len(blocks) < cap(blocks) { 225 block := new(types.Block) 226 if err := stream.Decode(block); err == io.EOF { 227 break 228 } else if err != nil { 229 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 230 } 231 blocks = append(blocks, block) 232 index++ 233 } 234 if len(blocks) == 0 { 235 break 236 } 237 238 if hasAllBlocks(api.eth.BlockChain(), blocks) { 239 blocks = blocks[:0] 240 continue 241 } 242 // Import the batch and reset the buffer 243 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 244 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 245 } 246 blocks = blocks[:0] 247 } 248 return true, nil 249 } 250 251 // PublicDebugAPI is the collection of Ethereum full node APIs exposed 252 // over the public debugging endpoint. 253 type PublicDebugAPI struct { 254 eth *Ethereum 255 } 256 257 // NewPublicDebugAPI creates a new API definition for the full node- 258 // related public debug methods of the Ethereum service. 259 func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { 260 return &PublicDebugAPI{eth: eth} 261 } 262 263 // DumpBlock retrieves the entire state of the database at a given block. 264 func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { 265 if blockNr == rpc.PendingBlockNumber { 266 // If we're dumping the pending state, we need to request 267 // both the pending block as well as the pending state from 268 // the miner and operate on those 269 _, stateDb := api.eth.miner.Pending() 270 return stateDb.RawDump(), nil 271 } 272 var block *types.Block 273 if blockNr == rpc.LatestBlockNumber { 274 block = api.eth.blockchain.CurrentBlock() 275 } else { 276 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 277 } 278 if block == nil { 279 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 280 } 281 stateDb, err := api.eth.BlockChain().StateAt(block.Root()) 282 if err != nil { 283 return state.Dump{}, err 284 } 285 return stateDb.RawDump(), nil 286 } 287 288 // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over 289 // the private debugging endpoint. 290 type PrivateDebugAPI struct { 291 config *params.ChainConfig 292 eth *Ethereum 293 } 294 295 // NewPrivateDebugAPI creates a new API definition for the full node-related 296 // private debug methods of the Ethereum service. 297 func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI { 298 return &PrivateDebugAPI{config: config, eth: eth} 299 } 300 301 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 302 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 303 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 304 return preimage, nil 305 } 306 return nil, errors.New("unknown preimage") 307 } 308 309 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 310 type BadBlockArgs struct { 311 Hash common.Hash `json:"hash"` 312 Block map[string]interface{} `json:"block"` 313 RLP string `json:"rlp"` 314 } 315 316 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 317 // and returns them as a JSON list of block-hashes 318 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 319 blocks := api.eth.BlockChain().BadBlocks() 320 results := make([]*BadBlockArgs, len(blocks)) 321 322 var err error 323 for i, block := range blocks { 324 results[i] = &BadBlockArgs{ 325 Hash: block.Hash(), 326 } 327 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 328 results[i].RLP = err.Error() // Hacky, but hey, it works 329 } else { 330 results[i].RLP = fmt.Sprintf("0x%x", rlpBytes) 331 } 332 if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil { 333 results[i].Block = map[string]interface{}{"error": err.Error()} 334 } 335 } 336 return results, nil 337 } 338 339 // StorageRangeResult is the result of a debug_storageRangeAt API call. 340 type StorageRangeResult struct { 341 Storage storageMap `json:"storage"` 342 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 343 } 344 345 type storageMap map[common.Hash]storageEntry 346 347 type storageEntry struct { 348 Key *common.Hash `json:"key"` 349 Value common.Hash `json:"value"` 350 } 351 352 // StorageRangeAt returns the storage at the given block height and transaction index. 353 func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 354 _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0) 355 if err != nil { 356 return StorageRangeResult{}, err 357 } 358 st := statedb.StorageTrie(contractAddress) 359 if st == nil { 360 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 361 } 362 return storageRangeAt(st, keyStart, maxResult) 363 } 364 365 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 366 it := trie.NewIterator(st.NodeIterator(start)) 367 result := StorageRangeResult{Storage: storageMap{}} 368 for i := 0; i < maxResult && it.Next(); i++ { 369 _, content, _, err := rlp.Split(it.Value) 370 if err != nil { 371 return StorageRangeResult{}, err 372 } 373 e := storageEntry{Value: common.BytesToHash(content)} 374 if preimage := st.GetKey(it.Key); preimage != nil { 375 preimage := common.BytesToHash(preimage) 376 e.Key = &preimage 377 } 378 result.Storage[common.BytesToHash(it.Key)] = e 379 } 380 // Add the 'next key' so clients can continue downloading. 381 if it.Next() { 382 next := common.BytesToHash(it.Key) 383 result.NextKey = &next 384 } 385 return result, nil 386 } 387 388 // GetModifiedAccountsByNumber returns all accounts that have changed between the 389 // two blocks specified. A change is defined as a difference in nonce, balance, 390 // code hash, or storage hash. 391 // 392 // With one parameter, returns the list of accounts modified in the specified block. 393 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 394 var startBlock, endBlock *types.Block 395 396 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 397 if startBlock == nil { 398 return nil, fmt.Errorf("start block %x not found", startNum) 399 } 400 401 if endNum == nil { 402 endBlock = startBlock 403 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 404 if startBlock == nil { 405 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 406 } 407 } else { 408 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 409 if endBlock == nil { 410 return nil, fmt.Errorf("end block %d not found", *endNum) 411 } 412 } 413 return api.getModifiedAccounts(startBlock, endBlock) 414 } 415 416 // GetModifiedAccountsByHash returns all accounts that have changed between the 417 // two blocks specified. A change is defined as a difference in nonce, balance, 418 // code hash, or storage hash. 419 // 420 // With one parameter, returns the list of accounts modified in the specified block. 421 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 422 var startBlock, endBlock *types.Block 423 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 424 if startBlock == nil { 425 return nil, fmt.Errorf("start block %x not found", startHash) 426 } 427 428 if endHash == nil { 429 endBlock = startBlock 430 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 431 if startBlock == nil { 432 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 433 } 434 } else { 435 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 436 if endBlock == nil { 437 return nil, fmt.Errorf("end block %x not found", *endHash) 438 } 439 } 440 return api.getModifiedAccounts(startBlock, endBlock) 441 } 442 443 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 444 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 445 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 446 } 447 triedb := api.eth.BlockChain().StateCache().TrieDB() 448 449 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb, 0) 450 if err != nil { 451 return nil, err 452 } 453 newTrie, err := trie.NewSecure(endBlock.Root(), triedb, 0) 454 if err != nil { 455 return nil, err 456 } 457 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 458 iter := trie.NewIterator(diff) 459 460 var dirty []common.Address 461 for iter.Next() { 462 key := newTrie.GetKey(iter.Key) 463 if key == nil { 464 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 465 } 466 dirty = append(dirty, common.BytesToAddress(key)) 467 } 468 return dirty, nil 469 }