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