github.com/calmw/ethereum@v0.1.1/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/calmw/ethereum/common" 31 "github.com/calmw/ethereum/common/hexutil" 32 "github.com/calmw/ethereum/core" 33 "github.com/calmw/ethereum/core/rawdb" 34 "github.com/calmw/ethereum/core/state" 35 "github.com/calmw/ethereum/core/types" 36 "github.com/calmw/ethereum/internal/ethapi" 37 "github.com/calmw/ethereum/log" 38 "github.com/calmw/ethereum/rlp" 39 "github.com/calmw/ethereum/rpc" 40 "github.com/calmw/ethereum/trie" 41 ) 42 43 // EthereumAPI provides an API to access Ethereum full node-related information. 44 type EthereumAPI struct { 45 e *Ethereum 46 } 47 48 // NewEthereumAPI creates a new Ethereum protocol API for full nodes. 49 func NewEthereumAPI(e *Ethereum) *EthereumAPI { 50 return &EthereumAPI{e} 51 } 52 53 // Etherbase is the address that mining rewards will be send to. 54 func (api *EthereumAPI) 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 *EthereumAPI) Coinbase() (common.Address, error) { 60 return api.Etherbase() 61 } 62 63 // Hashrate returns the POW hashrate. 64 func (api *EthereumAPI) Hashrate() hexutil.Uint64 { 65 return hexutil.Uint64(api.e.Miner().Hashrate()) 66 } 67 68 // Mining returns an indication if this node is currently mining. 69 func (api *EthereumAPI) Mining() bool { 70 return api.e.IsMining() 71 } 72 73 // MinerAPI provides an API to control the miner. 74 type MinerAPI struct { 75 e *Ethereum 76 } 77 78 // NewMinerAPI create a new MinerAPI instance. 79 func NewMinerAPI(e *Ethereum) *MinerAPI { 80 return &MinerAPI{e} 81 } 82 83 // Start starts the miner with the given number of threads. If threads is nil, 84 // the number of workers started is equal to the number of logical CPUs that are 85 // usable by this process. If mining is already running, this method adjust the 86 // number of threads allowed to use and updates the minimum price required by the 87 // transaction pool. 88 func (api *MinerAPI) Start() error { 89 return api.e.StartMining() 90 } 91 92 // Stop terminates the miner, both at the consensus engine level as well as at 93 // the block creation level. 94 func (api *MinerAPI) Stop() { 95 api.e.StopMining() 96 } 97 98 // SetExtra sets the extra data string that is included when this miner mines a block. 99 func (api *MinerAPI) SetExtra(extra string) (bool, error) { 100 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 101 return false, err 102 } 103 return true, nil 104 } 105 106 // SetGasPrice sets the minimum accepted gas price for the miner. 107 func (api *MinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 108 api.e.lock.Lock() 109 api.e.gasPrice = (*big.Int)(&gasPrice) 110 api.e.lock.Unlock() 111 112 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 113 return true 114 } 115 116 // SetGasLimit sets the gaslimit to target towards during mining. 117 func (api *MinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool { 118 api.e.Miner().SetGasCeil(uint64(gasLimit)) 119 return true 120 } 121 122 // SetEtherbase sets the etherbase of the miner. 123 func (api *MinerAPI) SetEtherbase(etherbase common.Address) bool { 124 api.e.SetEtherbase(etherbase) 125 return true 126 } 127 128 // SetRecommitInterval updates the interval for miner sealing work recommitting. 129 func (api *MinerAPI) SetRecommitInterval(interval int) { 130 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 131 } 132 133 // AdminAPI is the collection of Ethereum full node related APIs for node 134 // administration. 135 type AdminAPI struct { 136 eth *Ethereum 137 } 138 139 // NewAdminAPI creates a new instance of AdminAPI. 140 func NewAdminAPI(eth *Ethereum) *AdminAPI { 141 return &AdminAPI{eth: eth} 142 } 143 144 // ExportChain exports the current blockchain into a local file, 145 // or a range of blocks if first and last are non-nil. 146 func (api *AdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { 147 if first == nil && last != nil { 148 return false, errors.New("last cannot be specified without first") 149 } 150 if first != nil && last == nil { 151 head := api.eth.BlockChain().CurrentHeader().Number.Uint64() 152 last = &head 153 } 154 if _, err := os.Stat(file); err == nil { 155 // File already exists. Allowing overwrite could be a DoS vector, 156 // since the 'file' may point to arbitrary paths on the drive. 157 return false, errors.New("location would overwrite an existing file") 158 } 159 // Make sure we can create the file to export into 160 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) 161 if err != nil { 162 return false, err 163 } 164 defer out.Close() 165 166 var writer io.Writer = out 167 if strings.HasSuffix(file, ".gz") { 168 writer = gzip.NewWriter(writer) 169 defer writer.(*gzip.Writer).Close() 170 } 171 172 // Export the blockchain 173 if first != nil { 174 if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil { 175 return false, err 176 } 177 } else if err := api.eth.BlockChain().Export(writer); err != nil { 178 return false, err 179 } 180 return true, nil 181 } 182 183 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 184 for _, b := range bs { 185 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 186 return false 187 } 188 } 189 190 return true 191 } 192 193 // ImportChain imports a blockchain from a local file. 194 func (api *AdminAPI) ImportChain(file string) (bool, error) { 195 // Make sure the can access the file to import 196 in, err := os.Open(file) 197 if err != nil { 198 return false, err 199 } 200 defer in.Close() 201 202 var reader io.Reader = in 203 if strings.HasSuffix(file, ".gz") { 204 if reader, err = gzip.NewReader(reader); err != nil { 205 return false, err 206 } 207 } 208 209 // Run actual the import in pre-configured batches 210 stream := rlp.NewStream(reader, 0) 211 212 blocks, index := make([]*types.Block, 0, 2500), 0 213 for batch := 0; ; batch++ { 214 // Load a batch of blocks from the input file 215 for len(blocks) < cap(blocks) { 216 block := new(types.Block) 217 if err := stream.Decode(block); err == io.EOF { 218 break 219 } else if err != nil { 220 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 221 } 222 blocks = append(blocks, block) 223 index++ 224 } 225 if len(blocks) == 0 { 226 break 227 } 228 229 if hasAllBlocks(api.eth.BlockChain(), blocks) { 230 blocks = blocks[:0] 231 continue 232 } 233 // Import the batch and reset the buffer 234 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 235 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 236 } 237 blocks = blocks[:0] 238 } 239 return true, nil 240 } 241 242 // DebugAPI is the collection of Ethereum full node APIs for debugging the 243 // protocol. 244 type DebugAPI struct { 245 eth *Ethereum 246 } 247 248 // NewDebugAPI creates a new DebugAPI instance. 249 func NewDebugAPI(eth *Ethereum) *DebugAPI { 250 return &DebugAPI{eth: eth} 251 } 252 253 // DumpBlock retrieves the entire state of the database at a given block. 254 func (api *DebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { 255 opts := &state.DumpConfig{ 256 OnlyWithAddresses: true, 257 Max: AccountRangeMaxResults, // Sanity limit over RPC 258 } 259 if blockNr == rpc.PendingBlockNumber { 260 // If we're dumping the pending state, we need to request 261 // both the pending block as well as the pending state from 262 // the miner and operate on those 263 _, stateDb := api.eth.miner.Pending() 264 return stateDb.RawDump(opts), nil 265 } 266 var header *types.Header 267 if blockNr == rpc.LatestBlockNumber { 268 header = api.eth.blockchain.CurrentBlock() 269 } else if blockNr == rpc.FinalizedBlockNumber { 270 header = api.eth.blockchain.CurrentFinalBlock() 271 } else if blockNr == rpc.SafeBlockNumber { 272 header = api.eth.blockchain.CurrentSafeBlock() 273 } else { 274 block := api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 275 if block == nil { 276 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 277 } 278 header = block.Header() 279 } 280 if header == nil { 281 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 282 } 283 stateDb, err := api.eth.BlockChain().StateAt(header.Root) 284 if err != nil { 285 return state.Dump{}, err 286 } 287 return stateDb.RawDump(opts), nil 288 } 289 290 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 291 func (api *DebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 292 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 293 return preimage, nil 294 } 295 return nil, errors.New("unknown preimage") 296 } 297 298 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 299 type BadBlockArgs struct { 300 Hash common.Hash `json:"hash"` 301 Block map[string]interface{} `json:"block"` 302 RLP string `json:"rlp"` 303 } 304 305 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 306 // and returns them as a JSON list of block hashes. 307 func (api *DebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 308 var ( 309 err error 310 blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb) 311 results = make([]*BadBlockArgs, 0, len(blocks)) 312 ) 313 for _, block := range blocks { 314 var ( 315 blockRlp string 316 blockJSON map[string]interface{} 317 ) 318 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 319 blockRlp = err.Error() // Hacky, but hey, it works 320 } else { 321 blockRlp = fmt.Sprintf("%#x", rlpBytes) 322 } 323 if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true, api.eth.APIBackend.ChainConfig()); err != nil { 324 blockJSON = map[string]interface{}{"error": err.Error()} 325 } 326 results = append(results, &BadBlockArgs{ 327 Hash: block.Hash(), 328 RLP: blockRlp, 329 Block: blockJSON, 330 }) 331 } 332 return results, nil 333 } 334 335 // AccountRangeMaxResults is the maximum number of results to be returned per call 336 const AccountRangeMaxResults = 256 337 338 // AccountRange enumerates all accounts in the given block and start point in paging request 339 func (api *DebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start hexutil.Bytes, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 340 var stateDb *state.StateDB 341 var err error 342 343 if number, ok := blockNrOrHash.Number(); ok { 344 if number == rpc.PendingBlockNumber { 345 // If we're dumping the pending state, we need to request 346 // both the pending block as well as the pending state from 347 // the miner and operate on those 348 _, stateDb = api.eth.miner.Pending() 349 } else { 350 var header *types.Header 351 if number == rpc.LatestBlockNumber { 352 header = api.eth.blockchain.CurrentBlock() 353 } else if number == rpc.FinalizedBlockNumber { 354 header = api.eth.blockchain.CurrentFinalBlock() 355 } else if number == rpc.SafeBlockNumber { 356 header = api.eth.blockchain.CurrentSafeBlock() 357 } else { 358 block := api.eth.blockchain.GetBlockByNumber(uint64(number)) 359 if block == nil { 360 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 361 } 362 header = block.Header() 363 } 364 if header == nil { 365 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 366 } 367 stateDb, err = api.eth.BlockChain().StateAt(header.Root) 368 if err != nil { 369 return state.IteratorDump{}, err 370 } 371 } 372 } else if hash, ok := blockNrOrHash.Hash(); ok { 373 block := api.eth.blockchain.GetBlockByHash(hash) 374 if block == nil { 375 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 376 } 377 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 378 if err != nil { 379 return state.IteratorDump{}, err 380 } 381 } else { 382 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 383 } 384 385 opts := &state.DumpConfig{ 386 SkipCode: nocode, 387 SkipStorage: nostorage, 388 OnlyWithAddresses: !incompletes, 389 Start: start, 390 Max: uint64(maxResults), 391 } 392 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 393 opts.Max = AccountRangeMaxResults 394 } 395 return stateDb.IteratorDump(opts), nil 396 } 397 398 // StorageRangeResult is the result of a debug_storageRangeAt API call. 399 type StorageRangeResult struct { 400 Storage storageMap `json:"storage"` 401 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 402 } 403 404 type storageMap map[common.Hash]storageEntry 405 406 type storageEntry struct { 407 Key *common.Hash `json:"key"` 408 Value common.Hash `json:"value"` 409 } 410 411 // StorageRangeAt returns the storage at the given block height and transaction index. 412 func (api *DebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 413 // Retrieve the block 414 block := api.eth.blockchain.GetBlockByHash(blockHash) 415 if block == nil { 416 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 417 } 418 _, _, statedb, release, err := api.eth.stateAtTransaction(ctx, block, txIndex, 0) 419 if err != nil { 420 return StorageRangeResult{}, err 421 } 422 defer release() 423 424 st, err := statedb.StorageTrie(contractAddress) 425 if err != nil { 426 return StorageRangeResult{}, err 427 } 428 if st == nil { 429 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 430 } 431 return storageRangeAt(st, keyStart, maxResult) 432 } 433 434 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 435 it := trie.NewIterator(st.NodeIterator(start)) 436 result := StorageRangeResult{Storage: storageMap{}} 437 for i := 0; i < maxResult && it.Next(); i++ { 438 _, content, _, err := rlp.Split(it.Value) 439 if err != nil { 440 return StorageRangeResult{}, err 441 } 442 e := storageEntry{Value: common.BytesToHash(content)} 443 if preimage := st.GetKey(it.Key); preimage != nil { 444 preimage := common.BytesToHash(preimage) 445 e.Key = &preimage 446 } 447 result.Storage[common.BytesToHash(it.Key)] = e 448 } 449 // Add the 'next key' so clients can continue downloading. 450 if it.Next() { 451 next := common.BytesToHash(it.Key) 452 result.NextKey = &next 453 } 454 return result, nil 455 } 456 457 // GetModifiedAccountsByNumber returns all accounts that have changed between the 458 // two blocks specified. A change is defined as a difference in nonce, balance, 459 // code hash, or storage hash. 460 // 461 // With one parameter, returns the list of accounts modified in the specified block. 462 func (api *DebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 463 var startBlock, endBlock *types.Block 464 465 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 466 if startBlock == nil { 467 return nil, fmt.Errorf("start block %x not found", startNum) 468 } 469 470 if endNum == nil { 471 endBlock = startBlock 472 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 473 if startBlock == nil { 474 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 475 } 476 } else { 477 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 478 if endBlock == nil { 479 return nil, fmt.Errorf("end block %d not found", *endNum) 480 } 481 } 482 return api.getModifiedAccounts(startBlock, endBlock) 483 } 484 485 // GetModifiedAccountsByHash returns all accounts that have changed between the 486 // two blocks specified. A change is defined as a difference in nonce, balance, 487 // code hash, or storage hash. 488 // 489 // With one parameter, returns the list of accounts modified in the specified block. 490 func (api *DebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 491 var startBlock, endBlock *types.Block 492 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 493 if startBlock == nil { 494 return nil, fmt.Errorf("start block %x not found", startHash) 495 } 496 497 if endHash == nil { 498 endBlock = startBlock 499 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 500 if startBlock == nil { 501 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 502 } 503 } else { 504 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 505 if endBlock == nil { 506 return nil, fmt.Errorf("end block %x not found", *endHash) 507 } 508 } 509 return api.getModifiedAccounts(startBlock, endBlock) 510 } 511 512 func (api *DebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 513 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 514 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 515 } 516 triedb := api.eth.BlockChain().StateCache().TrieDB() 517 518 oldTrie, err := trie.NewStateTrie(trie.StateTrieID(startBlock.Root()), triedb) 519 if err != nil { 520 return nil, err 521 } 522 newTrie, err := trie.NewStateTrie(trie.StateTrieID(endBlock.Root()), triedb) 523 if err != nil { 524 return nil, err 525 } 526 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 527 iter := trie.NewIterator(diff) 528 529 var dirty []common.Address 530 for iter.Next() { 531 key := newTrie.GetKey(iter.Key) 532 if key == nil { 533 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 534 } 535 dirty = append(dirty, common.BytesToAddress(key)) 536 } 537 return dirty, nil 538 } 539 540 // GetAccessibleState returns the first number where the node has accessible 541 // state on disk. Note this being the post-state of that block and the pre-state 542 // of the next block. 543 // The (from, to) parameters are the sequence of blocks to search, which can go 544 // either forwards or backwards 545 func (api *DebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { 546 db := api.eth.ChainDb() 547 var pivot uint64 548 if p := rawdb.ReadLastPivotNumber(db); p != nil { 549 pivot = *p 550 log.Info("Found fast-sync pivot marker", "number", pivot) 551 } 552 var resolveNum = func(num rpc.BlockNumber) (uint64, error) { 553 // We don't have state for pending (-2), so treat it as latest 554 if num.Int64() < 0 { 555 block := api.eth.blockchain.CurrentBlock() 556 if block == nil { 557 return 0, fmt.Errorf("current block missing") 558 } 559 return block.Number.Uint64(), nil 560 } 561 return uint64(num.Int64()), nil 562 } 563 var ( 564 start uint64 565 end uint64 566 delta = int64(1) 567 lastLog time.Time 568 err error 569 ) 570 if start, err = resolveNum(from); err != nil { 571 return 0, err 572 } 573 if end, err = resolveNum(to); err != nil { 574 return 0, err 575 } 576 if start == end { 577 return 0, fmt.Errorf("from and to needs to be different") 578 } 579 if start > end { 580 delta = -1 581 } 582 for i := int64(start); i != int64(end); i += delta { 583 if time.Since(lastLog) > 8*time.Second { 584 log.Info("Finding roots", "from", start, "to", end, "at", i) 585 lastLog = time.Now() 586 } 587 if i < int64(pivot) { 588 continue 589 } 590 h := api.eth.BlockChain().GetHeaderByNumber(uint64(i)) 591 if h == nil { 592 return 0, fmt.Errorf("missing header %d", i) 593 } 594 if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok { 595 return uint64(i), nil 596 } 597 } 598 return 0, errors.New("no state found") 599 } 600 601 // SetTrieFlushInterval configures how often in-memory tries are persisted 602 // to disk. The value is in terms of block processing time, not wall clock. 603 func (api *DebugAPI) SetTrieFlushInterval(interval string) error { 604 t, err := time.ParseDuration(interval) 605 if err != nil { 606 return err 607 } 608 api.eth.blockchain.SetTrieFlushInterval(t) 609 return nil 610 }