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