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