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