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