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