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