github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/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 "encoding/json" 23 "errors" 24 "fmt" 25 "io" 26 "math/big" 27 "os" 28 "runtime" 29 "strings" 30 "time" 31 32 "github.com/scroll-tech/go-ethereum/common" 33 "github.com/scroll-tech/go-ethereum/common/hexutil" 34 "github.com/scroll-tech/go-ethereum/core" 35 "github.com/scroll-tech/go-ethereum/core/rawdb" 36 "github.com/scroll-tech/go-ethereum/core/state" 37 "github.com/scroll-tech/go-ethereum/core/types" 38 "github.com/scroll-tech/go-ethereum/internal/ethapi" 39 "github.com/scroll-tech/go-ethereum/log" 40 "github.com/scroll-tech/go-ethereum/rlp" 41 "github.com/scroll-tech/go-ethereum/rpc" 42 "github.com/scroll-tech/go-ethereum/trie" 43 ) 44 45 // PublicEthereumAPI provides an API to access Ethereum full node-related 46 // information. 47 type PublicEthereumAPI struct { 48 e *Ethereum 49 } 50 51 // NewPublicEthereumAPI creates a new Ethereum protocol API for full nodes. 52 func NewPublicEthereumAPI(e *Ethereum) *PublicEthereumAPI { 53 return &PublicEthereumAPI{e} 54 } 55 56 // Etherbase is the address that mining rewards will be send to 57 func (api *PublicEthereumAPI) Etherbase() (common.Address, error) { 58 return api.e.Etherbase() 59 } 60 61 // Coinbase is the address that mining rewards will be send to (alias for Etherbase) 62 func (api *PublicEthereumAPI) Coinbase() (common.Address, error) { 63 return api.Etherbase() 64 } 65 66 // Hashrate returns the POW hashrate 67 func (api *PublicEthereumAPI) Hashrate() hexutil.Uint64 { 68 return hexutil.Uint64(api.e.Miner().Hashrate()) 69 } 70 71 // PublicMinerAPI provides an API to control the miner. 72 // It offers only methods that operate on data that pose no security risk when it is publicly accessible. 73 type PublicMinerAPI struct { 74 e *Ethereum 75 } 76 77 // NewPublicMinerAPI create a new PublicMinerAPI instance. 78 func NewPublicMinerAPI(e *Ethereum) *PublicMinerAPI { 79 return &PublicMinerAPI{e} 80 } 81 82 // Mining returns an indication if this node is currently mining. 83 func (api *PublicMinerAPI) Mining() bool { 84 return api.e.IsMining() 85 } 86 87 // PrivateMinerAPI provides private RPC methods to control the miner. 88 // These methods can be abused by external users and must be considered insecure for use by untrusted users. 89 type PrivateMinerAPI struct { 90 e *Ethereum 91 } 92 93 // NewPrivateMinerAPI create a new RPC service which controls the miner of this node. 94 func NewPrivateMinerAPI(e *Ethereum) *PrivateMinerAPI { 95 return &PrivateMinerAPI{e: e} 96 } 97 98 // Start starts the miner with the given number of threads. If threads is nil, 99 // the number of workers started is equal to the number of logical CPUs that are 100 // usable by this process. If mining is already running, this method adjust the 101 // number of threads allowed to use and updates the minimum price required by the 102 // transaction pool. 103 func (api *PrivateMinerAPI) Start(threads *int) error { 104 if threads == nil { 105 return api.e.StartMining(runtime.NumCPU()) 106 } 107 return api.e.StartMining(*threads) 108 } 109 110 // Stop terminates the miner, both at the consensus engine level as well as at 111 // the block creation level. 112 func (api *PrivateMinerAPI) Stop() { 113 api.e.StopMining() 114 } 115 116 // SetExtra sets the extra data string that is included when this miner mines a block. 117 func (api *PrivateMinerAPI) SetExtra(extra string) (bool, error) { 118 if err := api.e.Miner().SetExtra([]byte(extra)); err != nil { 119 return false, err 120 } 121 return true, nil 122 } 123 124 // SetGasPrice sets the minimum accepted gas price for the miner. 125 func (api *PrivateMinerAPI) SetGasPrice(gasPrice hexutil.Big) bool { 126 api.e.lock.Lock() 127 api.e.gasPrice = (*big.Int)(&gasPrice) 128 api.e.lock.Unlock() 129 130 api.e.txPool.SetGasPrice((*big.Int)(&gasPrice)) 131 return true 132 } 133 134 // SetGasLimit sets the gaslimit to target towards during mining. 135 func (api *PrivateMinerAPI) SetGasLimit(gasLimit hexutil.Uint64) bool { 136 api.e.Miner().SetGasCeil(uint64(gasLimit)) 137 return true 138 } 139 140 // SetEtherbase sets the etherbase of the miner 141 func (api *PrivateMinerAPI) SetEtherbase(etherbase common.Address) bool { 142 api.e.SetEtherbase(etherbase) 143 return true 144 } 145 146 // SetRecommitInterval updates the interval for miner sealing work recommitting. 147 func (api *PrivateMinerAPI) SetRecommitInterval(interval int) { 148 api.e.Miner().SetRecommitInterval(time.Duration(interval) * time.Millisecond) 149 } 150 151 // PrivateAdminAPI is the collection of Ethereum full node-related APIs 152 // exposed over the private admin endpoint. 153 type PrivateAdminAPI struct { 154 eth *Ethereum 155 } 156 157 // NewPrivateAdminAPI creates a new API definition for the full node private 158 // admin methods of the Ethereum service. 159 func NewPrivateAdminAPI(eth *Ethereum) *PrivateAdminAPI { 160 return &PrivateAdminAPI{eth: eth} 161 } 162 163 // ExportChain exports the current blockchain into a local file, 164 // or a range of blocks if first and last are non-nil 165 func (api *PrivateAdminAPI) ExportChain(file string, first *uint64, last *uint64) (bool, error) { 166 if first == nil && last != nil { 167 return false, errors.New("last cannot be specified without first") 168 } 169 if first != nil && last == nil { 170 head := api.eth.BlockChain().CurrentHeader().Number.Uint64() 171 last = &head 172 } 173 if _, err := os.Stat(file); err == nil { 174 // File already exists. Allowing overwrite could be a DoS vector, 175 // since the 'file' may point to arbitrary paths on the drive 176 return false, errors.New("location would overwrite an existing file") 177 } 178 // Make sure we can create the file to export into 179 out, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, os.ModePerm) 180 if err != nil { 181 return false, err 182 } 183 defer out.Close() 184 185 var writer io.Writer = out 186 if strings.HasSuffix(file, ".gz") { 187 writer = gzip.NewWriter(writer) 188 defer writer.(*gzip.Writer).Close() 189 } 190 191 // Export the blockchain 192 if first != nil { 193 if err := api.eth.BlockChain().ExportN(writer, *first, *last); err != nil { 194 return false, err 195 } 196 } else if err := api.eth.BlockChain().Export(writer); err != nil { 197 return false, err 198 } 199 return true, nil 200 } 201 202 func hasAllBlocks(chain *core.BlockChain, bs []*types.Block) bool { 203 for _, b := range bs { 204 if !chain.HasBlock(b.Hash(), b.NumberU64()) { 205 return false 206 } 207 } 208 209 return true 210 } 211 212 // ImportChain imports a blockchain from a local file. 213 func (api *PrivateAdminAPI) ImportChain(file string) (bool, error) { 214 // Make sure the can access the file to import 215 in, err := os.Open(file) 216 if err != nil { 217 return false, err 218 } 219 defer in.Close() 220 221 var reader io.Reader = in 222 if strings.HasSuffix(file, ".gz") { 223 if reader, err = gzip.NewReader(reader); err != nil { 224 return false, err 225 } 226 } 227 228 // Run actual the import in pre-configured batches 229 stream := rlp.NewStream(reader, 0) 230 231 blocks, index := make([]*types.Block, 0, 2500), 0 232 for batch := 0; ; batch++ { 233 // Load a batch of blocks from the input file 234 for len(blocks) < cap(blocks) { 235 block := new(types.Block) 236 if err := stream.Decode(block); err == io.EOF { 237 break 238 } else if err != nil { 239 return false, fmt.Errorf("block %d: failed to parse: %v", index, err) 240 } 241 blocks = append(blocks, block) 242 index++ 243 } 244 if len(blocks) == 0 { 245 break 246 } 247 248 if hasAllBlocks(api.eth.BlockChain(), blocks) { 249 blocks = blocks[:0] 250 continue 251 } 252 // Import the batch and reset the buffer 253 if _, err := api.eth.BlockChain().InsertChain(blocks); err != nil { 254 return false, fmt.Errorf("batch %d: failed to insert: %v", batch, err) 255 } 256 blocks = blocks[:0] 257 } 258 return true, nil 259 } 260 261 // PublicDebugAPI is the collection of Ethereum full node APIs exposed 262 // over the public debugging endpoint. 263 type PublicDebugAPI struct { 264 eth *Ethereum 265 } 266 267 // NewPublicDebugAPI creates a new API definition for the full node- 268 // related public debug methods of the Ethereum service. 269 func NewPublicDebugAPI(eth *Ethereum) *PublicDebugAPI { 270 return &PublicDebugAPI{eth: eth} 271 } 272 273 // DumpBlock retrieves the entire state of the database at a given block. 274 func (api *PublicDebugAPI) DumpBlock(blockNr rpc.BlockNumber) (state.Dump, error) { 275 opts := &state.DumpConfig{ 276 OnlyWithAddresses: true, 277 Max: AccountRangeMaxResults, // Sanity limit over RPC 278 } 279 if blockNr == rpc.PendingBlockNumber { 280 // If we're dumping the pending state, we need to request 281 // both the pending block as well as the pending state from 282 // the miner and operate on those 283 _, stateDb := api.eth.miner.Pending() 284 return stateDb.RawDump(opts), nil 285 } 286 var block *types.Block 287 if blockNr == rpc.LatestBlockNumber { 288 block = api.eth.blockchain.CurrentBlock() 289 } else { 290 block = api.eth.blockchain.GetBlockByNumber(uint64(blockNr)) 291 } 292 if block == nil { 293 return state.Dump{}, fmt.Errorf("block #%d not found", blockNr) 294 } 295 stateDb, err := api.eth.BlockChain().StateAt(block.Root()) 296 if err != nil { 297 return state.Dump{}, err 298 } 299 return stateDb.RawDump(opts), nil 300 } 301 302 // PrivateDebugAPI is the collection of Ethereum full node APIs exposed over 303 // the private debugging endpoint. 304 type PrivateDebugAPI struct { 305 eth *Ethereum 306 } 307 308 // NewPrivateDebugAPI creates a new API definition for the full node-related 309 // private debug methods of the Ethereum service. 310 func NewPrivateDebugAPI(eth *Ethereum) *PrivateDebugAPI { 311 return &PrivateDebugAPI{eth: eth} 312 } 313 314 // Preimage is a debug API function that returns the preimage for a sha3 hash, if known. 315 func (api *PrivateDebugAPI) Preimage(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 316 if preimage := rawdb.ReadPreimage(api.eth.ChainDb(), hash); preimage != nil { 317 return preimage, nil 318 } 319 return nil, errors.New("unknown preimage") 320 } 321 322 // BadBlockArgs represents the entries in the list returned when bad blocks are queried. 323 type BadBlockArgs struct { 324 Hash common.Hash `json:"hash"` 325 Block map[string]interface{} `json:"block"` 326 RLP string `json:"rlp"` 327 } 328 329 // GetBadBlocks returns a list of the last 'bad blocks' that the client has seen on the network 330 // and returns them as a JSON list of block-hashes 331 func (api *PrivateDebugAPI) GetBadBlocks(ctx context.Context) ([]*BadBlockArgs, error) { 332 var ( 333 err error 334 blocks = rawdb.ReadAllBadBlocks(api.eth.chainDb) 335 results = make([]*BadBlockArgs, 0, len(blocks)) 336 ) 337 for _, block := range blocks { 338 var ( 339 blockRlp string 340 blockJSON map[string]interface{} 341 ) 342 if rlpBytes, err := rlp.EncodeToBytes(block); err != nil { 343 blockRlp = err.Error() // Hacky, but hey, it works 344 } else { 345 blockRlp = fmt.Sprintf("0x%x", rlpBytes) 346 } 347 if blockJSON, err = ethapi.RPCMarshalBlock(block, true, true, api.eth.APIBackend.ChainConfig()); err != nil { 348 blockJSON = map[string]interface{}{"error": err.Error()} 349 } 350 results = append(results, &BadBlockArgs{ 351 Hash: block.Hash(), 352 RLP: blockRlp, 353 Block: blockJSON, 354 }) 355 } 356 return results, nil 357 } 358 359 // AccountRangeMaxResults is the maximum number of results to be returned per call 360 const AccountRangeMaxResults = 256 361 362 // AccountRange enumerates all accounts in the given block and start point in paging request 363 func (api *PublicDebugAPI) AccountRange(blockNrOrHash rpc.BlockNumberOrHash, start []byte, maxResults int, nocode, nostorage, incompletes bool) (state.IteratorDump, error) { 364 var stateDb *state.StateDB 365 var err error 366 367 if number, ok := blockNrOrHash.Number(); ok { 368 if number == rpc.PendingBlockNumber { 369 // If we're dumping the pending state, we need to request 370 // both the pending block as well as the pending state from 371 // the miner and operate on those 372 _, stateDb = api.eth.miner.Pending() 373 } else { 374 var block *types.Block 375 if number == rpc.LatestBlockNumber { 376 block = api.eth.blockchain.CurrentBlock() 377 } else { 378 block = api.eth.blockchain.GetBlockByNumber(uint64(number)) 379 } 380 if block == nil { 381 return state.IteratorDump{}, fmt.Errorf("block #%d not found", number) 382 } 383 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 384 if err != nil { 385 return state.IteratorDump{}, err 386 } 387 } 388 } else if hash, ok := blockNrOrHash.Hash(); ok { 389 block := api.eth.blockchain.GetBlockByHash(hash) 390 if block == nil { 391 return state.IteratorDump{}, fmt.Errorf("block %s not found", hash.Hex()) 392 } 393 stateDb, err = api.eth.BlockChain().StateAt(block.Root()) 394 if err != nil { 395 return state.IteratorDump{}, err 396 } 397 } else { 398 return state.IteratorDump{}, errors.New("either block number or block hash must be specified") 399 } 400 401 opts := &state.DumpConfig{ 402 SkipCode: nocode, 403 SkipStorage: nostorage, 404 OnlyWithAddresses: !incompletes, 405 Start: start, 406 Max: uint64(maxResults), 407 } 408 if maxResults > AccountRangeMaxResults || maxResults <= 0 { 409 opts.Max = AccountRangeMaxResults 410 } 411 return stateDb.IteratorDump(opts), nil 412 } 413 414 // StorageRangeResult is the result of a debug_storageRangeAt API call. 415 type StorageRangeResult struct { 416 Storage storageMap `json:"storage"` 417 NextKey *common.Hash `json:"nextKey"` // nil if Storage includes the last key in the trie. 418 } 419 420 type storageMap map[common.Hash]storageEntry 421 422 type storageEntry struct { 423 Key *common.Hash `json:"key"` 424 Value common.Hash `json:"value"` 425 } 426 427 // StorageRangeAt returns the storage at the given block height and transaction index. 428 func (api *PrivateDebugAPI) StorageRangeAt(blockHash common.Hash, txIndex int, contractAddress common.Address, keyStart hexutil.Bytes, maxResult int) (StorageRangeResult, error) { 429 // Retrieve the block 430 block := api.eth.blockchain.GetBlockByHash(blockHash) 431 if block == nil { 432 return StorageRangeResult{}, fmt.Errorf("block %#x not found", blockHash) 433 } 434 _, _, statedb, err := api.eth.stateAtTransaction(block, txIndex, 0) 435 if err != nil { 436 return StorageRangeResult{}, err 437 } 438 st := statedb.StorageTrie(contractAddress) 439 if st == nil { 440 return StorageRangeResult{}, fmt.Errorf("account %x doesn't exist", contractAddress) 441 } 442 return storageRangeAt(st, keyStart, maxResult) 443 } 444 445 func storageRangeAt(st state.Trie, start []byte, maxResult int) (StorageRangeResult, error) { 446 it := trie.NewIterator(st.NodeIterator(start)) 447 result := StorageRangeResult{Storage: storageMap{}} 448 for i := 0; i < maxResult && it.Next(); i++ { 449 _, content, _, err := rlp.Split(it.Value) 450 if err != nil { 451 return StorageRangeResult{}, err 452 } 453 e := storageEntry{Value: common.BytesToHash(content)} 454 if preimage := st.GetKey(it.Key); preimage != nil { 455 preimage := common.BytesToHash(preimage) 456 e.Key = &preimage 457 } 458 result.Storage[common.BytesToHash(it.Key)] = e 459 } 460 // Add the 'next key' so clients can continue downloading. 461 if it.Next() { 462 next := common.BytesToHash(it.Key) 463 result.NextKey = &next 464 } 465 return result, nil 466 } 467 468 // GetModifiedAccountsByNumber returns all accounts that have changed between the 469 // two blocks specified. A change is defined as a difference in nonce, balance, 470 // code hash, or storage hash. 471 // 472 // With one parameter, returns the list of accounts modified in the specified block. 473 func (api *PrivateDebugAPI) GetModifiedAccountsByNumber(startNum uint64, endNum *uint64) ([]common.Address, error) { 474 var startBlock, endBlock *types.Block 475 476 startBlock = api.eth.blockchain.GetBlockByNumber(startNum) 477 if startBlock == nil { 478 return nil, fmt.Errorf("start block %x not found", startNum) 479 } 480 481 if endNum == nil { 482 endBlock = startBlock 483 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 484 if startBlock == nil { 485 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 486 } 487 } else { 488 endBlock = api.eth.blockchain.GetBlockByNumber(*endNum) 489 if endBlock == nil { 490 return nil, fmt.Errorf("end block %d not found", *endNum) 491 } 492 } 493 return api.getModifiedAccounts(startBlock, endBlock) 494 } 495 496 // GetModifiedAccountsByHash returns all accounts that have changed between the 497 // two blocks specified. A change is defined as a difference in nonce, balance, 498 // code hash, or storage hash. 499 // 500 // With one parameter, returns the list of accounts modified in the specified block. 501 func (api *PrivateDebugAPI) GetModifiedAccountsByHash(startHash common.Hash, endHash *common.Hash) ([]common.Address, error) { 502 var startBlock, endBlock *types.Block 503 startBlock = api.eth.blockchain.GetBlockByHash(startHash) 504 if startBlock == nil { 505 return nil, fmt.Errorf("start block %x not found", startHash) 506 } 507 508 if endHash == nil { 509 endBlock = startBlock 510 startBlock = api.eth.blockchain.GetBlockByHash(startBlock.ParentHash()) 511 if startBlock == nil { 512 return nil, fmt.Errorf("block %x has no parent", endBlock.Number()) 513 } 514 } else { 515 endBlock = api.eth.blockchain.GetBlockByHash(*endHash) 516 if endBlock == nil { 517 return nil, fmt.Errorf("end block %x not found", *endHash) 518 } 519 } 520 return api.getModifiedAccounts(startBlock, endBlock) 521 } 522 523 func (api *PrivateDebugAPI) getModifiedAccounts(startBlock, endBlock *types.Block) ([]common.Address, error) { 524 if startBlock.Number().Uint64() >= endBlock.Number().Uint64() { 525 return nil, fmt.Errorf("start block height (%d) must be less than end block height (%d)", startBlock.Number().Uint64(), endBlock.Number().Uint64()) 526 } 527 triedb := api.eth.BlockChain().StateCache().TrieDB() 528 529 oldTrie, err := trie.NewSecure(startBlock.Root(), triedb) 530 if err != nil { 531 return nil, err 532 } 533 newTrie, err := trie.NewSecure(endBlock.Root(), triedb) 534 if err != nil { 535 return nil, err 536 } 537 diff, _ := trie.NewDifferenceIterator(oldTrie.NodeIterator([]byte{}), newTrie.NodeIterator([]byte{})) 538 iter := trie.NewIterator(diff) 539 540 var dirty []common.Address 541 for iter.Next() { 542 key := newTrie.GetKey(iter.Key) 543 if key == nil { 544 return nil, fmt.Errorf("no preimage found for hash %x", iter.Key) 545 } 546 dirty = append(dirty, common.BytesToAddress(key)) 547 } 548 return dirty, nil 549 } 550 551 // GetAccessibleState returns the first number where the node has accessible 552 // state on disk. Note this being the post-state of that block and the pre-state 553 // of the next block. 554 // The (from, to) parameters are the sequence of blocks to search, which can go 555 // either forwards or backwards 556 func (api *PrivateDebugAPI) GetAccessibleState(from, to rpc.BlockNumber) (uint64, error) { 557 db := api.eth.ChainDb() 558 var pivot uint64 559 if p := rawdb.ReadLastPivotNumber(db); p != nil { 560 pivot = *p 561 log.Info("Found fast-sync pivot marker", "number", pivot) 562 } 563 var resolveNum = func(num rpc.BlockNumber) (uint64, error) { 564 // We don't have state for pending (-2), so treat it as latest 565 if num.Int64() < 0 { 566 block := api.eth.blockchain.CurrentBlock() 567 if block == nil { 568 return 0, fmt.Errorf("current block missing") 569 } 570 return block.NumberU64(), nil 571 } 572 return uint64(num.Int64()), nil 573 } 574 var ( 575 start uint64 576 end uint64 577 delta = int64(1) 578 lastLog time.Time 579 err error 580 ) 581 if start, err = resolveNum(from); err != nil { 582 return 0, err 583 } 584 if end, err = resolveNum(to); err != nil { 585 return 0, err 586 } 587 if start == end { 588 return 0, fmt.Errorf("from and to needs to be different") 589 } 590 if start > end { 591 delta = -1 592 } 593 for i := int64(start); i != int64(end); i += delta { 594 if time.Since(lastLog) > 8*time.Second { 595 log.Info("Finding roots", "from", start, "to", end, "at", i) 596 lastLog = time.Now() 597 } 598 if i < int64(pivot) { 599 continue 600 } 601 h := api.eth.BlockChain().GetHeaderByNumber(uint64(i)) 602 if h == nil { 603 return 0, fmt.Errorf("missing header %d", i) 604 } 605 if ok, _ := api.eth.ChainDb().Has(h.Root[:]); ok { 606 return uint64(i), nil 607 } 608 } 609 return 0, fmt.Errorf("No state found") 610 } 611 612 // ScrollAPI provides private RPC methods to query the L1 message database. 613 type ScrollAPI struct { 614 eth *Ethereum 615 } 616 617 // l1MessageTxRPC is the RPC-layer representation of an L1 message. 618 type l1MessageTxRPC struct { 619 QueueIndex uint64 `json:"queueIndex"` 620 Gas uint64 `json:"gas"` 621 To *common.Address `json:"to"` 622 Value *hexutil.Big `json:"value"` 623 Data hexutil.Bytes `json:"data"` 624 Sender common.Address `json:"sender"` 625 Hash common.Hash `json:"hash"` 626 } 627 628 // NewScrollAPI creates a new RPC service to query the L1 message database. 629 func NewScrollAPI(eth *Ethereum) *ScrollAPI { 630 return &ScrollAPI{eth: eth} 631 } 632 633 // GetL1SyncHeight returns the latest synced L1 block height from the local database. 634 func (api *ScrollAPI) GetL1SyncHeight(ctx context.Context) (height *uint64, err error) { 635 return rawdb.ReadSyncedL1BlockNumber(api.eth.ChainDb()), nil 636 } 637 638 // GetL1MessageByIndex queries an L1 message by its index in the local database. 639 func (api *ScrollAPI) GetL1MessageByIndex(ctx context.Context, queueIndex uint64) (height *l1MessageTxRPC, err error) { 640 msg := rawdb.ReadL1Message(api.eth.ChainDb(), queueIndex) 641 if msg == nil { 642 return nil, nil 643 } 644 rpcMsg := l1MessageTxRPC{ 645 QueueIndex: msg.QueueIndex, 646 Gas: msg.Gas, 647 To: msg.To, 648 Value: (*hexutil.Big)(msg.Value), 649 Data: msg.Data, 650 Sender: msg.Sender, 651 Hash: types.NewTx(msg).Hash(), 652 } 653 return &rpcMsg, nil 654 } 655 656 // GetFirstQueueIndexNotInL2Block returns the first L1 message queue index that is 657 // not included in the chain up to and including the provided block. 658 func (api *ScrollAPI) GetFirstQueueIndexNotInL2Block(ctx context.Context, hash common.Hash) (queueIndex *uint64, err error) { 659 return rawdb.ReadFirstQueueIndexNotInL2Block(api.eth.ChainDb(), hash), nil 660 } 661 662 // GetLatestRelayedQueueIndex returns the highest L1 message queue index included in the canonical chain. 663 func (api *ScrollAPI) GetLatestRelayedQueueIndex(ctx context.Context) (queueIndex *uint64, err error) { 664 block := api.eth.blockchain.CurrentBlock() 665 queueIndex, err = api.GetFirstQueueIndexNotInL2Block(ctx, block.Hash()) 666 if queueIndex == nil || err != nil { 667 return queueIndex, err 668 } 669 if *queueIndex == 0 { 670 return nil, nil 671 } 672 lastIncluded := *queueIndex - 1 673 return &lastIncluded, nil 674 } 675 676 // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires 677 // a `ScrollAPI`. 678 func (api *ScrollAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, fullTx bool) (map[string]interface{}, error) { 679 fields, err := ethapi.RPCMarshalBlock(b, true, fullTx, api.eth.APIBackend.ChainConfig()) 680 if err != nil { 681 return nil, err 682 } 683 fields["totalDifficulty"] = (*hexutil.Big)(api.eth.APIBackend.GetTd(ctx, b.Hash())) 684 rc := rawdb.ReadBlockRowConsumption(api.eth.ChainDb(), b.Hash()) 685 if rc != nil { 686 fields["rowConsumption"] = rc 687 } else { 688 fields["rowConsumption"] = nil 689 } 690 return fields, err 691 } 692 693 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 694 // detail, otherwise only the transaction hash is returned. 695 func (api *ScrollAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) { 696 block, err := api.eth.APIBackend.BlockByHash(ctx, hash) 697 if block != nil { 698 return api.rpcMarshalBlock(ctx, block, fullTx) 699 } 700 return nil, err 701 } 702 703 // GetBlockByNumber returns the requested block. When fullTx is true all transactions in the block are returned in full 704 // detail, otherwise only the transaction hash is returned. 705 func (api *ScrollAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 706 block, err := api.eth.APIBackend.BlockByNumber(ctx, number) 707 if block != nil { 708 return api.rpcMarshalBlock(ctx, block, fullTx) 709 } 710 return nil, err 711 } 712 713 // GetNumSkippedTransactions returns the number of skipped transactions. 714 func (api *ScrollAPI) GetNumSkippedTransactions(ctx context.Context) (uint64, error) { 715 return rawdb.ReadNumSkippedTransactions(api.eth.ChainDb()), nil 716 } 717 718 // RPCTransaction is the standard RPC transaction return type with some additional skip-related fields. 719 type RPCTransaction struct { 720 ethapi.RPCTransaction 721 SkipReason string `json:"skipReason"` 722 SkipBlockNumber *hexutil.Big `json:"skipBlockNumber"` 723 SkipBlockHash *common.Hash `json:"skipBlockHash,omitempty"` 724 725 // wrapped traces, currently only available for `scroll_getSkippedTransaction` API, when `MinerStoreSkippedTxTracesFlag` is set 726 Traces *types.BlockTrace `json:"traces,omitempty"` 727 } 728 729 // GetSkippedTransaction returns a skipped transaction by its hash. 730 func (api *ScrollAPI) GetSkippedTransaction(ctx context.Context, hash common.Hash) (*RPCTransaction, error) { 731 stx := rawdb.ReadSkippedTransaction(api.eth.ChainDb(), hash) 732 if stx == nil { 733 return nil, nil 734 } 735 var rpcTx RPCTransaction 736 rpcTx.RPCTransaction = *ethapi.NewRPCTransaction(stx.Tx, common.Hash{}, 0, 0, nil, api.eth.blockchain.Config()) 737 rpcTx.SkipReason = stx.Reason 738 rpcTx.SkipBlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(stx.BlockNumber)) 739 rpcTx.SkipBlockHash = stx.BlockHash 740 if len(stx.TracesBytes) != 0 { 741 traces := &types.BlockTrace{} 742 if err := json.Unmarshal(stx.TracesBytes, traces); err != nil { 743 return nil, fmt.Errorf("fail to Unmarshal traces for skipped tx, hash: %s, err: %w", hash.String(), err) 744 } 745 rpcTx.Traces = traces 746 } 747 return &rpcTx, nil 748 } 749 750 // GetSkippedTransactionHashes returns a list of skipped transaction hashes between the two indices provided (inclusive). 751 func (api *ScrollAPI) GetSkippedTransactionHashes(ctx context.Context, from uint64, to uint64) ([]common.Hash, error) { 752 it := rawdb.IterateSkippedTransactionsFrom(api.eth.ChainDb(), from) 753 defer it.Release() 754 755 var hashes []common.Hash 756 757 for it.Next() { 758 if it.Index() > to { 759 break 760 } 761 hashes = append(hashes, it.TransactionHash()) 762 } 763 764 return hashes, nil 765 }