gitlab.com/flarenetwork/coreth@v0.1.1/eth/api.go (about) 1 // (c) 2019-2020, Ava Labs, Inc. 2 // 3 // This file is a derived work, based on the go-ethereum library whose original 4 // notices appear below. 5 // 6 // It is distributed under a license compatible with the licensing terms of the 7 // original code from which it is derived. 8 // 9 // Much love to the original authors for their work. 10 // ********** 11 // Copyright 2015 The go-ethereum Authors 12 // This file is part of the go-ethereum library. 13 // 14 // The go-ethereum library is free software: you can redistribute it and/or modify 15 // it under the terms of the GNU Lesser General Public License as published by 16 // the Free Software Foundation, either version 3 of the License, or 17 // (at your option) any later version. 18 // 19 // The go-ethereum library is distributed in the hope that it will be useful, 20 // but WITHOUT ANY WARRANTY; without even the implied warranty of 21 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 22 // GNU Lesser General Public License for more details. 23 // 24 // You should have received a copy of the GNU Lesser General Public License 25 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 26 27 package eth 28 29 import ( 30 "compress/gzip" 31 "context" 32 "errors" 33 "fmt" 34 "io" 35 "os" 36 "strings" 37 38 "github.com/ethereum/go-ethereum/common" 39 "github.com/ethereum/go-ethereum/common/hexutil" 40 "github.com/ethereum/go-ethereum/rlp" 41 "github.com/ethereum/go-ethereum/trie" 42 "gitlab.com/flarenetwork/coreth/core" 43 "gitlab.com/flarenetwork/coreth/core/rawdb" 44 "gitlab.com/flarenetwork/coreth/core/state" 45 "gitlab.com/flarenetwork/coreth/core/types" 46 "gitlab.com/flarenetwork/coreth/internal/ethapi" 47 "gitlab.com/flarenetwork/coreth/rpc" 48 ) 49 50 // PublicEthereumAPI provides an API to access Ethereum full node-related 51 // information. 52 type PublicEthereumAPI struct { 53 e *Ethereum 54 } 55 56 // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. 57 func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { 58 return &PublicEthereumAPI{e} 59 } 60 61 // Etherbase is the address that mining rewards will be send to 62 func (api *PublicEthereumAPI) Etherbase() (common.Address, error) { 63 return api.e.Etherbase() 64 } 65 66 // Coinbase is the address that mining rewards will be send to (alias for Etherbase) 67 func (api *PublicEthereumAPI) Coinbase() (common.Address, error) { 68 return api.Etherbase() 69 } 70 71 // PrivateAdminAPI is the collection of Ethereum full node-related APIs 72 // exposed over the private admin endpoint. 73 type PrivateAdminAPI struct { 74 eth *Ethereum 75 } 76 77 // NewPrivateAdminAPI creates a new API definition for the full node private 78 // admin methods of the Ethereum service. 79 func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { 80 return &PrivateAdminAPI{eth: eth} 81 } 82 83 // ExportChain exports the current blockchain into a local file, 84 // or a range of blocks if first and last are non-nil 85 func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { 86 if first == nil && last != nil { 87 return false, errors.New("last cannot be specified without first") 88 } 89 if first != nil && last == nil { 90 head := api.eth.BlockChain().CurrentHeader().Number.Uint64() 91 last = &head 92 } 93 if _, err := os.Stat(file); err == nil { 94 // File already exists. Allowing overwrite could be a DoS vecotor, 95 // since the 'file' may point to arbitrary paths on the drive 96 return false, errors.New("location would overwrite an existing file") 97 } 98 // Make sure we can create the file to export into 99 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 100 if err != nil { 101 return false, err 102 } 103 defer out.Close() 104 105 var writer io.Writer = out 106 if strings.HasSuffix(file, ".gz") { 107 writer = gzip.NewWriter(writer) 108 defer writer.(*gzip.Writer).Close() 109 } 110 111 // Export the blockchain 112 if first != nil { 113 if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil { 114 return false, err 115 } 116 } else if err := api.eth.BlockChain().Export(writer); err != nil { 117 return false, err 118 } 119 return true, nil 120 } 121 122 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 123 for _, b := range bs { 124 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 125 return false 126 } 127 } 128 129 return true 130 } 131 132 // ImportChain imports a blockchain from a local file. 133 func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) { 134 // Make sure the can access the file to import 135 in, err := os.Open(file) 136 if err != nil { 137 return false, err 138 } 139 defer in.Close() 140 141 var reader io.Reader = in 142 if strings.HasSuffix(file, ".gz") { 143 if reader, err = gzip.NewReader(reader); err != nil { 144 return false, err 145 } 146 } 147 148 // Run actual the import in pre-configured batches 149 stream := rlp.NewStream(reader, 0) 150 151 blocks, index := make([]*types.Block, 0, 2500), 0 152 for batch := 0; ; batch++ { 153 // Load a batch of blocks from the input file 154 for len(blocks) < cap(blocks) { 155 block := new(types.Block) 156 if err := stream.Decode(block); err == io.EOF { 157 break 158 } else if err != nil { 159 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 160 } 161 blocks = append(blocks, block) 162 index++ 163 } 164 if len(blocks) == 0 { 165 break 166 } 167 168 if hasAllBlocks(api.eth.BlockChain(), blocks) { 169 blocks = blocks[:0] 170 continue 171 } 172 // Import the batch and reset the buffer 173 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 174 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 175 } 176 blocks = blocks[:0] 177 } 178 return true, nil 179 } 180 181 // PublicDebugAPI is the collection of Ethereum full node APIs exposed 182 // over the public debugging endpoint. 183 type PublicDebugAPI struct { 184 eth *Ethereum 185 } 186 187 // NewPublicDebugAPI creates a new API definition for the full node- 188 // related public debug methods of the Ethereum service. 189 func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { 190 return &PublicDebugAPI{eth: eth} 191 } 192 193 // DumpBlock retrieves the entire state of the database at a given block. 194 func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { 195 opts := &state.DumpConfig{ 196 OnlyWithAddresses: true, 197 Max: AccountRangeMaxResults, // Sanity limit over RPC 198 } 199 var block *types.Block 200 if blockNr.IsAccepted() { 201 block = api.eth.LastAcceptedBlock() 202 } else { 203 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 204 } 205 206 if block == nil { 207 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 208 } 209 stateDb, err := api.eth.BlockChain().StateAt(block.Root()) 210 if err != nil { 211 return state.Dump{}, err 212 } 213 return stateDb.RawDump(opts), nil 214 } 215 216 // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over 217 // the private debugging endpoint. 218 type PrivateDebugAPI struct { 219 eth *Ethereum 220 } 221 222 // NewPrivateDebugAPI creates a new API definition for the full node-related 223 // private debug methods of the Ethereum service. 224 func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI { 225 return &PrivateDebugAPI{eth: eth} 226 } 227 228 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 229 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 230 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 231 return preimage, nil 232 } 233 return nil, errors.New("unknown preimage") 234 } 235 236 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 237 type BadBlockArgs struct { 238 Hash common.Hash `json:"hash"` 239 Block map[string]interface{} `json:"block"` 240 RLP string `json:"rlp"` 241 } 242 243 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 244 // and returns them as a JSON list of block-hashes 245 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 246 var ( 247 err error 248 blocks = api.eth.BlockChain().BadBlocks() 249 results = make([]*BadBlockArgs, 0, len(blocks)) 250 ) 251 for _, block := range blocks { 252 var ( 253 blockRlp string 254 blockJSON map[string]interface{} 255 ) 256 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 257 blockRlp = err.Error() // Hacky, but hey, it works 258 } else { 259 blockRlp = fmt.Sprintf("0x%x", rlpBytes) 260 } 261 if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true); err != nil { 262 blockJSON = map[string]interface{}{"error": err.Error()} 263 } 264 results = append(results, &BadBlockArgs{ 265 Hash: block.Hash(), 266 RLP: blockRlp, 267 Block: blockJSON, 268 }) 269 } 270 return results, nil 271 } 272 273 // AccountRangeMaxResults is the maximum number of results to be returned per call 274 const AccountRangeMaxResults = 256 275 276 // AccountRange enumerates all accounts in the given block and start point in paging request 277 func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 278 var stateDb *state.StateDB 279 var err error 280 281 if number, ok := blockNrOrHash.Number(); ok { 282 var block *types.Block 283 if number.IsAccepted() { 284 block = api.eth.LastAcceptedBlock() 285 } else { 286 block = api.eth.blockchain.GetBlockByNumber(uint64(number)) 287 } 288 if block == nil { 289 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 290 } 291 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 292 if err != nil { 293 return state.IteratorDump{}, err 294 } 295 } else if hash, ok := blockNrOrHash.Hash(); ok { 296 block := api.eth.blockchain.GetBlockByHash(hash) 297 if block == nil { 298 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 299 } 300 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 301 if err != nil { 302 return state.IteratorDump{}, err 303 } 304 } else { 305 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 306 } 307 308 opts := &state.DumpConfig{ 309 SkipCode: nocode, 310 SkipStorage: nostorage, 311 OnlyWithAddresses: !incompletes, 312 Start: start, 313 Max: uint64(maxResults), 314 } 315 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 316 opts.Max = AccountRangeMaxResults 317 } 318 return stateDb.IteratorDump(opts), nil 319 } 320 321 // StorageRangeResult is the result of a debug_storageRangeAt API call. 322 type StorageRangeResult struct { 323 Storage storageMap `json:"storage"` 324 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 325 } 326 327 type storageMap map[common.Hash]storageEntry 328 329 type storageEntry struct { 330 Key *common.Hash `json:"key"` 331 Value common.Hash `json:"value"` 332 } 333 334 // StorageRangeAt returns the storage at the given block height and transaction index. 335 func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 336 // Retrieve the block 337 block := api.eth.blockchain.GetBlockByHash(blockHash) 338 if block == nil { 339 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 340 } 341 _, _, statedb, err := api.eth.stateAtTransaction(block, txIndex, 0) 342 if err != nil { 343 return StorageRangeResult{}, err 344 } 345 st := statedb.StorageTrie(contractAddress) 346 if st == nil { 347 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 348 } 349 return storageRangeAt(st, keyStart, maxResult) 350 } 351 352 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 353 it := trie.NewIterator(st.NodeIterator(start)) 354 result := StorageRangeResult{Storage: storageMap{}} 355 for i := 0; i < maxResult && it.Next(); i++ { 356 _, content, _, err := rlp.Split(it.Value) 357 if err != nil { 358 return StorageRangeResult{}, err 359 } 360 e := storageEntry{Value: common.BytesToHash(content)} 361 if preimage := st.GetKey(it.Key); preimage != nil { 362 preimage := common.BytesToHash(preimage) 363 e.Key = &preimage 364 } 365 result.Storage[common.BytesToHash(it.Key)] = e 366 } 367 // Add the 'next key' so clients can continue downloading. 368 if it.Next() { 369 next := common.BytesToHash(it.Key) 370 result.NextKey = &next 371 } 372 return result, nil 373 } 374 375 // GetModifiedAccountsByNumber returns all accounts that have changed between the 376 // two blocks specified. A change is defined as a difference in nonce, balance, 377 // code hash, or storage hash. 378 // 379 // With one parameter, returns the list of accounts modified in the specified block. 380 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 381 var startBlock, endBlock *types.Block 382 383 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 384 if startBlock == nil { 385 return nil, fmt.Errorf("start block %x not found", startNum) 386 } 387 388 if endNum == nil { 389 endBlock = startBlock 390 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 391 if startBlock == nil { 392 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 393 } 394 } else { 395 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 396 if endBlock == nil { 397 return nil, fmt.Errorf("end block %d not found", *endNum) 398 } 399 } 400 return api.getModifiedAccounts(startBlock, endBlock) 401 } 402 403 // GetModifiedAccountsByHash returns all accounts that have changed between the 404 // two blocks specified. A change is defined as a difference in nonce, balance, 405 // code hash, or storage hash. 406 // 407 // With one parameter, returns the list of accounts modified in the specified block. 408 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 409 var startBlock, endBlock *types.Block 410 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 411 if startBlock == nil { 412 return nil, fmt.Errorf("start block %x not found", startHash) 413 } 414 415 if endHash == nil { 416 endBlock = startBlock 417 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 418 if startBlock == nil { 419 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 420 } 421 } else { 422 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 423 if endBlock == nil { 424 return nil, fmt.Errorf("end block %x not found", *endHash) 425 } 426 } 427 return api.getModifiedAccounts(startBlock, endBlock) 428 } 429 430 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 431 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 432 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 433 } 434 triedb := api.eth.BlockChain().StateCache().TrieDB() 435 436 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb) 437 if err != nil { 438 return nil, err 439 } 440 newTrie, err := trie.NewSecure(endBlock.Root(), triedb) 441 if err != nil { 442 return nil, err 443 } 444 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 445 iter := trie.NewIterator(diff) 446 447 var dirty []common.Address 448 for iter.Next() { 449 key := newTrie.GetKey(iter.Key) 450 if key == nil { 451 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 452 } 453 dirty = append(dirty, common.BytesToAddress(key)) 454 } 455 return dirty, nil 456 }