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