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