github.com/marconiprotocol/go-methereum-lite@v0.0.0-20190918214227-3cd8b06fcf99/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 "runtime" 28 "strings" 29 30 "github.com/MarconiProtocol/go-methereum-lite/common" 31 "github.com/MarconiProtocol/go-methereum-lite/common/hexutil" 32 "github.com/MarconiProtocol/go-methereum-lite/core" 33 "github.com/MarconiProtocol/go-methereum-lite/core/rawdb" 34 "github.com/MarconiProtocol/go-methereum-lite/core/state" 35 "github.com/MarconiProtocol/go-methereum-lite/core/types" 36 "github.com/MarconiProtocol/go-methereum-lite/internal/ethapi" 37 "github.com/MarconiProtocol/go-methereum-lite/params" 38 "github.com/MarconiProtocol/go-methereum-lite/rlp" 39 "github.com/MarconiProtocol/go-methereum-lite/rpc" 40 "github.com/MarconiProtocol/go-methereum-lite/trie" 41 ) 42 43 // PublicEthereumAPI provides an API to access Ethereum full node-related 44 // information. 45 type PublicEthereumAPI struct { 46 e *Ethereum 47 } 48 49 // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. 50 func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { 51 return &PublicEthereumAPI{e} 52 } 53 54 // Etherbase is the address that mining rewards will be send to 55 func (api *PublicEthereumAPI) Etherbase() (common.Address, error) { 56 return api.e.Etherbase() 57 } 58 59 // Coinbase is the address that mining rewards will be send to (alias for Etherbase) 60 func (api *PublicEthereumAPI) Coinbase() (common.Address, error) { 61 return api.Etherbase() 62 } 63 64 // Hashrate returns the POW hashrate 65 func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 { 66 return 0 67 } 68 69 // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config. 70 func (api *PublicEthereumAPI) ChainId() hexutil.Uint64 { 71 chainID := new(big.Int) 72 if config := api.e.chainConfig; config.IsEIP155(api.e.blockchain.CurrentBlock().Number()) { 73 chainID = config.ChainID 74 } 75 return (hexutil.Uint64)(chainID.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 *Ethereum 82 } 83 84 // NewPublicMinerAPI create a new PublicMinerAPI instance. 85 func NewPublicMinerAPI(e *Ethereum) *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 *Ethereum 98 } 99 100 // NewPrivateMinerAPI create a new RPC service which controls the miner of this node. 101 func NewPrivateMinerAPI(e *Ethereum) *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 return false, nil 126 } 127 128 // SetGasPrice sets the minimum accepted gas price for the miner. 129 func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 130 api.e.lock.Lock() 131 api.e.gasPrice = (*big.Int)(&gasPrice) 132 api.e.lock.Unlock() 133 134 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 135 return true 136 } 137 138 // SetEtherbase sets the etherbase of the miner 139 func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool { 140 api.e.SetEtherbase(etherbase) 141 return true 142 } 143 144 // SetRecommitInterval updates the interval for miner sealing work recommitting. 145 func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { 146 } 147 148 // GetHashrate returns the current hashrate of the miner. 149 func (api *PrivateMinerAPI) GetHashrate() uint64 { 150 return 0 151 } 152 153 // PrivateAdminAPI is the collection of Ethereum full node-related APIs 154 // exposed over the private admin endpoint. 155 type PrivateAdminAPI struct { 156 eth *Ethereum 157 } 158 159 // NewPrivateAdminAPI creates a new API definition for the full node private 160 // admin methods of the Ethereum service. 161 func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { 162 return &PrivateAdminAPI{eth: eth} 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.eth.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.eth.BlockChain(), blocks) { 234 blocks = blocks[:0] 235 continue 236 } 237 // Import the batch and reset the buffer 238 if _, err := api.eth.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 Ethereum full node APIs exposed 247 // over the public debugging endpoint. 248 type PublicDebugAPI struct { 249 eth *Ethereum 250 } 251 252 // NewPublicDebugAPI creates a new API definition for the full node- 253 // related public debug methods of the Ethereum service. 254 func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { 255 return &PublicDebugAPI{eth: eth} 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 return state.Dump{}, nil 262 } 263 var block *types.Block 264 if blockNr == rpc.LatestBlockNumber { 265 block = api.eth.blockchain.CurrentBlock() 266 } else { 267 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 268 } 269 if block == nil { 270 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 271 } 272 stateDb, err := api.eth.BlockChain().StateAt(block.Root()) 273 if err != nil { 274 return state.Dump{}, err 275 } 276 return stateDb.RawDump(), nil 277 } 278 279 // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over 280 // the private debugging endpoint. 281 type PrivateDebugAPI struct { 282 config *params.ChainConfig 283 eth *Ethereum 284 } 285 286 // NewPrivateDebugAPI creates a new API definition for the full node-related 287 // private debug methods of the Ethereum service. 288 func NewPrivateDebugAPI(config *params.ChainConfig, eth *Ethereum) *PrivateDebugAPI { 289 return &PrivateDebugAPI{config: config, eth: eth} 290 } 291 292 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 293 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 294 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 295 return preimage, nil 296 } 297 return nil, errors.New("unknown preimage") 298 } 299 300 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 301 type BadBlockArgs struct { 302 Hash common.Hash `json:"hash"` 303 Block map[string]interface{} `json:"block"` 304 RLP string `json:"rlp"` 305 } 306 307 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 308 // and returns them as a JSON list of block-hashes 309 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 310 blocks := api.eth.BlockChain().BadBlocks() 311 results := make([]*BadBlockArgs, len(blocks)) 312 313 var err error 314 for i, block := range blocks { 315 results[i] = &BadBlockArgs{ 316 Hash: block.Hash(), 317 } 318 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 319 results[i].RLP = err.Error() // Hacky, but hey, it works 320 } else { 321 results[i].RLP = fmt.Sprintf("0x%x", rlpBytes) 322 } 323 if results[i].Block, err = ethapi.RPCMarshalBlock(block, true, true); err != nil { 324 results[i].Block = map[string]interface{}{"error": err.Error()} 325 } 326 } 327 return results, nil 328 } 329 330 // StorageRangeResult is the result of a debug_storageRangeAt API call. 331 type StorageRangeResult struct { 332 Storage storageMap `json:"storage"` 333 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 334 } 335 336 type storageMap map[common.Hash]storageEntry 337 338 type storageEntry struct { 339 Key *common.Hash `json:"key"` 340 Value common.Hash `json:"value"` 341 } 342 343 // StorageRangeAt returns the storage at the given block height and transaction index. 344 func (api *PrivateDebugAPI) StorageRangeAt(ctx context.Context, blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 345 _, _, statedb, err := api.computeTxEnv(blockHash, txIndex, 0) 346 if err != nil { 347 return StorageRangeResult{}, err 348 } 349 st := statedb.StorageTrie(contractAddress) 350 if st == nil { 351 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 352 } 353 return storageRangeAt(st, keyStart, maxResult) 354 } 355 356 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 357 it := trie.NewIterator(st.NodeIterator(start)) 358 result := StorageRangeResult{Storage: storageMap{}} 359 for i := 0; i < maxResult && it.Next(); i++ { 360 _, content, _, err := rlp.Split(it.Value) 361 if err != nil { 362 return StorageRangeResult{}, err 363 } 364 e := storageEntry{Value: common.BytesToHash(content)} 365 if preimage := st.GetKey(it.Key); preimage != nil { 366 preimage := common.BytesToHash(preimage) 367 e.Key = &preimage 368 } 369 result.Storage[common.BytesToHash(it.Key)] = e 370 } 371 // Add the 'next key' so clients can continue downloading. 372 if it.Next() { 373 next := common.BytesToHash(it.Key) 374 result.NextKey = &next 375 } 376 return result, nil 377 } 378 379 // GetModifiedAccountsByNumber returns all accounts that have changed between the 380 // two blocks specified. A change is defined as a difference in nonce, balance, 381 // code hash, or storage hash. 382 // 383 // With one parameter, returns the list of accounts modified in the specified block. 384 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 385 var startBlock, endBlock *types.Block 386 387 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 388 if startBlock == nil { 389 return nil, fmt.Errorf("start block %x not found", startNum) 390 } 391 392 if endNum == nil { 393 endBlock = startBlock 394 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 395 if startBlock == nil { 396 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 397 } 398 } else { 399 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 400 if endBlock == nil { 401 return nil, fmt.Errorf("end block %d not found", *endNum) 402 } 403 } 404 return api.getModifiedAccounts(startBlock, endBlock) 405 } 406 407 // GetModifiedAccountsByHash returns all accounts that have changed between the 408 // two blocks specified. A change is defined as a difference in nonce, balance, 409 // code hash, or storage hash. 410 // 411 // With one parameter, returns the list of accounts modified in the specified block. 412 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 413 var startBlock, endBlock *types.Block 414 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 415 if startBlock == nil { 416 return nil, fmt.Errorf("start block %x not found", startHash) 417 } 418 419 if endHash == nil { 420 endBlock = startBlock 421 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 422 if startBlock == nil { 423 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 424 } 425 } else { 426 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 427 if endBlock == nil { 428 return nil, fmt.Errorf("end block %x not found", *endHash) 429 } 430 } 431 return api.getModifiedAccounts(startBlock, endBlock) 432 } 433 434 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 435 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 436 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 437 } 438 triedb := api.eth.BlockChain().StateCache().TrieDB() 439 440 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb, 0) 441 if err != nil { 442 return nil, err 443 } 444 newTrie, err := trie.NewSecure(endBlock.Root(), triedb, 0) 445 if err != nil { 446 return nil, err 447 } 448 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 449 iter := trie.NewIterator(diff) 450 451 var dirty []common.Address 452 for iter.Next() { 453 key := newTrie.GetKey(iter.Key) 454 if key == nil { 455 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 456 } 457 dirty = append(dirty, common.BytesToAddress(key)) 458 } 459 return dirty, nil 460 }