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