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