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