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