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