github.com/cryptotooltop/go-ethereum@v0.0.0-20231103184714-151d1922f3e5/internal/ethapi/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 ethapi 18 19 import ( 20 "context" 21 "errors" 22 "fmt" 23 "math/big" 24 "strings" 25 "time" 26 27 "github.com/davecgh/go-spew/spew" 28 "github.com/tyler-smith/go-bip39" 29 30 "github.com/scroll-tech/go-ethereum/accounts" 31 "github.com/scroll-tech/go-ethereum/accounts/abi" 32 "github.com/scroll-tech/go-ethereum/accounts/keystore" 33 "github.com/scroll-tech/go-ethereum/accounts/scwallet" 34 "github.com/scroll-tech/go-ethereum/common" 35 "github.com/scroll-tech/go-ethereum/common/hexutil" 36 "github.com/scroll-tech/go-ethereum/common/math" 37 "github.com/scroll-tech/go-ethereum/consensus/clique" 38 "github.com/scroll-tech/go-ethereum/consensus/ethash" 39 "github.com/scroll-tech/go-ethereum/consensus/misc" 40 "github.com/scroll-tech/go-ethereum/core" 41 "github.com/scroll-tech/go-ethereum/core/state" 42 "github.com/scroll-tech/go-ethereum/core/types" 43 "github.com/scroll-tech/go-ethereum/core/vm" 44 "github.com/scroll-tech/go-ethereum/crypto" 45 "github.com/scroll-tech/go-ethereum/crypto/codehash" 46 "github.com/scroll-tech/go-ethereum/log" 47 "github.com/scroll-tech/go-ethereum/p2p" 48 "github.com/scroll-tech/go-ethereum/params" 49 "github.com/scroll-tech/go-ethereum/rlp" 50 "github.com/scroll-tech/go-ethereum/rollup/fees" 51 "github.com/scroll-tech/go-ethereum/rpc" 52 ) 53 54 // PublicEthereumAPI provides an API to access Ethereum related information. 55 // It offers only methods that operate on public data that is freely available to anyone. 56 type PublicEthereumAPI struct { 57 b Backend 58 } 59 60 // NewPublicEthereumAPI creates a new Ethereum protocol API. 61 func NewPublicEthereumAPI(b Backend) *PublicEthereumAPI { 62 return &PublicEthereumAPI{b} 63 } 64 65 // GasPrice returns a suggestion for a gas price for legacy transactions. 66 func (s *PublicEthereumAPI) GasPrice(ctx context.Context) (*hexutil.Big, error) { 67 tipcap, err := s.b.SuggestGasTipCap(ctx) 68 if err != nil { 69 return nil, err 70 } 71 if head := s.b.CurrentHeader(); head.BaseFee != nil { 72 tipcap.Add(tipcap, head.BaseFee) 73 } 74 return (*hexutil.Big)(tipcap), err 75 } 76 77 // MaxPriorityFeePerGas returns a suggestion for a gas tip cap for dynamic fee transactions. 78 func (s *PublicEthereumAPI) MaxPriorityFeePerGas(ctx context.Context) (*hexutil.Big, error) { 79 tipcap, err := s.b.SuggestGasTipCap(ctx) 80 if err != nil { 81 return nil, err 82 } 83 return (*hexutil.Big)(tipcap), err 84 } 85 86 type feeHistoryResult struct { 87 OldestBlock *hexutil.Big `json:"oldestBlock"` 88 Reward [][]*hexutil.Big `json:"reward,omitempty"` 89 BaseFee []*hexutil.Big `json:"baseFeePerGas,omitempty"` 90 GasUsedRatio []float64 `json:"gasUsedRatio"` 91 } 92 93 func (s *PublicEthereumAPI) FeeHistory(ctx context.Context, blockCount rpc.DecimalOrHex, lastBlock rpc.BlockNumber, rewardPercentiles []float64) (*feeHistoryResult, error) { 94 oldest, reward, baseFee, gasUsed, err := s.b.FeeHistory(ctx, int(blockCount), lastBlock, rewardPercentiles) 95 if err != nil { 96 return nil, err 97 } 98 results := &feeHistoryResult{ 99 OldestBlock: (*hexutil.Big)(oldest), 100 GasUsedRatio: gasUsed, 101 } 102 if reward != nil { 103 results.Reward = make([][]*hexutil.Big, len(reward)) 104 for i, w := range reward { 105 results.Reward[i] = make([]*hexutil.Big, len(w)) 106 for j, v := range w { 107 results.Reward[i][j] = (*hexutil.Big)(v) 108 } 109 } 110 } 111 if baseFee != nil { 112 results.BaseFee = make([]*hexutil.Big, len(baseFee)) 113 for i, v := range baseFee { 114 results.BaseFee[i] = (*hexutil.Big)(v) 115 } 116 } 117 return results, nil 118 } 119 120 // Syncing returns false in case the node is currently not syncing with the network. It can be up to date or has not 121 // yet received the latest block headers from its pears. In case it is synchronizing: 122 // - startingBlock: block number this node started to synchronise from 123 // - currentBlock: block number this node is currently importing 124 // - highestBlock: block number of the highest block header this node has received from peers 125 // - pulledStates: number of state entries processed until now 126 // - knownStates: number of known state entries that still need to be pulled 127 func (s *PublicEthereumAPI) Syncing() (interface{}, error) { 128 progress := s.b.SyncProgress() 129 130 // Return not syncing if the synchronisation already completed 131 if progress.CurrentBlock >= progress.HighestBlock { 132 return false, nil 133 } 134 // Otherwise gather the block sync stats 135 return map[string]interface{}{ 136 "startingBlock": hexutil.Uint64(progress.StartingBlock), 137 "currentBlock": hexutil.Uint64(progress.CurrentBlock), 138 "highestBlock": hexutil.Uint64(progress.HighestBlock), 139 "pulledStates": hexutil.Uint64(progress.PulledStates), 140 "knownStates": hexutil.Uint64(progress.KnownStates), 141 }, nil 142 } 143 144 // PublicTxPoolAPI offers and API for the transaction pool. It only operates on data that is non confidential. 145 type PublicTxPoolAPI struct { 146 b Backend 147 } 148 149 // NewPublicTxPoolAPI creates a new tx pool service that gives information about the transaction pool. 150 func NewPublicTxPoolAPI(b Backend) *PublicTxPoolAPI { 151 return &PublicTxPoolAPI{b} 152 } 153 154 // Content returns the transactions contained within the transaction pool. 155 func (s *PublicTxPoolAPI) Content() map[string]map[string]map[string]*RPCTransaction { 156 content := map[string]map[string]map[string]*RPCTransaction{ 157 "pending": make(map[string]map[string]*RPCTransaction), 158 "queued": make(map[string]map[string]*RPCTransaction), 159 } 160 pending, queue := s.b.TxPoolContent() 161 curHeader := s.b.CurrentHeader() 162 // Flatten the pending transactions 163 for account, txs := range pending { 164 dump := make(map[string]*RPCTransaction) 165 for _, tx := range txs { 166 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()) 167 } 168 content["pending"][account.Hex()] = dump 169 } 170 // Flatten the queued transactions 171 for account, txs := range queue { 172 dump := make(map[string]*RPCTransaction) 173 for _, tx := range txs { 174 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()) 175 } 176 content["queued"][account.Hex()] = dump 177 } 178 return content 179 } 180 181 // ContentFrom returns the transactions contained within the transaction pool. 182 func (s *PublicTxPoolAPI) ContentFrom(addr common.Address) map[string]map[string]*RPCTransaction { 183 content := make(map[string]map[string]*RPCTransaction, 2) 184 pending, queue := s.b.TxPoolContentFrom(addr) 185 curHeader := s.b.CurrentHeader() 186 187 // Build the pending transactions 188 dump := make(map[string]*RPCTransaction, len(pending)) 189 for _, tx := range pending { 190 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()) 191 } 192 content["pending"] = dump 193 194 // Build the queued transactions 195 dump = make(map[string]*RPCTransaction, len(queue)) 196 for _, tx := range queue { 197 dump[fmt.Sprintf("%d", tx.Nonce())] = newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig()) 198 } 199 content["queued"] = dump 200 201 return content 202 } 203 204 // Status returns the number of pending and queued transaction in the pool. 205 func (s *PublicTxPoolAPI) Status() map[string]hexutil.Uint { 206 pending, queue := s.b.Stats() 207 return map[string]hexutil.Uint{ 208 "pending": hexutil.Uint(pending), 209 "queued": hexutil.Uint(queue), 210 } 211 } 212 213 // Inspect retrieves the content of the transaction pool and flattens it into an 214 // easily inspectable list. 215 func (s *PublicTxPoolAPI) Inspect() map[string]map[string]map[string]string { 216 content := map[string]map[string]map[string]string{ 217 "pending": make(map[string]map[string]string), 218 "queued": make(map[string]map[string]string), 219 } 220 pending, queue := s.b.TxPoolContent() 221 222 // Define a formatter to flatten a transaction into a string 223 var format = func(tx *types.Transaction) string { 224 if to := tx.To(); to != nil { 225 return fmt.Sprintf("%s: %v wei + %v gas × %v wei", tx.To().Hex(), tx.Value(), tx.Gas(), tx.GasPrice()) 226 } 227 return fmt.Sprintf("contract creation: %v wei + %v gas × %v wei", tx.Value(), tx.Gas(), tx.GasPrice()) 228 } 229 // Flatten the pending transactions 230 for account, txs := range pending { 231 dump := make(map[string]string) 232 for _, tx := range txs { 233 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 234 } 235 content["pending"][account.Hex()] = dump 236 } 237 // Flatten the queued transactions 238 for account, txs := range queue { 239 dump := make(map[string]string) 240 for _, tx := range txs { 241 dump[fmt.Sprintf("%d", tx.Nonce())] = format(tx) 242 } 243 content["queued"][account.Hex()] = dump 244 } 245 return content 246 } 247 248 // PublicAccountAPI provides an API to access accounts managed by this node. 249 // It offers only methods that can retrieve accounts. 250 type PublicAccountAPI struct { 251 am *accounts.Manager 252 } 253 254 // NewPublicAccountAPI creates a new PublicAccountAPI. 255 func NewPublicAccountAPI(am *accounts.Manager) *PublicAccountAPI { 256 return &PublicAccountAPI{am: am} 257 } 258 259 // Accounts returns the collection of accounts this node manages 260 func (s *PublicAccountAPI) Accounts() []common.Address { 261 return s.am.Accounts() 262 } 263 264 // PrivateAccountAPI provides an API to access accounts managed by this node. 265 // It offers methods to create, (un)lock en list accounts. Some methods accept 266 // passwords and are therefore considered private by default. 267 type PrivateAccountAPI struct { 268 am *accounts.Manager 269 nonceLock *AddrLocker 270 b Backend 271 } 272 273 // NewPrivateAccountAPI create a new PrivateAccountAPI. 274 func NewPrivateAccountAPI(b Backend, nonceLock *AddrLocker) *PrivateAccountAPI { 275 return &PrivateAccountAPI{ 276 am: b.AccountManager(), 277 nonceLock: nonceLock, 278 b: b, 279 } 280 } 281 282 // listAccounts will return a list of addresses for accounts this node manages. 283 func (s *PrivateAccountAPI) ListAccounts() []common.Address { 284 return s.am.Accounts() 285 } 286 287 // rawWallet is a JSON representation of an accounts.Wallet interface, with its 288 // data contents extracted into plain fields. 289 type rawWallet struct { 290 URL string `json:"url"` 291 Status string `json:"status"` 292 Failure string `json:"failure,omitempty"` 293 Accounts []accounts.Account `json:"accounts,omitempty"` 294 } 295 296 // ListWallets will return a list of wallets this node manages. 297 func (s *PrivateAccountAPI) ListWallets() []rawWallet { 298 wallets := make([]rawWallet, 0) // return [] instead of nil if empty 299 for _, wallet := range s.am.Wallets() { 300 status, failure := wallet.Status() 301 302 raw := rawWallet{ 303 URL: wallet.URL().String(), 304 Status: status, 305 Accounts: wallet.Accounts(), 306 } 307 if failure != nil { 308 raw.Failure = failure.Error() 309 } 310 wallets = append(wallets, raw) 311 } 312 return wallets 313 } 314 315 // OpenWallet initiates a hardware wallet opening procedure, establishing a USB 316 // connection and attempting to authenticate via the provided passphrase. Note, 317 // the method may return an extra challenge requiring a second open (e.g. the 318 // Trezor PIN matrix challenge). 319 func (s *PrivateAccountAPI) OpenWallet(url string, passphrase *string) error { 320 wallet, err := s.am.Wallet(url) 321 if err != nil { 322 return err 323 } 324 pass := "" 325 if passphrase != nil { 326 pass = *passphrase 327 } 328 return wallet.Open(pass) 329 } 330 331 // DeriveAccount requests a HD wallet to derive a new account, optionally pinning 332 // it for later reuse. 333 func (s *PrivateAccountAPI) DeriveAccount(url string, path string, pin *bool) (accounts.Account, error) { 334 wallet, err := s.am.Wallet(url) 335 if err != nil { 336 return accounts.Account{}, err 337 } 338 derivPath, err := accounts.ParseDerivationPath(path) 339 if err != nil { 340 return accounts.Account{}, err 341 } 342 if pin == nil { 343 pin = new(bool) 344 } 345 return wallet.Derive(derivPath, *pin) 346 } 347 348 // NewAccount will create a new account and returns the address for the new account. 349 func (s *PrivateAccountAPI) NewAccount(password string) (common.Address, error) { 350 ks, err := fetchKeystore(s.am) 351 if err != nil { 352 return common.Address{}, err 353 } 354 acc, err := ks.NewAccount(password) 355 if err == nil { 356 log.Info("Your new key was generated", "address", acc.Address) 357 log.Warn("Please backup your key file!", "path", acc.URL.Path) 358 log.Warn("Please remember your password!") 359 return acc.Address, nil 360 } 361 return common.Address{}, err 362 } 363 364 // fetchKeystore retrieves the encrypted keystore from the account manager. 365 func fetchKeystore(am *accounts.Manager) (*keystore.KeyStore, error) { 366 if ks := am.Backends(keystore.KeyStoreType); len(ks) > 0 { 367 return ks[0].(*keystore.KeyStore), nil 368 } 369 return nil, errors.New("local keystore not used") 370 } 371 372 // ImportRawKey stores the given hex encoded ECDSA key into the key directory, 373 // encrypting it with the passphrase. 374 func (s *PrivateAccountAPI) ImportRawKey(privkey string, password string) (common.Address, error) { 375 key, err := crypto.HexToECDSA(privkey) 376 if err != nil { 377 return common.Address{}, err 378 } 379 ks, err := fetchKeystore(s.am) 380 if err != nil { 381 return common.Address{}, err 382 } 383 acc, err := ks.ImportECDSA(key, password) 384 return acc.Address, err 385 } 386 387 // UnlockAccount will unlock the account associated with the given address with 388 // the given password for duration seconds. If duration is nil it will use a 389 // default of 300 seconds. It returns an indication if the account was unlocked. 390 func (s *PrivateAccountAPI) UnlockAccount(ctx context.Context, addr common.Address, password string, duration *uint64) (bool, error) { 391 // When the API is exposed by external RPC(http, ws etc), unless the user 392 // explicitly specifies to allow the insecure account unlocking, otherwise 393 // it is disabled. 394 if s.b.ExtRPCEnabled() && !s.b.AccountManager().Config().InsecureUnlockAllowed { 395 return false, errors.New("account unlock with HTTP access is forbidden") 396 } 397 398 const max = uint64(time.Duration(math.MaxInt64) / time.Second) 399 var d time.Duration 400 if duration == nil { 401 d = 300 * time.Second 402 } else if *duration > max { 403 return false, errors.New("unlock duration too large") 404 } else { 405 d = time.Duration(*duration) * time.Second 406 } 407 ks, err := fetchKeystore(s.am) 408 if err != nil { 409 return false, err 410 } 411 err = ks.TimedUnlock(accounts.Account{Address: addr}, password, d) 412 if err != nil { 413 log.Warn("Failed account unlock attempt", "address", addr, "err", err) 414 } 415 return err == nil, err 416 } 417 418 // LockAccount will lock the account associated with the given address when it's unlocked. 419 func (s *PrivateAccountAPI) LockAccount(addr common.Address) bool { 420 if ks, err := fetchKeystore(s.am); err == nil { 421 return ks.Lock(addr) == nil 422 } 423 return false 424 } 425 426 // signTransaction sets defaults and signs the given transaction 427 // NOTE: the caller needs to ensure that the nonceLock is held, if applicable, 428 // and release it after the transaction has been submitted to the tx pool 429 func (s *PrivateAccountAPI) signTransaction(ctx context.Context, args *TransactionArgs, passwd string) (*types.Transaction, error) { 430 // Look up the wallet containing the requested signer 431 account := accounts.Account{Address: args.from()} 432 wallet, err := s.am.Find(account) 433 if err != nil { 434 return nil, err 435 } 436 // Set some sanity defaults and terminate on failure 437 if err := args.setDefaults(ctx, s.b); err != nil { 438 return nil, err 439 } 440 // Assemble the transaction and sign with the wallet 441 tx := args.toTransaction() 442 443 return wallet.SignTxWithPassphrase(account, passwd, tx, s.b.ChainConfig().ChainID) 444 } 445 446 // SendTransaction will create a transaction from the given arguments and 447 // tries to sign it with the key associated with args.From. If the given 448 // passwd isn't able to decrypt the key it fails. 449 func (s *PrivateAccountAPI) SendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) { 450 if args.Nonce == nil { 451 // Hold the addresse's mutex around signing to prevent concurrent assignment of 452 // the same nonce to multiple accounts. 453 s.nonceLock.LockAddr(args.from()) 454 defer s.nonceLock.UnlockAddr(args.from()) 455 } 456 signed, err := s.signTransaction(ctx, &args, passwd) 457 if err != nil { 458 log.Warn("Failed transaction send attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err) 459 return common.Hash{}, err 460 } 461 return SubmitTransaction(ctx, s.b, signed) 462 } 463 464 // SignTransaction will create a transaction from the given arguments and 465 // tries to sign it with the key associated with args.From. If the given passwd isn't 466 // able to decrypt the key it fails. The transaction is returned in RLP-form, not broadcast 467 // to other nodes 468 func (s *PrivateAccountAPI) SignTransaction(ctx context.Context, args TransactionArgs, passwd string) (*SignTransactionResult, error) { 469 // No need to obtain the noncelock mutex, since we won't be sending this 470 // tx into the transaction pool, but right back to the user 471 if args.From == nil { 472 return nil, fmt.Errorf("sender not specified") 473 } 474 if args.Gas == nil { 475 return nil, fmt.Errorf("gas not specified") 476 } 477 if args.GasPrice == nil && (args.MaxFeePerGas == nil || args.MaxPriorityFeePerGas == nil) { 478 return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas") 479 } 480 if args.Nonce == nil { 481 return nil, fmt.Errorf("nonce not specified") 482 } 483 // Before actually signing the transaction, ensure the transaction fee is reasonable. 484 tx := args.toTransaction() 485 if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil { 486 return nil, err 487 } 488 signed, err := s.signTransaction(ctx, &args, passwd) 489 if err != nil { 490 log.Warn("Failed transaction sign attempt", "from", args.from(), "to", args.To, "value", args.Value.ToInt(), "err", err) 491 return nil, err 492 } 493 data, err := signed.MarshalBinary() 494 if err != nil { 495 return nil, err 496 } 497 return &SignTransactionResult{data, signed}, nil 498 } 499 500 // Sign calculates an Ethereum ECDSA signature for: 501 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message)) 502 // 503 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 504 // where the V value will be 27 or 28 for legacy reasons. 505 // 506 // The key used to calculate the signature is decrypted with the given password. 507 // 508 // https://github.com/scroll-tech/go-ethereum/wiki/Management-APIs#personal_sign 509 func (s *PrivateAccountAPI) Sign(ctx context.Context, data hexutil.Bytes, addr common.Address, passwd string) (hexutil.Bytes, error) { 510 // Look up the wallet containing the requested signer 511 account := accounts.Account{Address: addr} 512 513 wallet, err := s.b.AccountManager().Find(account) 514 if err != nil { 515 return nil, err 516 } 517 // Assemble sign the data with the wallet 518 signature, err := wallet.SignTextWithPassphrase(account, passwd, data) 519 if err != nil { 520 log.Warn("Failed data sign attempt", "address", addr, "err", err) 521 return nil, err 522 } 523 signature[crypto.RecoveryIDOffset] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 524 return signature, nil 525 } 526 527 // EcRecover returns the address for the account that was used to create the signature. 528 // Note, this function is compatible with eth_sign and personal_sign. As such it recovers 529 // the address of: 530 // hash = keccak256("\x19Ethereum Signed Message:\n"${message length}${message}) 531 // addr = ecrecover(hash, signature) 532 // 533 // Note, the signature must conform to the secp256k1 curve R, S and V values, where 534 // the V value must be 27 or 28 for legacy reasons. 535 // 536 // https://github.com/scroll-tech/go-ethereum/wiki/Management-APIs#personal_ecRecover 537 func (s *PrivateAccountAPI) EcRecover(ctx context.Context, data, sig hexutil.Bytes) (common.Address, error) { 538 if len(sig) != crypto.SignatureLength { 539 return common.Address{}, fmt.Errorf("signature must be %d bytes long", crypto.SignatureLength) 540 } 541 if sig[crypto.RecoveryIDOffset] != 27 && sig[crypto.RecoveryIDOffset] != 28 { 542 return common.Address{}, fmt.Errorf("invalid Ethereum signature (V is not 27 or 28)") 543 } 544 sig[crypto.RecoveryIDOffset] -= 27 // Transform yellow paper V from 27/28 to 0/1 545 546 rpk, err := crypto.SigToPub(accounts.TextHash(data), sig) 547 if err != nil { 548 return common.Address{}, err 549 } 550 return crypto.PubkeyToAddress(*rpk), nil 551 } 552 553 // SignAndSendTransaction was renamed to SendTransaction. This method is deprecated 554 // and will be removed in the future. It primary goal is to give clients time to update. 555 func (s *PrivateAccountAPI) SignAndSendTransaction(ctx context.Context, args TransactionArgs, passwd string) (common.Hash, error) { 556 return s.SendTransaction(ctx, args, passwd) 557 } 558 559 // InitializeWallet initializes a new wallet at the provided URL, by generating and returning a new private key. 560 func (s *PrivateAccountAPI) InitializeWallet(ctx context.Context, url string) (string, error) { 561 wallet, err := s.am.Wallet(url) 562 if err != nil { 563 return "", err 564 } 565 566 entropy, err := bip39.NewEntropy(256) 567 if err != nil { 568 return "", err 569 } 570 571 mnemonic, err := bip39.NewMnemonic(entropy) 572 if err != nil { 573 return "", err 574 } 575 576 seed := bip39.NewSeed(mnemonic, "") 577 578 switch wallet := wallet.(type) { 579 case *scwallet.Wallet: 580 return mnemonic, wallet.Initialize(seed) 581 default: 582 return "", fmt.Errorf("specified wallet does not support initialization") 583 } 584 } 585 586 // Unpair deletes a pairing between wallet and geth. 587 func (s *PrivateAccountAPI) Unpair(ctx context.Context, url string, pin string) error { 588 wallet, err := s.am.Wallet(url) 589 if err != nil { 590 return err 591 } 592 593 switch wallet := wallet.(type) { 594 case *scwallet.Wallet: 595 return wallet.Unpair([]byte(pin)) 596 default: 597 return fmt.Errorf("specified wallet does not support pairing") 598 } 599 } 600 601 // PublicBlockChainAPI provides an API to access the Ethereum blockchain. 602 // It offers only methods that operate on public data that is freely available to anyone. 603 type PublicBlockChainAPI struct { 604 b Backend 605 } 606 607 // NewPublicBlockChainAPI creates a new Ethereum blockchain API. 608 func NewPublicBlockChainAPI(b Backend) *PublicBlockChainAPI { 609 return &PublicBlockChainAPI{b} 610 } 611 612 // ChainId is the EIP-155 replay-protection chain id for the current ethereum chain config. 613 func (api *PublicBlockChainAPI) ChainId() (*hexutil.Big, error) { 614 // if current block is at or past the EIP-155 replay-protection fork block, return chainID from config 615 if config := api.b.ChainConfig(); config.IsEIP155(api.b.CurrentBlock().Number()) { 616 return (*hexutil.Big)(config.ChainID), nil 617 } 618 return nil, fmt.Errorf("chain not synced beyond EIP-155 replay-protection fork block") 619 } 620 621 // BlockNumber returns the block number of the chain head. 622 func (s *PublicBlockChainAPI) BlockNumber() hexutil.Uint64 { 623 header, _ := s.b.HeaderByNumber(context.Background(), rpc.LatestBlockNumber) // latest header should always be available 624 return hexutil.Uint64(header.Number.Uint64()) 625 } 626 627 // GetBalance returns the amount of wei for the given address in the state of the 628 // given block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta 629 // block numbers are also allowed. 630 func (s *PublicBlockChainAPI) GetBalance(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Big, error) { 631 state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 632 if state == nil || err != nil { 633 return nil, err 634 } 635 return (*hexutil.Big)(state.GetBalance(address)), state.Error() 636 } 637 638 // Result structs for GetProof 639 type AccountResult struct { 640 Address common.Address `json:"address"` 641 AccountProof []string `json:"accountProof"` 642 Balance *hexutil.Big `json:"balance"` 643 PoseidonCodeHash common.Hash `json:"poseidonCodeHash"` 644 KeccakCodeHash common.Hash `json:"keccakCodeHash"` 645 CodeSize hexutil.Uint64 `json:"codeSize"` 646 Nonce hexutil.Uint64 `json:"nonce"` 647 StorageHash common.Hash `json:"storageHash"` 648 StorageProof []StorageResult `json:"storageProof"` 649 } 650 651 type StorageResult struct { 652 Key string `json:"key"` 653 Value *hexutil.Big `json:"value"` 654 Proof []string `json:"proof"` 655 } 656 657 // GetProof returns the Merkle-proof for a given account and optionally some storage keys. 658 func (s *PublicBlockChainAPI) GetProof(ctx context.Context, address common.Address, storageKeys []string, blockNrOrHash rpc.BlockNumberOrHash) (*AccountResult, error) { 659 state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 660 if state == nil || err != nil { 661 return nil, err 662 } 663 664 zktrie := s.b.ChainConfig().Scroll.ZktrieEnabled() 665 666 storageTrie := state.StorageTrie(address) 667 var storageHash common.Hash 668 if !zktrie { 669 storageHash = types.EmptyRootHash 670 } 671 keccakCodeHash := state.GetKeccakCodeHash(address) 672 poseidonCodeHash := state.GetPoseidonCodeHash(address) 673 storageProof := make([]StorageResult, len(storageKeys)) 674 675 // if we have a storageTrie, (which means the account exists), we can update the storagehash 676 if storageTrie != nil { 677 storageHash = storageTrie.Hash() 678 } else { 679 // no storageTrie means the account does not exist, so the codeHash is the hash of an empty bytearray. 680 keccakCodeHash = codehash.EmptyKeccakCodeHash 681 poseidonCodeHash = codehash.EmptyPoseidonCodeHash 682 } 683 684 // create the proof for the storageKeys 685 for i, key := range storageKeys { 686 if storageTrie != nil { 687 proof, storageError := state.GetStorageProof(address, common.HexToHash(key)) 688 if storageError != nil { 689 return nil, storageError 690 } 691 storageProof[i] = StorageResult{key, (*hexutil.Big)(state.GetState(address, common.HexToHash(key)).Big()), toHexSlice(proof)} 692 } else { 693 storageProof[i] = StorageResult{key, &hexutil.Big{}, []string{}} 694 } 695 } 696 697 // create the accountProof 698 accountProof, proofErr := state.GetProof(address) 699 if proofErr != nil { 700 return nil, proofErr 701 } 702 703 return &AccountResult{ 704 Address: address, 705 AccountProof: toHexSlice(accountProof), 706 Balance: (*hexutil.Big)(state.GetBalance(address)), 707 KeccakCodeHash: keccakCodeHash, 708 PoseidonCodeHash: poseidonCodeHash, 709 CodeSize: hexutil.Uint64(state.GetCodeSize(address)), 710 Nonce: hexutil.Uint64(state.GetNonce(address)), 711 StorageHash: storageHash, 712 StorageProof: storageProof, 713 }, state.Error() 714 } 715 716 // GetHeaderByNumber returns the requested canonical block header. 717 // * When blockNr is -1 the chain head is returned. 718 // * When blockNr is -2 the pending chain head is returned. 719 func (s *PublicBlockChainAPI) GetHeaderByNumber(ctx context.Context, number rpc.BlockNumber) (map[string]interface{}, error) { 720 header, err := s.b.HeaderByNumber(ctx, number) 721 if header != nil && err == nil { 722 response := s.rpcMarshalHeader(ctx, header) 723 if number == rpc.PendingBlockNumber { 724 // Pending header need to nil out a few fields 725 for _, field := range []string{"hash", "nonce", "miner"} { 726 response[field] = nil 727 } 728 } 729 return response, err 730 } 731 return nil, err 732 } 733 734 // GetHeaderByHash returns the requested header by hash. 735 func (s *PublicBlockChainAPI) GetHeaderByHash(ctx context.Context, hash common.Hash) map[string]interface{} { 736 header, _ := s.b.HeaderByHash(ctx, hash) 737 if header != nil { 738 return s.rpcMarshalHeader(ctx, header) 739 } 740 return nil 741 } 742 743 // GetBlockByNumber returns the requested canonical block. 744 // * When blockNr is -1 the chain head is returned. 745 // * When blockNr is -2 the pending chain head is returned. 746 // * When fullTx is true all transactions in the block are returned, otherwise 747 // only the transaction hash is returned. 748 func (s *PublicBlockChainAPI) GetBlockByNumber(ctx context.Context, number rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) { 749 block, err := s.b.BlockByNumber(ctx, number) 750 if block != nil && err == nil { 751 response, err := s.rpcMarshalBlock(ctx, block, true, fullTx) 752 if err == nil && number == rpc.PendingBlockNumber { 753 // Pending blocks need to nil out a few fields 754 for _, field := range []string{"hash", "nonce", "miner"} { 755 response[field] = nil 756 } 757 } 758 return response, err 759 } 760 return nil, err 761 } 762 763 // GetBlockByHash returns the requested block. When fullTx is true all transactions in the block are returned in full 764 // detail, otherwise only the transaction hash is returned. 765 func (s *PublicBlockChainAPI) GetBlockByHash(ctx context.Context, hash common.Hash, fullTx bool) (map[string]interface{}, error) { 766 block, err := s.b.BlockByHash(ctx, hash) 767 if block != nil { 768 return s.rpcMarshalBlock(ctx, block, true, fullTx) 769 } 770 return nil, err 771 } 772 773 // GetUncleByBlockNumberAndIndex returns the uncle block for the given block hash and index. When fullTx is true 774 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 775 func (s *PublicBlockChainAPI) GetUncleByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) (map[string]interface{}, error) { 776 block, err := s.b.BlockByNumber(ctx, blockNr) 777 if block != nil { 778 uncles := block.Uncles() 779 if index >= hexutil.Uint(len(uncles)) { 780 log.Debug("Requested uncle not found", "number", blockNr, "hash", block.Hash(), "index", index) 781 return nil, nil 782 } 783 block = types.NewBlockWithHeader(uncles[index]) 784 return s.rpcMarshalBlock(ctx, block, false, false) 785 } 786 return nil, err 787 } 788 789 // GetUncleByBlockHashAndIndex returns the uncle block for the given block hash and index. When fullTx is true 790 // all transactions in the block are returned in full detail, otherwise only the transaction hash is returned. 791 func (s *PublicBlockChainAPI) GetUncleByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) (map[string]interface{}, error) { 792 block, err := s.b.BlockByHash(ctx, blockHash) 793 if block != nil { 794 uncles := block.Uncles() 795 if index >= hexutil.Uint(len(uncles)) { 796 log.Debug("Requested uncle not found", "number", block.Number(), "hash", blockHash, "index", index) 797 return nil, nil 798 } 799 block = types.NewBlockWithHeader(uncles[index]) 800 return s.rpcMarshalBlock(ctx, block, false, false) 801 } 802 return nil, err 803 } 804 805 // GetUncleCountByBlockNumber returns number of uncles in the block for the given block number 806 func (s *PublicBlockChainAPI) GetUncleCountByBlockNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 807 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 808 n := hexutil.Uint(len(block.Uncles())) 809 return &n 810 } 811 return nil 812 } 813 814 // GetUncleCountByBlockHash returns number of uncles in the block for the given block hash 815 func (s *PublicBlockChainAPI) GetUncleCountByBlockHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 816 if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil { 817 n := hexutil.Uint(len(block.Uncles())) 818 return &n 819 } 820 return nil 821 } 822 823 // GetCode returns the code stored at the given address in the state for the given block number. 824 func (s *PublicBlockChainAPI) GetCode(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 825 state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 826 if state == nil || err != nil { 827 return nil, err 828 } 829 code := state.GetCode(address) 830 return code, state.Error() 831 } 832 833 // GetStorageAt returns the storage from the state at the given address, key and 834 // block number. The rpc.LatestBlockNumber and rpc.PendingBlockNumber meta block 835 // numbers are also allowed. 836 func (s *PublicBlockChainAPI) GetStorageAt(ctx context.Context, address common.Address, key string, blockNrOrHash rpc.BlockNumberOrHash) (hexutil.Bytes, error) { 837 state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 838 if state == nil || err != nil { 839 return nil, err 840 } 841 res := state.GetState(address, common.HexToHash(key)) 842 return res[:], state.Error() 843 } 844 845 // OverrideAccount indicates the overriding fields of account during the execution 846 // of a message call. 847 // Note, state and stateDiff can't be specified at the same time. If state is 848 // set, message execution will only use the data in the given state. Otherwise 849 // if statDiff is set, all diff will be applied first and then execute the call 850 // message. 851 type OverrideAccount struct { 852 Nonce *hexutil.Uint64 `json:"nonce"` 853 Code *hexutil.Bytes `json:"code"` 854 Balance **hexutil.Big `json:"balance"` 855 State *map[common.Hash]common.Hash `json:"state"` 856 StateDiff *map[common.Hash]common.Hash `json:"stateDiff"` 857 } 858 859 // StateOverride is the collection of overridden accounts. 860 type StateOverride map[common.Address]OverrideAccount 861 862 // Apply overrides the fields of specified accounts into the given state. 863 func (diff *StateOverride) Apply(state *state.StateDB) error { 864 if diff == nil { 865 return nil 866 } 867 for addr, account := range *diff { 868 // Override account nonce. 869 if account.Nonce != nil { 870 state.SetNonce(addr, uint64(*account.Nonce)) 871 } 872 // Override account(contract) code. 873 if account.Code != nil { 874 state.SetCode(addr, *account.Code) 875 } 876 // Override account balance. 877 if account.Balance != nil { 878 state.SetBalance(addr, (*big.Int)(*account.Balance)) 879 } 880 if account.State != nil && account.StateDiff != nil { 881 return fmt.Errorf("account %s has both 'state' and 'stateDiff'", addr.Hex()) 882 } 883 // Replace entire state if caller requires. 884 if account.State != nil { 885 state.SetStorage(addr, *account.State) 886 } 887 // Apply state diff into specified accounts. 888 if account.StateDiff != nil { 889 for key, value := range *account.StateDiff { 890 state.SetState(addr, key, value) 891 } 892 } 893 } 894 return nil 895 } 896 897 func EstimateL1MsgFee(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64, config *params.ChainConfig) (*big.Int, error) { 898 if !config.Scroll.FeeVaultEnabled() { 899 return big.NewInt(0), nil 900 } 901 902 state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 903 if state == nil || err != nil { 904 return nil, err 905 } 906 if err := overrides.Apply(state); err != nil { 907 return nil, err 908 } 909 // Setup context so it may be cancelled the call has completed 910 // or, in case of unmetered gas, setup a context with a timeout. 911 var cancel context.CancelFunc 912 if timeout > 0 { 913 ctx, cancel = context.WithTimeout(ctx, timeout) 914 } else { 915 ctx, cancel = context.WithCancel(ctx) 916 } 917 // Make sure the context is cancelled when the call has completed 918 // this makes sure resources are cleaned up. 919 defer cancel() 920 921 // Get a new instance of the EVM. 922 msg, err := args.ToMessage(globalGasCap, header.BaseFee) 923 if err != nil { 924 return nil, err 925 } 926 evm, _, err := b.GetEVM(ctx, msg, state, header, &vm.Config{NoBaseFee: true}) 927 if err != nil { 928 return nil, err 929 } 930 // Wait for the context to be done and cancel the evm. Even if the 931 // EVM has finished, cancelling may be done (repeatedly) 932 go func() { 933 <-ctx.Done() 934 evm.Cancel() 935 }() 936 937 signer := types.MakeSigner(config, header.Number) 938 return fees.EstimateL1DataFeeForMessage(msg, header.BaseFee, config.ChainID, signer, evm.StateDB) 939 } 940 941 func DoCall(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride, timeout time.Duration, globalGasCap uint64) (*core.ExecutionResult, error) { 942 defer func(start time.Time) { log.Debug("Executing EVM call finished", "runtime", time.Since(start)) }(time.Now()) 943 944 state, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 945 if state == nil || err != nil { 946 return nil, err 947 } 948 if err := overrides.Apply(state); err != nil { 949 return nil, err 950 } 951 // Setup context so it may be cancelled the call has completed 952 // or, in case of unmetered gas, setup a context with a timeout. 953 var cancel context.CancelFunc 954 if timeout > 0 { 955 ctx, cancel = context.WithTimeout(ctx, timeout) 956 } else { 957 ctx, cancel = context.WithCancel(ctx) 958 } 959 // Make sure the context is cancelled when the call has completed 960 // this makes sure resources are cleaned up. 961 defer cancel() 962 963 // Get a new instance of the EVM. 964 msg, err := args.ToMessage(globalGasCap, header.BaseFee) 965 if err != nil { 966 return nil, err 967 } 968 evm, vmError, err := b.GetEVM(ctx, msg, state, header, &vm.Config{NoBaseFee: true}) 969 if err != nil { 970 return nil, err 971 } 972 // Wait for the context to be done and cancel the evm. Even if the 973 // EVM has finished, cancelling may be done (repeatedly) 974 go func() { 975 <-ctx.Done() 976 evm.Cancel() 977 }() 978 979 // Execute the message. 980 gp := new(core.GasPool).AddGas(math.MaxUint64) 981 982 result, err := core.ApplyMessage(evm, msg, gp, common.Big0) 983 if err := vmError(); err != nil { 984 return nil, err 985 } 986 987 // If the timer caused an abort, return an appropriate error message 988 if evm.Cancelled() { 989 return nil, fmt.Errorf("execution aborted (timeout = %v)", timeout) 990 } 991 if err != nil { 992 return result, fmt.Errorf("err: %w (supplied gas %d)", err, msg.Gas()) 993 } 994 return result, nil 995 } 996 997 func newRevertError(result *core.ExecutionResult) *revertError { 998 reason, errUnpack := abi.UnpackRevert(result.Revert()) 999 err := errors.New("execution reverted") 1000 if errUnpack == nil { 1001 err = fmt.Errorf("execution reverted: %v", reason) 1002 } 1003 return &revertError{ 1004 error: err, 1005 reason: hexutil.Encode(result.Revert()), 1006 } 1007 } 1008 1009 // revertError is an API error that encompassas an EVM revertal with JSON error 1010 // code and a binary data blob. 1011 type revertError struct { 1012 error 1013 reason string // revert reason hex encoded 1014 } 1015 1016 // ErrorCode returns the JSON error code for a revertal. 1017 // See: https://github.com/ethereum/wiki/wiki/JSON-RPC-Error-Codes-Improvement-Proposal 1018 func (e *revertError) ErrorCode() int { 1019 return 3 1020 } 1021 1022 // ErrorData returns the hex encoded revert reason. 1023 func (e *revertError) ErrorData() interface{} { 1024 return e.reason 1025 } 1026 1027 // Call executes the given transaction on the state for the given block number. 1028 // 1029 // Additionally, the caller can specify a batch of contract for fields overriding. 1030 // 1031 // Note, this function doesn't make and changes in the state/blockchain and is 1032 // useful to execute and retrieve values. 1033 func (s *PublicBlockChainAPI) Call(ctx context.Context, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, overrides *StateOverride) (hexutil.Bytes, error) { 1034 result, err := DoCall(ctx, s.b, args, blockNrOrHash, overrides, s.b.RPCEVMTimeout(), s.b.RPCGasCap()) 1035 if err != nil { 1036 return nil, err 1037 } 1038 // If the result contains a revert reason, try to unpack and return it. 1039 if len(result.Revert()) > 0 { 1040 return nil, newRevertError(result) 1041 } 1042 return result.Return(), result.Err 1043 } 1044 1045 func DoEstimateGas(ctx context.Context, b Backend, args TransactionArgs, blockNrOrHash rpc.BlockNumberOrHash, gasCap uint64) (hexutil.Uint64, error) { 1046 // Binary search the gas requirement, as it may be higher than the amount used 1047 var ( 1048 lo uint64 = params.TxGas - 1 1049 hi uint64 1050 cap uint64 1051 ) 1052 // Use zero address if sender unspecified. 1053 if args.From == nil { 1054 args.From = new(common.Address) 1055 } 1056 // Determine the highest gas limit can be used during the estimation. 1057 if args.Gas != nil && uint64(*args.Gas) >= params.TxGas { 1058 hi = uint64(*args.Gas) 1059 } else { 1060 // Retrieve the block to act as the gas ceiling 1061 block, err := b.BlockByNumberOrHash(ctx, blockNrOrHash) 1062 if err != nil { 1063 return 0, err 1064 } 1065 if block == nil { 1066 return 0, errors.New("block not found") 1067 } 1068 hi = block.GasLimit() 1069 } 1070 // Normalize the max fee per gas the call is willing to spend. 1071 var feeCap *big.Int 1072 if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) { 1073 return 0, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified") 1074 } else if args.GasPrice != nil { 1075 feeCap = args.GasPrice.ToInt() 1076 } else if args.MaxFeePerGas != nil { 1077 feeCap = args.MaxFeePerGas.ToInt() 1078 } else { 1079 feeCap = common.Big0 1080 } 1081 // Recap the highest gas limit with account's available balance. 1082 if feeCap.BitLen() != 0 { 1083 state, _, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 1084 if err != nil { 1085 return 0, err 1086 } 1087 balance := state.GetBalance(*args.From) // from can't be nil 1088 available := new(big.Int).Set(balance) 1089 1090 // account for tx value 1091 if args.Value != nil { 1092 if args.Value.ToInt().Cmp(available) >= 0 { 1093 return 0, errors.New("insufficient funds for transfer") 1094 } 1095 available.Sub(available, args.Value.ToInt()) 1096 } 1097 1098 // account for l1 fee 1099 l1DataFee, err := EstimateL1MsgFee(ctx, b, args, blockNrOrHash, nil, 0, gasCap, b.ChainConfig()) 1100 if err != nil { 1101 return 0, err 1102 } 1103 if l1DataFee.Cmp(available) >= 0 { 1104 return 0, errors.New("insufficient funds for l1 fee") 1105 } 1106 available.Sub(available, l1DataFee) 1107 1108 allowance := new(big.Int).Div(available, feeCap) 1109 1110 // If the allowance is larger than maximum uint64, skip checking 1111 if allowance.IsUint64() && hi > allowance.Uint64() { 1112 transfer := args.Value 1113 if transfer == nil { 1114 transfer = new(hexutil.Big) 1115 } 1116 log.Warn("Gas estimation capped by limited funds", "original", hi, "balance", balance, 1117 "sent", transfer.ToInt(), "maxFeePerGas", feeCap, "fundable", allowance) 1118 hi = allowance.Uint64() 1119 } 1120 } 1121 // Recap the highest gas allowance with specified gascap. 1122 if gasCap != 0 && hi > gasCap { 1123 log.Warn("Caller gas above allowance, capping", "requested", hi, "cap", gasCap) 1124 hi = gasCap 1125 } 1126 cap = hi 1127 1128 // Create a helper to check if a gas allowance results in an executable transaction 1129 executable := func(gas uint64) (bool, *core.ExecutionResult, error) { 1130 args.Gas = (*hexutil.Uint64)(&gas) 1131 1132 result, err := DoCall(ctx, b, args, blockNrOrHash, nil, 0, gasCap) 1133 if err != nil { 1134 if errors.Is(err, core.ErrIntrinsicGas) { 1135 return true, nil, nil // Special case, raise gas limit 1136 } 1137 return true, nil, err // Bail out 1138 } 1139 return result.Failed(), result, nil 1140 } 1141 // Execute the binary search and hone in on an executable gas limit 1142 for lo+1 < hi { 1143 mid := (hi + lo) / 2 1144 failed, _, err := executable(mid) 1145 1146 // If the error is not nil(consensus error), it means the provided message 1147 // call or transaction will never be accepted no matter how much gas it is 1148 // assigned. Return the error directly, don't struggle any more. 1149 if err != nil { 1150 return 0, err 1151 } 1152 if failed { 1153 lo = mid 1154 } else { 1155 hi = mid 1156 } 1157 } 1158 // Reject the transaction as invalid if it still fails at the highest allowance 1159 if hi == cap { 1160 failed, result, err := executable(hi) 1161 if err != nil { 1162 return 0, err 1163 } 1164 if failed { 1165 if result != nil && result.Err != vm.ErrOutOfGas { 1166 if len(result.Revert()) > 0 { 1167 return 0, newRevertError(result) 1168 } 1169 return 0, result.Err 1170 } 1171 // Otherwise, the specified gas cap is too low 1172 return 0, fmt.Errorf("gas required exceeds allowance (%d)", cap) 1173 } 1174 } 1175 return hexutil.Uint64(hi), nil 1176 } 1177 1178 // EstimateGas returns an estimate of the amount of gas needed to execute the 1179 // given transaction against the current pending block. 1180 func (s *PublicBlockChainAPI) EstimateGas(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (hexutil.Uint64, error) { 1181 bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) 1182 if blockNrOrHash != nil { 1183 bNrOrHash = *blockNrOrHash 1184 } 1185 return DoEstimateGas(ctx, s.b, args, bNrOrHash, s.b.RPCGasCap()) 1186 } 1187 1188 // RPCMarshalHeader converts the given header to the RPC output . 1189 func RPCMarshalHeader(head *types.Header, enableBaseFee bool) map[string]interface{} { 1190 result := map[string]interface{}{ 1191 "number": (*hexutil.Big)(head.Number), 1192 "hash": head.Hash(), 1193 "parentHash": head.ParentHash, 1194 "nonce": head.Nonce, 1195 "mixHash": head.MixDigest, 1196 "sha3Uncles": head.UncleHash, 1197 "logsBloom": head.Bloom, 1198 "stateRoot": head.Root, 1199 "miner": head.Coinbase, 1200 "difficulty": (*hexutil.Big)(head.Difficulty), 1201 "extraData": hexutil.Bytes(head.Extra), 1202 "size": hexutil.Uint64(head.Size()), 1203 "gasLimit": hexutil.Uint64(head.GasLimit), 1204 "gasUsed": hexutil.Uint64(head.GasUsed), 1205 "timestamp": hexutil.Uint64(head.Time), 1206 "transactionsRoot": head.TxHash, 1207 "receiptsRoot": head.ReceiptHash, 1208 } 1209 1210 if enableBaseFee && head.BaseFee != nil { 1211 result["baseFeePerGas"] = (*hexutil.Big)(head.BaseFee) 1212 } 1213 1214 return result 1215 } 1216 1217 // RPCMarshalBlock converts the given block to the RPC output which depends on fullTx. If inclTx is true transactions are 1218 // returned. When fullTx is true the returned block contains full transaction details, otherwise it will only contain 1219 // transaction hashes. 1220 func RPCMarshalBlock(block *types.Block, inclTx bool, fullTx bool, config *params.ChainConfig) (map[string]interface{}, error) { 1221 fields := RPCMarshalHeader(block.Header(), config.Scroll.BaseFeeEnabled()) 1222 fields["size"] = hexutil.Uint64(block.Size()) 1223 1224 if inclTx { 1225 formatTx := func(tx *types.Transaction) (interface{}, error) { 1226 return tx.Hash(), nil 1227 } 1228 if fullTx { 1229 formatTx = func(tx *types.Transaction) (interface{}, error) { 1230 return newRPCTransactionFromBlockHash(block, tx.Hash(), config), nil 1231 } 1232 } 1233 txs := block.Transactions() 1234 transactions := make([]interface{}, len(txs)) 1235 var err error 1236 for i, tx := range txs { 1237 if transactions[i], err = formatTx(tx); err != nil { 1238 return nil, err 1239 } 1240 } 1241 fields["transactions"] = transactions 1242 } 1243 uncles := block.Uncles() 1244 uncleHashes := make([]common.Hash, len(uncles)) 1245 for i, uncle := range uncles { 1246 uncleHashes[i] = uncle.Hash() 1247 } 1248 fields["uncles"] = uncleHashes 1249 1250 return fields, nil 1251 } 1252 1253 // rpcMarshalHeader uses the generalized output filler, then adds the total difficulty field, which requires 1254 // a `PublicBlockchainAPI`. 1255 func (s *PublicBlockChainAPI) rpcMarshalHeader(ctx context.Context, header *types.Header) map[string]interface{} { 1256 fields := RPCMarshalHeader(header, s.b.ChainConfig().Scroll.BaseFeeEnabled()) 1257 fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, header.Hash())) 1258 return fields 1259 } 1260 1261 // rpcMarshalBlock uses the generalized output filler, then adds the total difficulty field, which requires 1262 // a `PublicBlockchainAPI`. 1263 func (s *PublicBlockChainAPI) rpcMarshalBlock(ctx context.Context, b *types.Block, inclTx bool, fullTx bool) (map[string]interface{}, error) { 1264 fields, err := RPCMarshalBlock(b, inclTx, fullTx, s.b.ChainConfig()) 1265 if err != nil { 1266 return nil, err 1267 } 1268 if inclTx { 1269 fields["totalDifficulty"] = (*hexutil.Big)(s.b.GetTd(ctx, b.Hash())) 1270 } 1271 return fields, err 1272 } 1273 1274 // RPCTransaction represents a transaction that will serialize to the RPC representation of a transaction 1275 type RPCTransaction struct { 1276 BlockHash *common.Hash `json:"blockHash"` 1277 BlockNumber *hexutil.Big `json:"blockNumber"` 1278 From common.Address `json:"from"` 1279 Gas hexutil.Uint64 `json:"gas"` 1280 GasPrice *hexutil.Big `json:"gasPrice"` 1281 GasFeeCap *hexutil.Big `json:"maxFeePerGas,omitempty"` 1282 GasTipCap *hexutil.Big `json:"maxPriorityFeePerGas,omitempty"` 1283 Hash common.Hash `json:"hash"` 1284 Input hexutil.Bytes `json:"input"` 1285 Nonce hexutil.Uint64 `json:"nonce"` 1286 To *common.Address `json:"to"` 1287 TransactionIndex *hexutil.Uint64 `json:"transactionIndex"` 1288 Value *hexutil.Big `json:"value"` 1289 Type hexutil.Uint64 `json:"type"` 1290 Accesses *types.AccessList `json:"accessList,omitempty"` 1291 ChainID *hexutil.Big `json:"chainId,omitempty"` 1292 V *hexutil.Big `json:"v"` 1293 R *hexutil.Big `json:"r"` 1294 S *hexutil.Big `json:"s"` 1295 1296 // L1 message transaction fields: 1297 Sender common.Address `json:"sender,omitempty"` 1298 QueueIndex *hexutil.Uint64 `json:"queueIndex,omitempty"` 1299 } 1300 1301 // NewRPCTransaction returns a transaction that will serialize to the RPC 1302 // representation, with the given location metadata set (if available). 1303 func NewRPCTransaction(tx *types.Transaction, blockHash common.Hash, blockNumber uint64, index uint64, baseFee *big.Int, config *params.ChainConfig) *RPCTransaction { 1304 signer := types.MakeSigner(config, big.NewInt(0).SetUint64(blockNumber)) 1305 from, _ := types.Sender(signer, tx) 1306 v, r, s := tx.RawSignatureValues() 1307 result := &RPCTransaction{ 1308 Type: hexutil.Uint64(tx.Type()), 1309 From: from, 1310 Gas: hexutil.Uint64(tx.Gas()), 1311 GasPrice: (*hexutil.Big)(tx.GasPrice()), 1312 Hash: tx.Hash(), 1313 Input: hexutil.Bytes(tx.Data()), 1314 Nonce: hexutil.Uint64(tx.Nonce()), 1315 To: tx.To(), 1316 Value: (*hexutil.Big)(tx.Value()), 1317 V: (*hexutil.Big)(v), 1318 R: (*hexutil.Big)(r), 1319 S: (*hexutil.Big)(s), 1320 } 1321 if blockHash != (common.Hash{}) { 1322 result.BlockHash = &blockHash 1323 result.BlockNumber = (*hexutil.Big)(new(big.Int).SetUint64(blockNumber)) 1324 result.TransactionIndex = (*hexutil.Uint64)(&index) 1325 } 1326 switch tx.Type() { 1327 case types.AccessListTxType: 1328 al := tx.AccessList() 1329 result.Accesses = &al 1330 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1331 case types.DynamicFeeTxType: 1332 al := tx.AccessList() 1333 result.Accesses = &al 1334 result.ChainID = (*hexutil.Big)(tx.ChainId()) 1335 result.GasFeeCap = (*hexutil.Big)(tx.GasFeeCap()) 1336 result.GasTipCap = (*hexutil.Big)(tx.GasTipCap()) 1337 // if the transaction has been mined, compute the effective gas price 1338 if baseFee != nil && blockHash != (common.Hash{}) { 1339 // price = min(tip, gasFeeCap - baseFee) + baseFee 1340 price := math.BigMin(new(big.Int).Add(tx.GasTipCap(), baseFee), tx.GasFeeCap()) 1341 result.GasPrice = (*hexutil.Big)(price) 1342 } else { 1343 result.GasPrice = (*hexutil.Big)(tx.GasFeeCap()) 1344 } 1345 case types.L1MessageTxType: 1346 msg := tx.AsL1MessageTx() 1347 result.Sender = msg.Sender 1348 result.QueueIndex = (*hexutil.Uint64)(&msg.QueueIndex) 1349 } 1350 return result 1351 } 1352 1353 // newRPCPendingTransaction returns a pending transaction that will serialize to the RPC representation 1354 func newRPCPendingTransaction(tx *types.Transaction, current *types.Header, config *params.ChainConfig) *RPCTransaction { 1355 var baseFee *big.Int 1356 blockNumber := uint64(0) 1357 if current != nil { 1358 baseFee = misc.CalcBaseFee(config, current) 1359 blockNumber = current.Number.Uint64() 1360 } 1361 return NewRPCTransaction(tx, common.Hash{}, blockNumber, 0, baseFee, config) 1362 } 1363 1364 // newRPCTransactionFromBlockIndex returns a transaction that will serialize to the RPC representation. 1365 func newRPCTransactionFromBlockIndex(b *types.Block, index uint64, config *params.ChainConfig) *RPCTransaction { 1366 txs := b.Transactions() 1367 if index >= uint64(len(txs)) { 1368 return nil 1369 } 1370 return NewRPCTransaction(txs[index], b.Hash(), b.NumberU64(), index, b.BaseFee(), config) 1371 } 1372 1373 // newRPCRawTransactionFromBlockIndex returns the bytes of a transaction given a block and a transaction index. 1374 func newRPCRawTransactionFromBlockIndex(b *types.Block, index uint64) hexutil.Bytes { 1375 txs := b.Transactions() 1376 if index >= uint64(len(txs)) { 1377 return nil 1378 } 1379 blob, _ := txs[index].MarshalBinary() 1380 return blob 1381 } 1382 1383 // newRPCTransactionFromBlockHash returns a transaction that will serialize to the RPC representation. 1384 func newRPCTransactionFromBlockHash(b *types.Block, hash common.Hash, config *params.ChainConfig) *RPCTransaction { 1385 for idx, tx := range b.Transactions() { 1386 if tx.Hash() == hash { 1387 return newRPCTransactionFromBlockIndex(b, uint64(idx), config) 1388 } 1389 } 1390 return nil 1391 } 1392 1393 // accessListResult returns an optional accesslist 1394 // Its the result of the `debug_createAccessList` RPC call. 1395 // It contains an error if the transaction itself failed. 1396 type accessListResult struct { 1397 Accesslist *types.AccessList `json:"accessList"` 1398 Error string `json:"error,omitempty"` 1399 GasUsed hexutil.Uint64 `json:"gasUsed"` 1400 } 1401 1402 // CreateAccessList creates a EIP-2930 type AccessList for the given transaction. 1403 // Reexec and BlockNrOrHash can be specified to create the accessList on top of a certain state. 1404 func (s *PublicBlockChainAPI) CreateAccessList(ctx context.Context, args TransactionArgs, blockNrOrHash *rpc.BlockNumberOrHash) (*accessListResult, error) { 1405 bNrOrHash := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber) 1406 if blockNrOrHash != nil { 1407 bNrOrHash = *blockNrOrHash 1408 } 1409 acl, gasUsed, vmerr, err := AccessList(ctx, s.b, bNrOrHash, args) 1410 if err != nil { 1411 return nil, err 1412 } 1413 result := &accessListResult{Accesslist: &acl, GasUsed: hexutil.Uint64(gasUsed)} 1414 if vmerr != nil { 1415 result.Error = vmerr.Error() 1416 } 1417 return result, nil 1418 } 1419 1420 // AccessList creates an access list for the given transaction. 1421 // If the accesslist creation fails an error is returned. 1422 // If the transaction itself fails, an vmErr is returned. 1423 func AccessList(ctx context.Context, b Backend, blockNrOrHash rpc.BlockNumberOrHash, args TransactionArgs) (acl types.AccessList, gasUsed uint64, vmErr error, err error) { 1424 // Retrieve the execution context 1425 db, header, err := b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 1426 if db == nil || err != nil { 1427 return nil, 0, nil, err 1428 } 1429 // If the gas amount is not set, extract this as it will depend on access 1430 // lists and we'll need to reestimate every time 1431 nogas := args.Gas == nil 1432 1433 // Ensure any missing fields are filled, extract the recipient and input data 1434 if err := args.setDefaults(ctx, b); err != nil { 1435 return nil, 0, nil, err 1436 } 1437 var to common.Address 1438 if args.To != nil { 1439 to = *args.To 1440 } else { 1441 to = crypto.CreateAddress(args.from(), uint64(*args.Nonce)) 1442 } 1443 // Retrieve the precompiles since they don't need to be added to the access list 1444 precompiles := vm.ActivePrecompiles(b.ChainConfig().Rules(header.Number)) 1445 1446 // Create an initial tracer 1447 prevTracer := vm.NewAccessListTracer(nil, args.from(), to, precompiles) 1448 if args.AccessList != nil { 1449 prevTracer = vm.NewAccessListTracer(*args.AccessList, args.from(), to, precompiles) 1450 } 1451 for { 1452 // Retrieve the current access list to expand 1453 accessList := prevTracer.AccessList() 1454 log.Trace("Creating access list", "input", accessList) 1455 1456 // If no gas amount was specified, each unique access list needs it's own 1457 // gas calculation. This is quite expensive, but we need to be accurate 1458 // and it's convered by the sender only anyway. 1459 if nogas { 1460 args.Gas = nil 1461 if err := args.setDefaults(ctx, b); err != nil { 1462 return nil, 0, nil, err // shouldn't happen, just in case 1463 } 1464 } 1465 // Copy the original db so we don't modify it 1466 statedb := db.Copy() 1467 // Set the accesslist to the last al 1468 args.AccessList = &accessList 1469 msg, err := args.ToMessage(b.RPCGasCap(), header.BaseFee) 1470 if err != nil { 1471 return nil, 0, nil, err 1472 } 1473 1474 // Apply the transaction with the access list tracer 1475 tracer := vm.NewAccessListTracer(accessList, args.from(), to, precompiles) 1476 config := vm.Config{Tracer: tracer, Debug: true, NoBaseFee: true} 1477 vmenv, _, err := b.GetEVM(ctx, msg, statedb, header, &config) 1478 if err != nil { 1479 return nil, 0, nil, err 1480 } 1481 signer := types.MakeSigner(b.ChainConfig(), header.Number) 1482 l1DataFee, err := fees.EstimateL1DataFeeForMessage(msg, header.BaseFee, b.ChainConfig().ChainID, signer, statedb) 1483 if err != nil { 1484 return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err) 1485 } 1486 res, err := core.ApplyMessage(vmenv, msg, new(core.GasPool).AddGas(msg.Gas()), l1DataFee) 1487 if err != nil { 1488 return nil, 0, nil, fmt.Errorf("failed to apply transaction: %v err: %v", args.toTransaction().Hash(), err) 1489 } 1490 if tracer.Equal(prevTracer) { 1491 return accessList, res.UsedGas, res.Err, nil 1492 } 1493 prevTracer = tracer 1494 } 1495 } 1496 1497 // PublicTransactionPoolAPI exposes methods for the RPC interface 1498 type PublicTransactionPoolAPI struct { 1499 b Backend 1500 nonceLock *AddrLocker 1501 signer types.Signer 1502 } 1503 1504 // NewPublicTransactionPoolAPI creates a new RPC service with methods specific for the transaction pool. 1505 func NewPublicTransactionPoolAPI(b Backend, nonceLock *AddrLocker) *PublicTransactionPoolAPI { 1506 // The signer used by the API should always be the 'latest' known one because we expect 1507 // signers to be backwards-compatible with old transactions. 1508 signer := types.LatestSigner(b.ChainConfig()) 1509 return &PublicTransactionPoolAPI{b, nonceLock, signer} 1510 } 1511 1512 // GetBlockTransactionCountByNumber returns the number of transactions in the block with the given block number. 1513 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByNumber(ctx context.Context, blockNr rpc.BlockNumber) *hexutil.Uint { 1514 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1515 n := hexutil.Uint(len(block.Transactions())) 1516 return &n 1517 } 1518 return nil 1519 } 1520 1521 // GetBlockTransactionCountByHash returns the number of transactions in the block with the given hash. 1522 func (s *PublicTransactionPoolAPI) GetBlockTransactionCountByHash(ctx context.Context, blockHash common.Hash) *hexutil.Uint { 1523 if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil { 1524 n := hexutil.Uint(len(block.Transactions())) 1525 return &n 1526 } 1527 return nil 1528 } 1529 1530 // GetTransactionByBlockNumberAndIndex returns the transaction for the given block number and index. 1531 func (s *PublicTransactionPoolAPI) GetTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) *RPCTransaction { 1532 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1533 return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig()) 1534 } 1535 return nil 1536 } 1537 1538 // GetTransactionByBlockHashAndIndex returns the transaction for the given block hash and index. 1539 func (s *PublicTransactionPoolAPI) GetTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) *RPCTransaction { 1540 if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil { 1541 return newRPCTransactionFromBlockIndex(block, uint64(index), s.b.ChainConfig()) 1542 } 1543 return nil 1544 } 1545 1546 // GetRawTransactionByBlockNumberAndIndex returns the bytes of the transaction for the given block number and index. 1547 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockNumberAndIndex(ctx context.Context, blockNr rpc.BlockNumber, index hexutil.Uint) hexutil.Bytes { 1548 if block, _ := s.b.BlockByNumber(ctx, blockNr); block != nil { 1549 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1550 } 1551 return nil 1552 } 1553 1554 // GetRawTransactionByBlockHashAndIndex returns the bytes of the transaction for the given block hash and index. 1555 func (s *PublicTransactionPoolAPI) GetRawTransactionByBlockHashAndIndex(ctx context.Context, blockHash common.Hash, index hexutil.Uint) hexutil.Bytes { 1556 if block, _ := s.b.BlockByHash(ctx, blockHash); block != nil { 1557 return newRPCRawTransactionFromBlockIndex(block, uint64(index)) 1558 } 1559 return nil 1560 } 1561 1562 // GetTransactionCount returns the number of transactions the given address has sent for the given block number 1563 func (s *PublicTransactionPoolAPI) GetTransactionCount(ctx context.Context, address common.Address, blockNrOrHash rpc.BlockNumberOrHash) (*hexutil.Uint64, error) { 1564 // Ask transaction pool for the nonce which includes pending transactions 1565 if blockNr, ok := blockNrOrHash.Number(); ok && blockNr == rpc.PendingBlockNumber { 1566 nonce, err := s.b.GetPoolNonce(ctx, address) 1567 if err != nil { 1568 return nil, err 1569 } 1570 return (*hexutil.Uint64)(&nonce), nil 1571 } 1572 // Resolve block number and use its state to ask for the nonce 1573 state, _, err := s.b.StateAndHeaderByNumberOrHash(ctx, blockNrOrHash) 1574 if state == nil || err != nil { 1575 return nil, err 1576 } 1577 nonce := state.GetNonce(address) 1578 return (*hexutil.Uint64)(&nonce), state.Error() 1579 } 1580 1581 // GetTransactionByHash returns the transaction for the given hash 1582 func (s *PublicTransactionPoolAPI) GetTransactionByHash(ctx context.Context, hash common.Hash) (*RPCTransaction, error) { 1583 // Try to return an already finalized transaction 1584 tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash) 1585 if err != nil { 1586 return nil, err 1587 } 1588 if tx != nil { 1589 header, err := s.b.HeaderByHash(ctx, blockHash) 1590 if err != nil { 1591 return nil, err 1592 } 1593 return NewRPCTransaction(tx, blockHash, blockNumber, index, header.BaseFee, s.b.ChainConfig()), nil 1594 } 1595 // No finalized transaction, try to retrieve it from the pool 1596 if tx := s.b.GetPoolTransaction(hash); tx != nil { 1597 return newRPCPendingTransaction(tx, s.b.CurrentHeader(), s.b.ChainConfig()), nil 1598 } 1599 1600 // Transaction unknown, return as such 1601 return nil, nil 1602 } 1603 1604 // GetRawTransactionByHash returns the bytes of the transaction for the given hash. 1605 func (s *PublicTransactionPoolAPI) GetRawTransactionByHash(ctx context.Context, hash common.Hash) (hexutil.Bytes, error) { 1606 // Retrieve a finalized transaction, or a pooled otherwise 1607 tx, _, _, _, err := s.b.GetTransaction(ctx, hash) 1608 if err != nil { 1609 return nil, err 1610 } 1611 if tx == nil { 1612 if tx = s.b.GetPoolTransaction(hash); tx == nil { 1613 // Transaction not found anywhere, abort 1614 return nil, nil 1615 } 1616 } 1617 // Serialize to RLP and return 1618 return tx.MarshalBinary() 1619 } 1620 1621 // GetTransactionReceipt returns the transaction receipt for the given transaction hash. 1622 func (s *PublicTransactionPoolAPI) GetTransactionReceipt(ctx context.Context, hash common.Hash) (map[string]interface{}, error) { 1623 tx, blockHash, blockNumber, index, err := s.b.GetTransaction(ctx, hash) 1624 if err != nil { 1625 return nil, nil 1626 } 1627 receipts, err := s.b.GetReceipts(ctx, blockHash) 1628 if err != nil { 1629 return nil, err 1630 } 1631 if len(receipts) <= int(index) { 1632 return nil, nil 1633 } 1634 receipt := receipts[index] 1635 1636 // Derive the sender. 1637 bigblock := new(big.Int).SetUint64(blockNumber) 1638 signer := types.MakeSigner(s.b.ChainConfig(), bigblock) 1639 from, _ := types.Sender(signer, tx) 1640 1641 fields := map[string]interface{}{ 1642 "blockHash": blockHash, 1643 "blockNumber": hexutil.Uint64(blockNumber), 1644 "transactionHash": hash, 1645 "transactionIndex": hexutil.Uint64(index), 1646 "from": from, 1647 "to": tx.To(), 1648 "gasUsed": hexutil.Uint64(receipt.GasUsed), 1649 "cumulativeGasUsed": hexutil.Uint64(receipt.CumulativeGasUsed), 1650 "contractAddress": nil, 1651 "logs": receipt.Logs, 1652 "logsBloom": receipt.Bloom, 1653 "type": hexutil.Uint(tx.Type()), 1654 "l1Fee": (*hexutil.Big)(receipt.L1Fee), 1655 } 1656 // Assign the effective gas price paid 1657 if !s.b.ChainConfig().IsLondon(bigblock) { 1658 fields["effectiveGasPrice"] = hexutil.Uint64(tx.GasPrice().Uint64()) 1659 } else { 1660 header, err := s.b.HeaderByHash(ctx, blockHash) 1661 if err != nil { 1662 return nil, err 1663 } 1664 1665 baseFee := header.BaseFee 1666 if baseFee == nil { 1667 baseFee = big.NewInt(0) 1668 } 1669 1670 gasPrice := new(big.Int).Add(baseFee, tx.EffectiveGasTipValue(header.BaseFee)) 1671 fields["effectiveGasPrice"] = hexutil.Uint64(gasPrice.Uint64()) 1672 } 1673 // Assign receipt status or post state. 1674 if len(receipt.PostState) > 0 { 1675 fields["root"] = hexutil.Bytes(receipt.PostState) 1676 } else { 1677 fields["status"] = hexutil.Uint(receipt.Status) 1678 } 1679 if receipt.Logs == nil { 1680 fields["logs"] = [][]*types.Log{} 1681 } 1682 // If the ContractAddress is 20 0x0 bytes, assume it is not a contract creation 1683 if receipt.ContractAddress != (common.Address{}) { 1684 fields["contractAddress"] = receipt.ContractAddress 1685 } 1686 return fields, nil 1687 } 1688 1689 // sign is a helper function that signs a transaction with the private key of the given address. 1690 func (s *PublicTransactionPoolAPI) sign(addr common.Address, tx *types.Transaction) (*types.Transaction, error) { 1691 // Look up the wallet containing the requested signer 1692 account := accounts.Account{Address: addr} 1693 1694 wallet, err := s.b.AccountManager().Find(account) 1695 if err != nil { 1696 return nil, err 1697 } 1698 // Request the wallet to sign the transaction 1699 return wallet.SignTx(account, tx, s.b.ChainConfig().ChainID) 1700 } 1701 1702 // SubmitTransaction is a helper function that submits tx to txPool and logs a message. 1703 func SubmitTransaction(ctx context.Context, b Backend, tx *types.Transaction) (common.Hash, error) { 1704 // If the transaction fee cap is already specified, ensure the 1705 // fee of the given transaction is _reasonable_. 1706 if err := checkTxFee(tx.GasPrice(), tx.Gas(), b.RPCTxFeeCap()); err != nil { 1707 return common.Hash{}, err 1708 } 1709 if !b.UnprotectedAllowed() && !tx.Protected() { 1710 // Ensure only eip155 signed transactions are submitted if EIP155Required is set. 1711 return common.Hash{}, errors.New("only replay-protected (EIP-155) transactions allowed over RPC") 1712 } 1713 if err := b.SendTx(ctx, tx); err != nil { 1714 return common.Hash{}, err 1715 } 1716 // Print a log with full tx details for manual investigations and interventions 1717 signer := types.MakeSigner(b.ChainConfig(), b.CurrentBlock().Number()) 1718 from, err := types.Sender(signer, tx) 1719 if err != nil { 1720 return common.Hash{}, err 1721 } 1722 1723 if tx.To() == nil { 1724 addr := crypto.CreateAddress(from, tx.Nonce()) 1725 log.Info("Submitted contract creation", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "contract", addr.Hex(), "value", tx.Value()) 1726 } else { 1727 log.Info("Submitted transaction", "hash", tx.Hash().Hex(), "from", from, "nonce", tx.Nonce(), "recipient", tx.To(), "value", tx.Value()) 1728 } 1729 return tx.Hash(), nil 1730 } 1731 1732 // SendTransaction creates a transaction for the given argument, sign it and submit it to the 1733 // transaction pool. 1734 func (s *PublicTransactionPoolAPI) SendTransaction(ctx context.Context, args TransactionArgs) (common.Hash, error) { 1735 // Look up the wallet containing the requested signer 1736 account := accounts.Account{Address: args.from()} 1737 1738 wallet, err := s.b.AccountManager().Find(account) 1739 if err != nil { 1740 return common.Hash{}, err 1741 } 1742 1743 if args.Nonce == nil { 1744 // Hold the addresse's mutex around signing to prevent concurrent assignment of 1745 // the same nonce to multiple accounts. 1746 s.nonceLock.LockAddr(args.from()) 1747 defer s.nonceLock.UnlockAddr(args.from()) 1748 } 1749 1750 // Set some sanity defaults and terminate on failure 1751 if err := args.setDefaults(ctx, s.b); err != nil { 1752 return common.Hash{}, err 1753 } 1754 // Assemble the transaction and sign with the wallet 1755 tx := args.toTransaction() 1756 1757 signed, err := wallet.SignTx(account, tx, s.b.ChainConfig().ChainID) 1758 if err != nil { 1759 return common.Hash{}, err 1760 } 1761 return SubmitTransaction(ctx, s.b, signed) 1762 } 1763 1764 // FillTransaction fills the defaults (nonce, gas, gasPrice or 1559 fields) 1765 // on a given unsigned transaction, and returns it to the caller for further 1766 // processing (signing + broadcast). 1767 func (s *PublicTransactionPoolAPI) FillTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { 1768 // Set some sanity defaults and terminate on failure 1769 if err := args.setDefaults(ctx, s.b); err != nil { 1770 return nil, err 1771 } 1772 // Assemble the transaction and obtain rlp 1773 tx := args.toTransaction() 1774 data, err := tx.MarshalBinary() 1775 if err != nil { 1776 return nil, err 1777 } 1778 return &SignTransactionResult{data, tx}, nil 1779 } 1780 1781 // SendRawTransaction will add the signed transaction to the transaction pool. 1782 // The sender is responsible for signing the transaction and using the correct nonce. 1783 func (s *PublicTransactionPoolAPI) SendRawTransaction(ctx context.Context, input hexutil.Bytes) (common.Hash, error) { 1784 tx := new(types.Transaction) 1785 if err := tx.UnmarshalBinary(input); err != nil { 1786 return common.Hash{}, err 1787 } 1788 return SubmitTransaction(ctx, s.b, tx) 1789 } 1790 1791 // Sign calculates an ECDSA signature for: 1792 // keccack256("\x19Ethereum Signed Message:\n" + len(message) + message). 1793 // 1794 // Note, the produced signature conforms to the secp256k1 curve R, S and V values, 1795 // where the V value will be 27 or 28 for legacy reasons. 1796 // 1797 // The account associated with addr must be unlocked. 1798 // 1799 // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign 1800 func (s *PublicTransactionPoolAPI) Sign(addr common.Address, data hexutil.Bytes) (hexutil.Bytes, error) { 1801 // Look up the wallet containing the requested signer 1802 account := accounts.Account{Address: addr} 1803 1804 wallet, err := s.b.AccountManager().Find(account) 1805 if err != nil { 1806 return nil, err 1807 } 1808 // Sign the requested hash with the wallet 1809 signature, err := wallet.SignText(account, data) 1810 if err == nil { 1811 signature[64] += 27 // Transform V from 0/1 to 27/28 according to the yellow paper 1812 } 1813 return signature, err 1814 } 1815 1816 // SignTransactionResult represents a RLP encoded signed transaction. 1817 type SignTransactionResult struct { 1818 Raw hexutil.Bytes `json:"raw"` 1819 Tx *types.Transaction `json:"tx"` 1820 } 1821 1822 // SignTransaction will sign the given transaction with the from account. 1823 // The node needs to have the private key of the account corresponding with 1824 // the given from address and it needs to be unlocked. 1825 func (s *PublicTransactionPoolAPI) SignTransaction(ctx context.Context, args TransactionArgs) (*SignTransactionResult, error) { 1826 if args.Gas == nil { 1827 return nil, fmt.Errorf("gas not specified") 1828 } 1829 if args.GasPrice == nil && (args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil) { 1830 return nil, fmt.Errorf("missing gasPrice or maxFeePerGas/maxPriorityFeePerGas") 1831 } 1832 if args.Nonce == nil { 1833 return nil, fmt.Errorf("nonce not specified") 1834 } 1835 if err := args.setDefaults(ctx, s.b); err != nil { 1836 return nil, err 1837 } 1838 // Before actually sign the transaction, ensure the transaction fee is reasonable. 1839 tx := args.toTransaction() 1840 if err := checkTxFee(tx.GasPrice(), tx.Gas(), s.b.RPCTxFeeCap()); err != nil { 1841 return nil, err 1842 } 1843 signed, err := s.sign(args.from(), tx) 1844 if err != nil { 1845 return nil, err 1846 } 1847 data, err := signed.MarshalBinary() 1848 if err != nil { 1849 return nil, err 1850 } 1851 return &SignTransactionResult{data, signed}, nil 1852 } 1853 1854 // PendingTransactions returns the transactions that are in the transaction pool 1855 // and have a from address that is one of the accounts this node manages. 1856 func (s *PublicTransactionPoolAPI) PendingTransactions() ([]*RPCTransaction, error) { 1857 pending, err := s.b.GetPoolTransactions() 1858 if err != nil { 1859 return nil, err 1860 } 1861 accounts := make(map[common.Address]struct{}) 1862 for _, wallet := range s.b.AccountManager().Wallets() { 1863 for _, account := range wallet.Accounts() { 1864 accounts[account.Address] = struct{}{} 1865 } 1866 } 1867 curHeader := s.b.CurrentHeader() 1868 transactions := make([]*RPCTransaction, 0, len(pending)) 1869 for _, tx := range pending { 1870 from, _ := types.Sender(s.signer, tx) 1871 if _, exists := accounts[from]; exists { 1872 transactions = append(transactions, newRPCPendingTransaction(tx, curHeader, s.b.ChainConfig())) 1873 } 1874 } 1875 return transactions, nil 1876 } 1877 1878 // Resend accepts an existing transaction and a new gas price and limit. It will remove 1879 // the given transaction from the pool and reinsert it with the new gas price and limit. 1880 func (s *PublicTransactionPoolAPI) Resend(ctx context.Context, sendArgs TransactionArgs, gasPrice *hexutil.Big, gasLimit *hexutil.Uint64) (common.Hash, error) { 1881 if sendArgs.Nonce == nil { 1882 return common.Hash{}, fmt.Errorf("missing transaction nonce in transaction spec") 1883 } 1884 if err := sendArgs.setDefaults(ctx, s.b); err != nil { 1885 return common.Hash{}, err 1886 } 1887 matchTx := sendArgs.toTransaction() 1888 1889 // Before replacing the old transaction, ensure the _new_ transaction fee is reasonable. 1890 var price = matchTx.GasPrice() 1891 if gasPrice != nil { 1892 price = gasPrice.ToInt() 1893 } 1894 var gas = matchTx.Gas() 1895 if gasLimit != nil { 1896 gas = uint64(*gasLimit) 1897 } 1898 if err := checkTxFee(price, gas, s.b.RPCTxFeeCap()); err != nil { 1899 return common.Hash{}, err 1900 } 1901 // Iterate the pending list for replacement 1902 pending, err := s.b.GetPoolTransactions() 1903 if err != nil { 1904 return common.Hash{}, err 1905 } 1906 for _, p := range pending { 1907 wantSigHash := s.signer.Hash(matchTx) 1908 pFrom, err := types.Sender(s.signer, p) 1909 if err == nil && pFrom == sendArgs.from() && s.signer.Hash(p) == wantSigHash { 1910 // Match. Re-sign and send the transaction. 1911 if gasPrice != nil && (*big.Int)(gasPrice).Sign() != 0 { 1912 sendArgs.GasPrice = gasPrice 1913 } 1914 if gasLimit != nil && *gasLimit != 0 { 1915 sendArgs.Gas = gasLimit 1916 } 1917 signedTx, err := s.sign(sendArgs.from(), sendArgs.toTransaction()) 1918 if err != nil { 1919 return common.Hash{}, err 1920 } 1921 if err = s.b.SendTx(ctx, signedTx); err != nil { 1922 return common.Hash{}, err 1923 } 1924 return signedTx.Hash(), nil 1925 } 1926 } 1927 return common.Hash{}, fmt.Errorf("transaction %#x not found", matchTx.Hash()) 1928 } 1929 1930 // PublicDebugAPI is the collection of Ethereum APIs exposed over the public 1931 // debugging endpoint. 1932 type PublicDebugAPI struct { 1933 b Backend 1934 } 1935 1936 // NewPublicDebugAPI creates a new API definition for the public debug methods 1937 // of the Ethereum service. 1938 func NewPublicDebugAPI(b Backend) *PublicDebugAPI { 1939 return &PublicDebugAPI{b: b} 1940 } 1941 1942 // GetHeaderRlp retrieves the RLP encoded for of a single header. 1943 func (api *PublicDebugAPI) GetHeaderRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) { 1944 header, _ := api.b.HeaderByNumber(ctx, rpc.BlockNumber(number)) 1945 if header == nil { 1946 return nil, fmt.Errorf("header #%d not found", number) 1947 } 1948 return rlp.EncodeToBytes(header) 1949 } 1950 1951 // GetBlockRlp retrieves the RLP encoded for of a single block. 1952 func (api *PublicDebugAPI) GetBlockRlp(ctx context.Context, number uint64) (hexutil.Bytes, error) { 1953 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1954 if block == nil { 1955 return nil, fmt.Errorf("block #%d not found", number) 1956 } 1957 return rlp.EncodeToBytes(block) 1958 } 1959 1960 // TestSignCliqueBlock fetches the given block number, and attempts to sign it as a clique header with the 1961 // given address, returning the address of the recovered signature 1962 // 1963 // This is a temporary method to debug the externalsigner integration, 1964 // TODO: Remove this method when the integration is mature 1965 func (api *PublicDebugAPI) TestSignCliqueBlock(ctx context.Context, address common.Address, number uint64) (common.Address, error) { 1966 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 1967 if block == nil { 1968 return common.Address{}, fmt.Errorf("block #%d not found", number) 1969 } 1970 header := block.Header() 1971 header.Extra = make([]byte, 32+65) 1972 encoded := clique.CliqueRLP(header) 1973 1974 // Look up the wallet containing the requested signer 1975 account := accounts.Account{Address: address} 1976 wallet, err := api.b.AccountManager().Find(account) 1977 if err != nil { 1978 return common.Address{}, err 1979 } 1980 1981 signature, err := wallet.SignData(account, accounts.MimetypeClique, encoded) 1982 if err != nil { 1983 return common.Address{}, err 1984 } 1985 sealHash := clique.SealHash(header).Bytes() 1986 log.Info("test signing of clique block", 1987 "Sealhash", fmt.Sprintf("%x", sealHash), 1988 "signature", fmt.Sprintf("%x", signature)) 1989 pubkey, err := crypto.Ecrecover(sealHash, signature) 1990 if err != nil { 1991 return common.Address{}, err 1992 } 1993 var signer common.Address 1994 copy(signer[:], crypto.Keccak256(pubkey[1:])[12:]) 1995 1996 return signer, nil 1997 } 1998 1999 // PrintBlock retrieves a block and returns its pretty printed form. 2000 func (api *PublicDebugAPI) PrintBlock(ctx context.Context, number uint64) (string, error) { 2001 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 2002 if block == nil { 2003 return "", fmt.Errorf("block #%d not found", number) 2004 } 2005 return spew.Sdump(block), nil 2006 } 2007 2008 // SeedHash retrieves the seed hash of a block. 2009 func (api *PublicDebugAPI) SeedHash(ctx context.Context, number uint64) (string, error) { 2010 block, _ := api.b.BlockByNumber(ctx, rpc.BlockNumber(number)) 2011 if block == nil { 2012 return "", fmt.Errorf("block #%d not found", number) 2013 } 2014 return fmt.Sprintf("0x%x", ethash.SeedHash(number)), nil 2015 } 2016 2017 // PrivateDebugAPI is the collection of Ethereum APIs exposed over the private 2018 // debugging endpoint. 2019 type PrivateDebugAPI struct { 2020 b Backend 2021 } 2022 2023 // NewPrivateDebugAPI creates a new API definition for the private debug methods 2024 // of the Ethereum service. 2025 func NewPrivateDebugAPI(b Backend) *PrivateDebugAPI { 2026 return &PrivateDebugAPI{b: b} 2027 } 2028 2029 // ChaindbProperty returns leveldb properties of the key-value database. 2030 func (api *PrivateDebugAPI) ChaindbProperty(property string) (string, error) { 2031 if property == "" { 2032 property = "leveldb.stats" 2033 } else if !strings.HasPrefix(property, "leveldb.") { 2034 property = "leveldb." + property 2035 } 2036 return api.b.ChainDb().Stat(property) 2037 } 2038 2039 // ChaindbCompact flattens the entire key-value database into a single level, 2040 // removing all unused slots and merging all keys. 2041 func (api *PrivateDebugAPI) ChaindbCompact() error { 2042 for b := byte(0); b < 255; b++ { 2043 log.Info("Compacting chain database", "range", fmt.Sprintf("0x%0.2X-0x%0.2X", b, b+1)) 2044 if err := api.b.ChainDb().Compact([]byte{b}, []byte{b + 1}); err != nil { 2045 log.Error("Database compaction failed", "err", err) 2046 return err 2047 } 2048 } 2049 return nil 2050 } 2051 2052 // SetHead rewinds the head of the blockchain to a previous block. 2053 func (api *PrivateDebugAPI) SetHead(number hexutil.Uint64) { 2054 api.b.SetHead(uint64(number)) 2055 } 2056 2057 // PublicNetAPI offers network related RPC methods 2058 type PublicNetAPI struct { 2059 net *p2p.Server 2060 networkVersion uint64 2061 } 2062 2063 // NewPublicNetAPI creates a new net API instance. 2064 func NewPublicNetAPI(net *p2p.Server, networkVersion uint64) *PublicNetAPI { 2065 return &PublicNetAPI{net, networkVersion} 2066 } 2067 2068 // Listening returns an indication if the node is listening for network connections. 2069 func (s *PublicNetAPI) Listening() bool { 2070 return true // always listening 2071 } 2072 2073 // PeerCount returns the number of connected peers 2074 func (s *PublicNetAPI) PeerCount() hexutil.Uint { 2075 return hexutil.Uint(s.net.PeerCount()) 2076 } 2077 2078 // Version returns the current ethereum protocol version. 2079 func (s *PublicNetAPI) Version() string { 2080 return fmt.Sprintf("%d", s.networkVersion) 2081 } 2082 2083 // checkTxFee is an internal function used to check whether the fee of 2084 // the given transaction is _reasonable_(under the cap). 2085 func checkTxFee(gasPrice *big.Int, gas uint64, cap float64) error { 2086 // Short circuit if there is no cap for transaction fee at all. 2087 if cap == 0 { 2088 return nil 2089 } 2090 feeEth := new(big.Float).Quo(new(big.Float).SetInt(new(big.Int).Mul(gasPrice, new(big.Int).SetUint64(gas))), new(big.Float).SetInt(big.NewInt(params.Ether))) 2091 feeFloat, _ := feeEth.Float64() 2092 if feeFloat > cap { 2093 return fmt.Errorf("tx fee (%.2f ether) exceeds the configured cap (%.2f ether)", feeFloat, cap) 2094 } 2095 return nil 2096 } 2097 2098 // toHexSlice creates a slice of hex-strings based on []byte. 2099 func toHexSlice(b [][]byte) []string { 2100 r := make([]string, len(b)) 2101 for i := range b { 2102 r[i] = hexutil.Encode(b[i]) 2103 } 2104 return r 2105 }