github.com/core-coin/go-core/v2@v2.1.9/xcb/api.go (about) 1 // Copyright 2023 by the Authors 2 // This file is part of the go-core library. 3 // 4 // The go-core 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-core 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-core library. If not, see <http://www.gnu.org/licenses/>. 16 17 package xcb 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/core-coin/go-core/v2/internal/xcbapi" 32 33 "github.com/core-coin/go-core/v2/common" 34 "github.com/core-coin/go-core/v2/common/hexutil" 35 "github.com/core-coin/go-core/v2/core" 36 "github.com/core-coin/go-core/v2/core/rawdb" 37 "github.com/core-coin/go-core/v2/core/state" 38 "github.com/core-coin/go-core/v2/core/types" 39 "github.com/core-coin/go-core/v2/rlp" 40 "github.com/core-coin/go-core/v2/rpc" 41 "github.com/core-coin/go-core/v2/trie" 42 ) 43 44 // PublicCoreAPI provides an API to access Core full node-related 45 // information. 46 type PublicCoreAPI struct { 47 e *Core 48 } 49 50 // NewPublicCoreAPI creates a new Core protocol API for full nodes. 51 func NewPublicCoreAPI(e *Core) *PublicCoreAPI { 52 return &PublicCoreAPI{e} 53 } 54 55 // Corebase is the address that mining rewards will be send to 56 func (api *PublicCoreAPI) Corebase() (common.Address, error) { 57 return api.e.Corebase() 58 } 59 60 // Coinbase is the address that mining rewards will be send to (alias for Corebase) 61 func (api *PublicCoreAPI) Coinbase() (common.Address, error) { 62 return api.Corebase() 63 } 64 65 // Hashrate returns the POW hashrate 66 func (api *PublicCoreAPI) Hashrate() hexutil.Uint64 { 67 return hexutil.Uint64(api.e.Miner().HashRate()) 68 } 69 70 // NetworkId is the CIP-155 replay-protection chain id for the current core chain config. 71 func (api *PublicCoreAPI) NetworkId() hexutil.Uint64 { 72 networkID := new(big.Int) 73 config := api.e.blockchain.Config() 74 networkID = config.NetworkID 75 return (hexutil.Uint64)(networkID.Uint64()) 76 } 77 78 // PublicMinerAPI provides an API to control the miner. 79 // It offers only methods that operate on data that pose no security risk when it is publicly accessible. 80 type PublicMinerAPI struct { 81 e *Core 82 } 83 84 // NewPublicMinerAPI create a new PublicMinerAPI instance. 85 func NewPublicMinerAPI(e *Core) *PublicMinerAPI { 86 return &PublicMinerAPI{e} 87 } 88 89 // Mining returns an indication if this node is currently mining. 90 func (api *PublicMinerAPI) Mining() bool { 91 return api.e.IsMining() 92 } 93 94 // PrivateMinerAPI provides private RPC methods to control the miner. 95 // These methods can be abused by external users and must be considered insecure for use by untrusted users. 96 type PrivateMinerAPI struct { 97 e *Core 98 } 99 100 // NewPrivateMinerAPI create a new RPC service which controls the miner of this node. 101 func NewPrivateMinerAPI(e *Core) *PrivateMinerAPI { 102 return &PrivateMinerAPI{e: e} 103 } 104 105 // Start starts the miner with the given number of threads. If threads is nil, 106 // the number of workers started is equal to the number of logical CPUs that are 107 // usable by this process. If mining is already running, this method adjust the 108 // number of threads allowed to use and updates the minimum price required by the 109 // transaction pool. 110 func (api *PrivateMinerAPI) Start(threads *int) error { 111 if threads == nil { 112 return api.e.StartMining(runtime.NumCPU()) 113 } 114 return api.e.StartMining(*threads) 115 } 116 117 // Stop terminates the miner, both at the consensus engine level as well as at 118 // the block creation level. 119 func (api *PrivateMinerAPI) Stop() { 120 api.e.StopMining() 121 } 122 123 // SetExtra sets the extra data string that is included when this miner mines a block. 124 func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) { 125 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 126 return false, err 127 } 128 return true, nil 129 } 130 131 // SetEnergyPrice sets the minimum accepted energy price for the miner. 132 func (api *PrivateMinerAPI) SetEnergyPrice(energyPrice hexutil.Big) bool { 133 api.e.lock.Lock() 134 api.e.energyPrice = (*big.Int)(&energyPrice) 135 api.e.lock.Unlock() 136 137 api.e.txPool.SetEnergyPrice((*big.Int)(&energyPrice)) 138 return true 139 } 140 141 // SetCorebase sets the corebase of the miner 142 func (api *PrivateMinerAPI) SetCorebase(corebase common.Address) bool { 143 api.e.SetCorebase(corebase) 144 return true 145 } 146 147 // SetRecommitInterval updates the interval for miner sealing work recommitting. 148 func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { 149 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 150 } 151 152 // GetHashrate returns the current hashrate of the miner. 153 func (api *PrivateMinerAPI) GetHashrate() uint64 { 154 return api.e.miner.HashRate() 155 } 156 157 // PrivateAdminAPI is the collection of Core full node-related APIs 158 // exposed over the private admin endpoint. 159 type PrivateAdminAPI struct { 160 xcb *Core 161 } 162 163 // NewPrivateAdminAPI creates a new API definition for the full node private 164 // admin methods of the Core service. 165 func NewPrivateAdminAPI(xcb *Core) *PrivateAdminAPI { 166 return &PrivateAdminAPI{xcb: xcb} 167 } 168 169 // ExportChain exports the current blockchain into a local file, 170 // or a range of blocks if first and last are non-nil 171 func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { 172 if first == nil && last != nil { 173 return false, errors.New("last cannot be specified without first") 174 } 175 if first != nil && last == nil { 176 head := api.xcb.BlockChain().CurrentHeader().Number.Uint64() 177 last = &head 178 } 179 if _, err := os.Stat(file); err == nil { 180 // File already exists. Allowing overwrite could be a DoS vecotor, 181 // since the 'file' may point to arbitrary paths on the drive 182 return false, errors.New("location would overwrite an existing file") 183 } 184 // Make sure we can create the file to export into 185 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 186 if err != nil { 187 return false, err 188 } 189 defer out.Close() 190 191 var writer io.Writer = out 192 if strings.HasSuffix(file, ".gz") { 193 writer = gzip.NewWriter(writer) 194 defer writer.(*gzip.Writer).Close() 195 } 196 197 // Export the blockchain 198 if first != nil { 199 if err := api.xcb.BlockChain().ExportN(writer, *first, *last); err != nil { 200 return false, err 201 } 202 } else if err := api.xcb.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.xcb.BlockChain(), blocks) { 255 blocks = blocks[:0] 256 continue 257 } 258 // Import the batch and reset the buffer 259 if _, err := api.xcb.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 Core full node APIs exposed 268 // over the public debugging endpoint. 269 type PublicDebugAPI struct { 270 xcb *Core 271 } 272 273 // NewPublicDebugAPI creates a new API definition for the full node- 274 // related public debug methods of the Core service. 275 func NewPublicDebugAPI(xcb *Core) *PublicDebugAPI { 276 return &PublicDebugAPI{xcb: xcb} 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.xcb.miner.Pending() 286 return stateDb.RawDump(false, false, true), nil 287 } 288 var block *types.Block 289 if blockNr == rpc.LatestBlockNumber { 290 block = api.xcb.blockchain.CurrentBlock() 291 } else { 292 block = api.xcb.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.xcb.BlockChain().StateAt(block.Root()) 298 if err != nil { 299 return state.Dump{}, err 300 } 301 return stateDb.RawDump(false, false, true), nil 302 } 303 304 // PrivateDebugAPI is the collection of Core full node APIs exposed over 305 // the private debugging endpoint. 306 type PrivateDebugAPI struct { 307 xcb *Core 308 } 309 310 // NewPrivateDebugAPI creates a new API definition for the full node-related 311 // private debug methods of the Core service. 312 func NewPrivateDebugAPI(xcb *Core) *PrivateDebugAPI { 313 return &PrivateDebugAPI{xcb: xcb} 314 } 315 316 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 317 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 318 if preimage := rawdb.ReadPreimage(api.xcb.ChainDb(), hash); preimage != nil { 319 return preimage, nil 320 } 321 return nil, errors.New("unknown preimage") 322 } 323 324 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 325 type BadBlockArgs struct { 326 Hash common.Hash `json:"hash"` 327 Block map[string]interface{} `json:"block"` 328 RLP string `json:"rlp"` 329 } 330 331 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 332 // and returns them as a JSON list of block-hashes 333 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 334 blocks := api.xcb.BlockChain().BadBlocks() 335 results := make([]*BadBlockArgs, len(blocks)) 336 337 var err error 338 for i, block := range blocks { 339 results[i] = &BadBlockArgs{ 340 Hash: block.Hash(), 341 } 342 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 343 results[i].RLP = err.Error() // Hacky, but hey, it works 344 } else { 345 results[i].RLP = fmt.Sprintf("0x%x", rlpBytes) 346 } 347 if results[i].Block, err = xcbapi.RPCMarshalBlock(block, true, true, big.NewInt(int64(api.xcb.config.NetworkId))); err != nil { 348 results[i].Block = map[string]interface{}{"error": err.Error()} 349 } 350 } 351 return results, nil 352 } 353 354 // AccountRangeMaxResults is the maximum number of results to be returned per call 355 const AccountRangeMaxResults = 256 356 357 // AccountRange enumerates all accounts in the given block and start point in paging request 358 func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 359 var stateDb *state.StateDB 360 var err error 361 362 if number, ok := blockNrOrHash.Number(); ok { 363 if number == rpc.PendingBlockNumber { 364 // If we're dumping the pending state, we need to request 365 // both the pending block as well as the pending state from 366 // the miner and operate on those 367 _, stateDb = api.xcb.miner.Pending() 368 } else { 369 var block *types.Block 370 if number == rpc.LatestBlockNumber { 371 block = api.xcb.blockchain.CurrentBlock() 372 } else { 373 block = api.xcb.blockchain.GetBlockByNumber(uint64(number)) 374 } 375 if block == nil { 376 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 377 } 378 stateDb, err = api.xcb.BlockChain().StateAt(block.Root()) 379 if err != nil { 380 return state.IteratorDump{}, err 381 } 382 } 383 } else if hash, ok := blockNrOrHash.Hash(); ok { 384 block := api.xcb.blockchain.GetBlockByHash(hash) 385 if block == nil { 386 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 387 } 388 stateDb, err = api.xcb.BlockChain().StateAt(block.Root()) 389 if err != nil { 390 return state.IteratorDump{}, err 391 } 392 } else { 393 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 394 } 395 396 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 397 maxResults = AccountRangeMaxResults 398 } 399 return stateDb.IteratorDump(nocode, nostorage, incompletes, start, maxResults), nil 400 } 401 402 // StorageRangeResult is the result of a debug_storageRangeAt API call. 403 type StorageRangeResult struct { 404 Storage storageMap `json:"storage"` 405 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 406 } 407 408 type storageMap map[common.Hash]storageEntry 409 410 type storageEntry struct { 411 Key *common.Hash `json:"key"` 412 Value common.Hash `json:"value"` 413 } 414 415 // StorageRangeAt returns the storage at the given block height and transaction index. 416 func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 417 // Retrieve the block 418 block := api.xcb.blockchain.GetBlockByHash(blockHash) 419 if block == nil { 420 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 421 } 422 _, _, statedb, err := api.computeTxEnv(block, txIndex, 0) 423 if err != nil { 424 return StorageRangeResult{}, err 425 } 426 st := statedb.StorageTrie(contractAddress) 427 if st == nil { 428 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 429 } 430 return storageRangeAt(st, keyStart, maxResult) 431 } 432 433 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 434 it := trie.NewIterator(st.NodeIterator(start)) 435 result := StorageRangeResult{Storage: storageMap{}} 436 for i := 0; i < maxResult && it.Next(); i++ { 437 _, content, _, err := rlp.Split(it.Value) 438 if err != nil { 439 return StorageRangeResult{}, err 440 } 441 e := storageEntry{Value: common.BytesToHash(content)} 442 if preimage := st.GetKey(it.Key); preimage != nil { 443 preimage := common.BytesToHash(preimage) 444 e.Key = &preimage 445 } 446 result.Storage[common.BytesToHash(it.Key)] = e 447 } 448 // Add the 'next key' so clients can continue downloading. 449 if it.Next() { 450 next := common.BytesToHash(it.Key) 451 result.NextKey = &next 452 } 453 return result, nil 454 } 455 456 // GetModifiedAccountsByNumber returns all accounts that have changed between the 457 // two blocks specified. A change is defined as a difference in nonce, balance, 458 // code hash, or storage hash. 459 // 460 // With one parameter, returns the list of accounts modified in the specified block. 461 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 462 var startBlock, endBlock *types.Block 463 464 startBlock = api.xcb.blockchain.GetBlockByNumber(startNum) 465 if startBlock == nil { 466 return nil, fmt.Errorf("start block %x not found", startNum) 467 } 468 469 if endNum == nil { 470 endBlock = startBlock 471 startBlock = api.xcb.blockchain.GetBlockByHash(startBlock.ParentHash()) 472 if startBlock == nil { 473 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 474 } 475 } else { 476 endBlock = api.xcb.blockchain.GetBlockByNumber(*endNum) 477 if endBlock == nil { 478 return nil, fmt.Errorf("end block %d not found", *endNum) 479 } 480 } 481 return api.getModifiedAccounts(startBlock, endBlock) 482 } 483 484 // GetModifiedAccountsByHash returns all accounts that have changed between the 485 // two blocks specified. A change is defined as a difference in nonce, balance, 486 // code hash, or storage hash. 487 // 488 // With one parameter, returns the list of accounts modified in the specified block. 489 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 490 var startBlock, endBlock *types.Block 491 startBlock = api.xcb.blockchain.GetBlockByHash(startHash) 492 if startBlock == nil { 493 return nil, fmt.Errorf("start block %x not found", startHash) 494 } 495 496 if endHash == nil { 497 endBlock = startBlock 498 startBlock = api.xcb.blockchain.GetBlockByHash(startBlock.ParentHash()) 499 if startBlock == nil { 500 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 501 } 502 } else { 503 endBlock = api.xcb.blockchain.GetBlockByHash(*endHash) 504 if endBlock == nil { 505 return nil, fmt.Errorf("end block %x not found", *endHash) 506 } 507 } 508 return api.getModifiedAccounts(startBlock, endBlock) 509 } 510 511 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 512 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 513 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 514 } 515 triedb := api.xcb.BlockChain().StateCache().TrieDB() 516 517 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb) 518 if err != nil { 519 return nil, err 520 } 521 newTrie, err := trie.NewSecure(endBlock.Root(), triedb) 522 if err != nil { 523 return nil, err 524 } 525 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 526 iter := trie.NewIterator(diff) 527 528 var dirty []common.Address 529 for iter.Next() { 530 key := newTrie.GetKey(iter.Key) 531 if key == nil { 532 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 533 } 534 dirty = append(dirty, common.BytesToAddress(key)) 535 } 536 return dirty, nil 537 }