github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/ethclient/ethclient.go (about) 1 // Copyright 2016 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 ethclient provides a client for the Ethereum RPC API. 18 package ethclient 19 20 import ( 21 "context" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 27 ethereum "github.com/ethereum-optimism/optimism/l2geth" 28 "github.com/ethereum-optimism/optimism/l2geth/common" 29 "github.com/ethereum-optimism/optimism/l2geth/common/hexutil" 30 "github.com/ethereum-optimism/optimism/l2geth/core/types" 31 "github.com/ethereum-optimism/optimism/l2geth/rlp" 32 "github.com/ethereum-optimism/optimism/l2geth/rpc" 33 ) 34 35 // Client defines typed wrappers for the Ethereum RPC API. 36 type Client struct { 37 c *rpc.Client 38 } 39 40 // Dial connects a client to the given URL. 41 func Dial(rawurl string) (*Client, error) { 42 return DialContext(context.Background(), rawurl) 43 } 44 45 func DialContext(ctx context.Context, rawurl string) (*Client, error) { 46 c, err := rpc.DialContext(ctx, rawurl) 47 if err != nil { 48 return nil, err 49 } 50 return NewClient(c), nil 51 } 52 53 // NewClient creates a client that uses the given RPC client. 54 func NewClient(c *rpc.Client) *Client { 55 return &Client{c} 56 } 57 58 func (ec *Client) Close() { 59 ec.c.Close() 60 } 61 62 // Blockchain Access 63 64 // ChainId retrieves the current chain ID for transaction replay protection. 65 func (ec *Client) ChainID(ctx context.Context) (*big.Int, error) { 66 var result hexutil.Big 67 err := ec.c.CallContext(ctx, &result, "eth_chainId") 68 if err != nil { 69 return nil, err 70 } 71 return (*big.Int)(&result), err 72 } 73 74 // BlockByHash returns the given full block. 75 // 76 // Note that loading full blocks requires two requests. Use HeaderByHash 77 // if you don't need all transactions or uncle headers. 78 func (ec *Client) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { 79 return ec.getBlock(ctx, "eth_getBlockByHash", hash, true) 80 } 81 82 // BlockByNumber returns a block from the current canonical chain. If number is nil, the 83 // latest known block is returned. 84 // 85 // Note that loading full blocks requires two requests. Use HeaderByNumber 86 // if you don't need all transactions or uncle headers. 87 func (ec *Client) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { 88 return ec.getBlock(ctx, "eth_getBlockByNumber", toBlockNumArg(number), true) 89 } 90 91 type rpcBlock struct { 92 Hash common.Hash `json:"hash"` 93 Transactions []rpcTransaction `json:"transactions"` 94 UncleHashes []common.Hash `json:"uncles"` 95 } 96 97 func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) { 98 var raw json.RawMessage 99 err := ec.c.CallContext(ctx, &raw, method, args...) 100 if err != nil { 101 return nil, err 102 } else if len(raw) == 0 { 103 return nil, ethereum.NotFound 104 } 105 // Decode header and transactions. 106 var head *types.Header 107 var body rpcBlock 108 if err := json.Unmarshal(raw, &head); err != nil { 109 return nil, err 110 } 111 if err := json.Unmarshal(raw, &body); err != nil { 112 return nil, err 113 } 114 // Quick-verify transaction and uncle lists. This mostly helps with debugging the server. 115 if head.UncleHash == types.EmptyUncleHash && len(body.UncleHashes) > 0 { 116 return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles") 117 } 118 if head.UncleHash != types.EmptyUncleHash && len(body.UncleHashes) == 0 { 119 return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles") 120 } 121 if head.TxHash == types.EmptyRootHash && len(body.Transactions) > 0 { 122 return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions") 123 } 124 if head.TxHash != types.EmptyRootHash && len(body.Transactions) == 0 { 125 return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions") 126 } 127 // Load uncles because they are not included in the block response. 128 var uncles []*types.Header 129 if len(body.UncleHashes) > 0 { 130 uncles = make([]*types.Header, len(body.UncleHashes)) 131 reqs := make([]rpc.BatchElem, len(body.UncleHashes)) 132 for i := range reqs { 133 reqs[i] = rpc.BatchElem{ 134 Method: "eth_getUncleByBlockHashAndIndex", 135 Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))}, 136 Result: &uncles[i], 137 } 138 } 139 if err := ec.c.BatchCallContext(ctx, reqs); err != nil { 140 return nil, err 141 } 142 for i := range reqs { 143 if reqs[i].Error != nil { 144 return nil, reqs[i].Error 145 } 146 if uncles[i] == nil { 147 return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:]) 148 } 149 } 150 } 151 // Fill the sender cache of transactions in the block. 152 txs := make([]*types.Transaction, len(body.Transactions)) 153 for i, tx := range body.Transactions { 154 if tx.From != nil { 155 setSenderFromServer(tx.tx, *tx.From, body.Hash) 156 } 157 meta := types.NewTransactionMeta( 158 tx.meta.L1BlockNumber, tx.meta.L1Timestamp, 159 tx.meta.L1MessageSender, tx.meta.QueueOrigin, 160 tx.meta.Index, tx.meta.QueueIndex, 161 tx.meta.RawTransaction, 162 ) 163 tx.tx.SetTransactionMeta(meta) 164 txs[i] = tx.tx 165 } 166 return types.NewBlockWithHeader(head).WithBody(txs, uncles), nil 167 } 168 169 // HeaderByHash returns the block header with the given hash. 170 func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 171 var head *types.Header 172 err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false) 173 if err == nil && head == nil { 174 err = ethereum.NotFound 175 } 176 return head, err 177 } 178 179 // HeaderByNumber returns a block header from the current canonical chain. If number is 180 // nil, the latest known header is returned. 181 func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { 182 var head *types.Header 183 err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false) 184 if err == nil && head == nil { 185 err = ethereum.NotFound 186 } 187 return head, err 188 } 189 190 type rpcTransaction struct { 191 tx *types.Transaction 192 meta *rpcTransactionMeta 193 txExtraInfo 194 } 195 196 //go:generate gencodec -type rpcTransactionMeta -field-override rpcTransactionMetaMarshaling -out gen_rpc_tx_meta_json.go 197 198 type rpcTransactionMeta struct { 199 L1BlockNumber *big.Int `json:"l1BlockNumber"` 200 L1Timestamp uint64 `json:"l1Timestamp"` 201 L1MessageSender *common.Address `json:"l1MessageSender"` 202 QueueOrigin types.QueueOrigin `json:"queueOrigin"` 203 Index *uint64 `json:"index"` 204 QueueIndex *uint64 `json:"queueIndex"` 205 RawTransaction []byte `json:"rawTransaction"` 206 } 207 208 type rpcTransactionMetaMarshaling struct { 209 L1BlockNumber *hexutil.Big 210 L1Timestamp hexutil.Uint64 211 Index *hexutil.Uint64 212 QueueIndex *hexutil.Uint64 213 RawTransaction hexutil.Bytes 214 } 215 216 type txExtraInfo struct { 217 BlockNumber *string `json:"blockNumber,omitempty"` 218 BlockHash *common.Hash `json:"blockHash,omitempty"` 219 From *common.Address `json:"from,omitempty"` 220 } 221 222 func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error { 223 if err := json.Unmarshal(msg, &tx.tx); err != nil { 224 return err 225 } 226 if err := json.Unmarshal(msg, &tx.meta); err != nil { 227 return err 228 } 229 return json.Unmarshal(msg, &tx.txExtraInfo) 230 } 231 232 // TransactionByHash returns the transaction with the given hash. 233 func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) { 234 var json *rpcTransaction 235 err = ec.c.CallContext(ctx, &json, "eth_getTransactionByHash", hash) 236 if err != nil { 237 return nil, false, err 238 } else if json == nil { 239 return nil, false, ethereum.NotFound 240 } else if _, r, _ := json.tx.RawSignatureValues(); r == nil { 241 return nil, false, fmt.Errorf("server returned transaction without signature") 242 } 243 if json.From != nil && json.BlockHash != nil { 244 setSenderFromServer(json.tx, *json.From, *json.BlockHash) 245 } 246 return json.tx, json.BlockNumber == nil, nil 247 } 248 249 // TransactionSender returns the sender address of the given transaction. The transaction 250 // must be known to the remote node and included in the blockchain at the given block and 251 // index. The sender is the one derived by the protocol at the time of inclusion. 252 // 253 // There is a fast-path for transactions retrieved by TransactionByHash and 254 // TransactionInBlock. Getting their sender address can be done without an RPC interaction. 255 func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) { 256 // Try to load the address from the cache. 257 sender, err := types.Sender(&senderFromServer{blockhash: block}, tx) 258 if err == nil { 259 return sender, nil 260 } 261 var meta struct { 262 Hash common.Hash 263 From common.Address 264 } 265 if err = ec.c.CallContext(ctx, &meta, "eth_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil { 266 return common.Address{}, err 267 } 268 if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() { 269 return common.Address{}, errors.New("wrong inclusion block/index") 270 } 271 return meta.From, nil 272 } 273 274 // TransactionCount returns the total number of transactions in the given block. 275 func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { 276 var num hexutil.Uint 277 err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByHash", blockHash) 278 return uint(num), err 279 } 280 281 // TransactionInBlock returns a single transaction at index in the given block. 282 func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { 283 var json *rpcTransaction 284 err := ec.c.CallContext(ctx, &json, "eth_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index)) 285 if err != nil { 286 return nil, err 287 } 288 if json == nil { 289 return nil, ethereum.NotFound 290 } else if _, r, _ := json.tx.RawSignatureValues(); r == nil { 291 return nil, fmt.Errorf("server returned transaction without signature") 292 } 293 if json.From != nil && json.BlockHash != nil { 294 setSenderFromServer(json.tx, *json.From, *json.BlockHash) 295 } 296 return json.tx, err 297 } 298 299 // TransactionReceipt returns the receipt of a transaction by transaction hash. 300 // Note that the receipt is not available for pending transactions. 301 func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 302 var r *types.Receipt 303 err := ec.c.CallContext(ctx, &r, "eth_getTransactionReceipt", txHash) 304 if err == nil { 305 if r == nil { 306 return nil, ethereum.NotFound 307 } 308 } 309 return r, err 310 } 311 312 func toBlockNumArg(number *big.Int) string { 313 if number == nil { 314 return "latest" 315 } 316 return hexutil.EncodeBig(number) 317 } 318 319 type rpcProgress struct { 320 StartingBlock hexutil.Uint64 321 CurrentBlock hexutil.Uint64 322 HighestBlock hexutil.Uint64 323 PulledStates hexutil.Uint64 324 KnownStates hexutil.Uint64 325 } 326 327 // SyncProgress retrieves the current progress of the sync algorithm. If there's 328 // no sync currently running, it returns nil. 329 func (ec *Client) SyncProgress(ctx context.Context) (*ethereum.SyncProgress, error) { 330 var raw json.RawMessage 331 if err := ec.c.CallContext(ctx, &raw, "eth_syncing"); err != nil { 332 return nil, err 333 } 334 // Handle the possible response types 335 var syncing bool 336 if err := json.Unmarshal(raw, &syncing); err == nil { 337 return nil, nil // Not syncing (always false) 338 } 339 var progress *rpcProgress 340 if err := json.Unmarshal(raw, &progress); err != nil { 341 return nil, err 342 } 343 return ðereum.SyncProgress{ 344 StartingBlock: uint64(progress.StartingBlock), 345 CurrentBlock: uint64(progress.CurrentBlock), 346 HighestBlock: uint64(progress.HighestBlock), 347 PulledStates: uint64(progress.PulledStates), 348 KnownStates: uint64(progress.KnownStates), 349 }, nil 350 } 351 352 // SubscribeNewHead subscribes to notifications about the current blockchain head 353 // on the given channel. 354 func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { 355 return ec.c.EthSubscribe(ctx, ch, "newHeads") 356 } 357 358 // State Access 359 360 // NetworkID returns the network ID (also known as the chain ID) for this chain. 361 func (ec *Client) NetworkID(ctx context.Context) (*big.Int, error) { 362 version := new(big.Int) 363 var ver string 364 if err := ec.c.CallContext(ctx, &ver, "net_version"); err != nil { 365 return nil, err 366 } 367 if _, ok := version.SetString(ver, 10); !ok { 368 return nil, fmt.Errorf("invalid net_version result %q", ver) 369 } 370 return version, nil 371 } 372 373 // BalanceAt returns the wei balance of the given account. 374 // The block number can be nil, in which case the balance is taken from the latest known block. 375 func (ec *Client) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error) { 376 var result hexutil.Big 377 err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, toBlockNumArg(blockNumber)) 378 return (*big.Int)(&result), err 379 } 380 381 // StorageAt returns the value of key in the contract storage of the given account. 382 // The block number can be nil, in which case the value is taken from the latest known block. 383 func (ec *Client) StorageAt(ctx context.Context, account common.Address, key common.Hash, blockNumber *big.Int) ([]byte, error) { 384 var result hexutil.Bytes 385 err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, toBlockNumArg(blockNumber)) 386 return result, err 387 } 388 389 // CodeAt returns the contract code of the given account. 390 // The block number can be nil, in which case the code is taken from the latest known block. 391 func (ec *Client) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) { 392 var result hexutil.Bytes 393 err := ec.c.CallContext(ctx, &result, "eth_getCode", account, toBlockNumArg(blockNumber)) 394 return result, err 395 } 396 397 // NonceAt returns the account nonce of the given account. 398 // The block number can be nil, in which case the nonce is taken from the latest known block. 399 func (ec *Client) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error) { 400 var result hexutil.Uint64 401 err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, toBlockNumArg(blockNumber)) 402 return uint64(result), err 403 } 404 405 // Filters 406 407 // FilterLogs executes a filter query. 408 func (ec *Client) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { 409 var result []types.Log 410 arg, err := toFilterArg(q) 411 if err != nil { 412 return nil, err 413 } 414 err = ec.c.CallContext(ctx, &result, "eth_getLogs", arg) 415 return result, err 416 } 417 418 // SubscribeFilterLogs subscribes to the results of a streaming filter query. 419 func (ec *Client) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { 420 arg, err := toFilterArg(q) 421 if err != nil { 422 return nil, err 423 } 424 return ec.c.EthSubscribe(ctx, ch, "logs", arg) 425 } 426 427 func toFilterArg(q ethereum.FilterQuery) (interface{}, error) { 428 arg := map[string]interface{}{ 429 "address": q.Addresses, 430 "topics": q.Topics, 431 } 432 if q.BlockHash != nil { 433 arg["blockHash"] = *q.BlockHash 434 if q.FromBlock != nil || q.ToBlock != nil { 435 return nil, fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock") 436 } 437 } else { 438 if q.FromBlock == nil { 439 arg["fromBlock"] = "0x0" 440 } else { 441 arg["fromBlock"] = toBlockNumArg(q.FromBlock) 442 } 443 arg["toBlock"] = toBlockNumArg(q.ToBlock) 444 } 445 return arg, nil 446 } 447 448 // Pending State 449 450 // PendingBalanceAt returns the wei balance of the given account in the pending state. 451 func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) { 452 var result hexutil.Big 453 err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending") 454 return (*big.Int)(&result), err 455 } 456 457 // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state. 458 func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) { 459 var result hexutil.Bytes 460 err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, "pending") 461 return result, err 462 } 463 464 // PendingCodeAt returns the contract code of the given account in the pending state. 465 func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { 466 var result hexutil.Bytes 467 err := ec.c.CallContext(ctx, &result, "eth_getCode", account, "pending") 468 return result, err 469 } 470 471 // PendingNonceAt returns the account nonce of the given account in the pending state. 472 // This is the nonce that should be used for the next transaction. 473 func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { 474 var result hexutil.Uint64 475 err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending") 476 return uint64(result), err 477 } 478 479 // PendingTransactionCount returns the total number of transactions in the pending state. 480 func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) { 481 var num hexutil.Uint 482 err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByNumber", "pending") 483 return uint(num), err 484 } 485 486 // TODO: SubscribePendingTransactions (needs server side) 487 488 // Contract Calling 489 490 // CallContract executes a message call transaction, which is directly executed in the VM 491 // of the node, but never mined into the blockchain. 492 // 493 // blockNumber selects the block height at which the call runs. It can be nil, in which 494 // case the code is taken from the latest known block. Note that state from very old 495 // blocks might not be available. 496 func (ec *Client) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { 497 var hex hexutil.Bytes 498 err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), toBlockNumArg(blockNumber)) 499 if err != nil { 500 return nil, err 501 } 502 return hex, nil 503 } 504 505 // PendingCallContract executes a message call transaction using the EVM. 506 // The state seen by the contract call is the pending state. 507 func (ec *Client) PendingCallContract(ctx context.Context, msg ethereum.CallMsg) ([]byte, error) { 508 var hex hexutil.Bytes 509 err := ec.c.CallContext(ctx, &hex, "eth_call", toCallArg(msg), "pending") 510 if err != nil { 511 return nil, err 512 } 513 return hex, nil 514 } 515 516 // SuggestGasPrice retrieves the currently suggested gas price to allow a timely 517 // execution of a transaction. 518 func (ec *Client) SuggestGasPrice(ctx context.Context) (*big.Int, error) { 519 var hex hexutil.Big 520 if err := ec.c.CallContext(ctx, &hex, "eth_gasPrice"); err != nil { 521 return nil, err 522 } 523 return (*big.Int)(&hex), nil 524 } 525 526 // EstimateGas tries to estimate the gas needed to execute a specific transaction based on 527 // the current pending state of the backend blockchain. There is no guarantee that this is 528 // the true gas limit requirement as other transactions may be added or removed by miners, 529 // but it should provide a basis for setting a reasonable default. 530 func (ec *Client) EstimateGas(ctx context.Context, msg ethereum.CallMsg) (uint64, error) { 531 var hex hexutil.Uint64 532 err := ec.c.CallContext(ctx, &hex, "eth_estimateGas", toCallArg(msg)) 533 if err != nil { 534 return 0, err 535 } 536 return uint64(hex), nil 537 } 538 539 // SendTransaction injects a signed transaction into the pending pool for execution. 540 // 541 // If the transaction was a contract creation use the TransactionReceipt method to get the 542 // contract address after the transaction has been mined. 543 func (ec *Client) SendTransaction(ctx context.Context, tx *types.Transaction) error { 544 data, err := rlp.EncodeToBytes(tx) 545 if err != nil { 546 return err 547 } 548 return ec.c.CallContext(ctx, nil, "eth_sendRawTransaction", hexutil.Encode(data)) 549 } 550 551 func toCallArg(msg ethereum.CallMsg) interface{} { 552 arg := map[string]interface{}{ 553 "from": msg.From, 554 "to": msg.To, 555 } 556 if len(msg.Data) > 0 { 557 arg["data"] = hexutil.Bytes(msg.Data) 558 } 559 if msg.Value != nil { 560 arg["value"] = (*hexutil.Big)(msg.Value) 561 } 562 if msg.Gas != 0 { 563 arg["gas"] = hexutil.Uint64(msg.Gas) 564 } 565 if msg.GasPrice != nil { 566 arg["gasPrice"] = (*hexutil.Big)(msg.GasPrice) 567 } 568 return arg 569 }