github.com/dominant-strategies/go-quai@v0.28.2/quaiclient/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 Quai RPC API. 18 package ethclient 19 20 import ( 21 "context" 22 "encoding/json" 23 "errors" 24 "fmt" 25 "math/big" 26 27 quai "github.com/dominant-strategies/go-quai" 28 "github.com/dominant-strategies/go-quai/common" 29 "github.com/dominant-strategies/go-quai/common/hexutil" 30 "github.com/dominant-strategies/go-quai/core/types" 31 "github.com/dominant-strategies/go-quai/rpc" 32 ) 33 34 // Client defines typed wrappers for the Quai 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 ExtTransactions []rpcTransaction `json:"extTransactions"` 102 SubManifest types.BlockManifest `json:"manifest"` 103 } 104 105 func (ec *Client) getBlock(ctx context.Context, method string, args ...interface{}) (*types.Block, error) { 106 var raw json.RawMessage 107 err := ec.c.CallContext(ctx, &raw, method, args...) 108 if err != nil { 109 return nil, err 110 } else if len(raw) == 0 { 111 return nil, quai.NotFound 112 } 113 // Decode header and transactions. 114 var head *types.Header 115 var body rpcBlock 116 if err := json.Unmarshal(raw, &head); err != nil { 117 return nil, err 118 } 119 if err := json.Unmarshal(raw, &body); err != nil { 120 return nil, err 121 } 122 // Quick-verify transaction and uncle lists. This mostly helps with debugging the server. 123 if head.UncleHash() == types.EmptyUncleHash && len(body.UncleHashes) > 0 { 124 return nil, fmt.Errorf("server returned non-empty uncle list but block header indicates no uncles") 125 } 126 if head.UncleHash() != types.EmptyUncleHash && len(body.UncleHashes) == 0 { 127 return nil, fmt.Errorf("server returned empty uncle list but block header indicates uncles") 128 } 129 if head.TxHash() == types.EmptyRootHash && len(body.Transactions) > 0 { 130 return nil, fmt.Errorf("server returned non-empty transaction list but block header indicates no transactions") 131 } 132 if head.TxHash() != types.EmptyRootHash && len(body.Transactions) == 0 { 133 return nil, fmt.Errorf("server returned empty transaction list but block header indicates transactions") 134 } 135 if head.EtxHash() == types.EmptyRootHash && len(body.ExtTransactions) > 0 { 136 return nil, fmt.Errorf("server returned non-empty external transaction list but block header indicates no transactions") 137 } 138 if head.EtxHash() != types.EmptyRootHash && len(body.ExtTransactions) == 0 { 139 return nil, fmt.Errorf("server returned empty external transaction list but block header indicates transactions") 140 } 141 if head.ManifestHash() == types.EmptyRootHash && len(body.SubManifest) > 0 { 142 return nil, fmt.Errorf("server returned non-empty subordinate manifest but block header indicates no transactions") 143 } 144 if head.ManifestHash() != types.EmptyRootHash && len(body.SubManifest) == 0 { 145 return nil, fmt.Errorf("server returned empty subordinate manifest but block header indicates transactions") 146 } 147 // Load uncles because they are not included in the block response. 148 var uncles []*types.Header 149 if len(body.UncleHashes) > 0 { 150 uncles = make([]*types.Header, len(body.UncleHashes)) 151 reqs := make([]rpc.BatchElem, len(body.UncleHashes)) 152 for i := range reqs { 153 reqs[i] = rpc.BatchElem{ 154 Method: "eth_getUncleByBlockHashAndIndex", 155 Args: []interface{}{body.Hash, hexutil.EncodeUint64(uint64(i))}, 156 Result: &uncles[i], 157 } 158 } 159 if err := ec.c.BatchCallContext(ctx, reqs); err != nil { 160 return nil, err 161 } 162 for i := range reqs { 163 if reqs[i].Error != nil { 164 return nil, reqs[i].Error 165 } 166 if uncles[i] == nil { 167 return nil, fmt.Errorf("got null header for uncle %d of block %x", i, body.Hash[:]) 168 } 169 } 170 } 171 // Fill the sender cache of transactions in the block. 172 txs := make([]*types.Transaction, len(body.Transactions)) 173 for i, tx := range body.Transactions { 174 if tx.From != nil { 175 setSenderFromServer(tx.tx, *tx.From, body.Hash) 176 } 177 txs[i] = tx.tx 178 } 179 etxs := make([]*types.Transaction, len(body.ExtTransactions)) 180 for i, etx := range body.ExtTransactions { 181 etxs[i] = etx.tx 182 } 183 // Fill the sender cache of subordinate block hashes in the block manifest. 184 var manifest types.BlockManifest 185 copy(manifest, body.SubManifest) 186 for i, tx := range body.Transactions { 187 if tx.From != nil { 188 setSenderFromServer(tx.tx, *tx.From, body.Hash) 189 } 190 txs[i] = tx.tx 191 } 192 return types.NewBlockWithHeader(head).WithBody(txs, uncles, etxs, manifest), nil 193 } 194 195 // HeaderByHash returns the block header with the given hash. 196 func (ec *Client) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { 197 var head *types.Header 198 err := ec.c.CallContext(ctx, &head, "eth_getBlockByHash", hash, false) 199 if err == nil && head == nil { 200 err = quai.NotFound 201 } 202 return head, err 203 } 204 205 // HeaderByNumber returns a block header from the current canonical chain. If number is 206 // nil, the latest known header is returned. 207 func (ec *Client) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { 208 var head *types.Header 209 err := ec.c.CallContext(ctx, &head, "eth_getBlockByNumber", toBlockNumArg(number), false) 210 if err == nil && head == nil { 211 err = quai.NotFound 212 } 213 return head, err 214 } 215 216 type rpcTransaction struct { 217 tx *types.Transaction 218 txExtraInfo 219 } 220 221 type txExtraInfo struct { 222 BlockNumber *string `json:"blockNumber,omitempty"` 223 BlockHash *common.Hash `json:"blockHash,omitempty"` 224 From *common.Address `json:"from,omitempty"` 225 } 226 227 func (tx *rpcTransaction) UnmarshalJSON(msg []byte) error { 228 if err := json.Unmarshal(msg, &tx.tx); err != nil { 229 return err 230 } 231 return json.Unmarshal(msg, &tx.txExtraInfo) 232 } 233 234 // TransactionByHash returns the transaction with the given hash. 235 func (ec *Client) TransactionByHash(ctx context.Context, hash common.Hash) (tx *types.Transaction, isPending bool, err error) { 236 var json *rpcTransaction 237 err = ec.c.CallContext(ctx, &json, "eth_getTransactionByHash", hash) 238 if err != nil { 239 return nil, false, err 240 } else if json == nil { 241 return nil, false, quai.NotFound 242 } else if _, r, _ := json.tx.RawSignatureValues(); r == nil && json.tx.Type() != types.ExternalTxType { 243 return nil, false, fmt.Errorf("server returned transaction without signature") 244 } 245 if json.From != nil && json.BlockHash != nil { 246 setSenderFromServer(json.tx, *json.From, *json.BlockHash) 247 } 248 return json.tx, json.BlockNumber == nil, nil 249 } 250 251 // TransactionSender returns the sender address of the given transaction. The transaction 252 // must be known to the remote node and included in the blockchain at the given block and 253 // index. The sender is the one derived by the protocol at the time of inclusion. 254 // 255 // There is a fast-path for transactions retrieved by TransactionByHash and 256 // TransactionInBlock. Getting their sender address can be done without an RPC interaction. 257 func (ec *Client) TransactionSender(ctx context.Context, tx *types.Transaction, block common.Hash, index uint) (common.Address, error) { 258 // Try to load the address from the cache. 259 sender, err := types.Sender(&senderFromServer{blockhash: block}, tx) 260 if err == nil { 261 return sender, nil 262 } 263 var meta struct { 264 Hash common.Hash 265 From common.Address 266 } 267 if err = ec.c.CallContext(ctx, &meta, "eth_getTransactionByBlockHashAndIndex", block, hexutil.Uint64(index)); err != nil { 268 return common.ZeroAddr, err 269 } 270 if meta.Hash == (common.Hash{}) || meta.Hash != tx.Hash() { 271 return common.ZeroAddr, errors.New("wrong inclusion block/index") 272 } 273 return meta.From, nil 274 } 275 276 // TransactionCount returns the total number of transactions in the given block. 277 func (ec *Client) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { 278 var num hexutil.Uint 279 err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByHash", blockHash) 280 return uint(num), err 281 } 282 283 // TransactionInBlock returns a single transaction at index in the given block. 284 func (ec *Client) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { 285 var json *rpcTransaction 286 err := ec.c.CallContext(ctx, &json, "eth_getTransactionByBlockHashAndIndex", blockHash, hexutil.Uint64(index)) 287 if err != nil { 288 return nil, err 289 } 290 if json == nil { 291 return nil, quai.NotFound 292 } else if _, r, _ := json.tx.RawSignatureValues(); r == nil && json.tx.Type() != types.ExternalTxType { 293 return nil, fmt.Errorf("server returned transaction without signature") 294 } 295 if json.From != nil && json.BlockHash != nil { 296 setSenderFromServer(json.tx, *json.From, *json.BlockHash) 297 } 298 return json.tx, err 299 } 300 301 // TransactionReceipt returns the receipt of a transaction by transaction hash. 302 // Note that the receipt is not available for pending transactions. 303 func (ec *Client) TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) { 304 var r *types.Receipt 305 err := ec.c.CallContext(ctx, &r, "eth_getTransactionReceipt", txHash) 306 if err == nil { 307 if r == nil { 308 return nil, quai.NotFound 309 } 310 } 311 return r, err 312 } 313 314 type rpcProgress struct { 315 StartingBlock hexutil.Uint64 316 CurrentBlock hexutil.Uint64 317 HighestBlock hexutil.Uint64 318 PulledStates hexutil.Uint64 319 KnownStates hexutil.Uint64 320 } 321 322 // SyncProgress retrieves the current progress of the sync algorithm. If there's 323 // no sync currently running, it returns nil. 324 func (ec *Client) SyncProgress(ctx context.Context) (*quai.SyncProgress, error) { 325 var raw json.RawMessage 326 if err := ec.c.CallContext(ctx, &raw, "eth_syncing"); err != nil { 327 return nil, err 328 } 329 // Handle the possible response types 330 var syncing bool 331 if err := json.Unmarshal(raw, &syncing); err == nil { 332 return nil, nil // Not syncing (always false) 333 } 334 var progress *rpcProgress 335 if err := json.Unmarshal(raw, &progress); err != nil { 336 return nil, err 337 } 338 return &quai.SyncProgress{ 339 StartingBlock: uint64(progress.StartingBlock), 340 CurrentBlock: uint64(progress.CurrentBlock), 341 HighestBlock: uint64(progress.HighestBlock), 342 PulledStates: uint64(progress.PulledStates), 343 KnownStates: uint64(progress.KnownStates), 344 }, nil 345 } 346 347 // SubscribeNewHead subscribes to notifications about the current blockchain head 348 // on the given channel. 349 func (ec *Client) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (quai.Subscription, error) { 350 return ec.c.EthSubscribe(ctx, ch, "newHeads") 351 } 352 353 // SubscribePendingHeader subscribes to notifications about the current pending block on the node. 354 func (ec *Client) SubscribePendingHeader(ctx context.Context, ch chan<- *types.Header) (quai.Subscription, error) { 355 return ec.c.EthSubscribe(ctx, ch, "pendingHeader") 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 // Pending State 406 407 // PendingBalanceAt returns the wei balance of the given account in the pending state. 408 func (ec *Client) PendingBalanceAt(ctx context.Context, account common.Address) (*big.Int, error) { 409 var result hexutil.Big 410 err := ec.c.CallContext(ctx, &result, "eth_getBalance", account, "pending") 411 return (*big.Int)(&result), err 412 } 413 414 // PendingStorageAt returns the value of key in the contract storage of the given account in the pending state. 415 func (ec *Client) PendingStorageAt(ctx context.Context, account common.Address, key common.Hash) ([]byte, error) { 416 var result hexutil.Bytes 417 err := ec.c.CallContext(ctx, &result, "eth_getStorageAt", account, key, "pending") 418 return result, err 419 } 420 421 // PendingCodeAt returns the contract code of the given account in the pending state. 422 func (ec *Client) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { 423 var result hexutil.Bytes 424 err := ec.c.CallContext(ctx, &result, "eth_getCode", account, "pending") 425 return result, err 426 } 427 428 // PendingNonceAt returns the account nonce of the given account in the pending state. 429 // This is the nonce that should be used for the next transaction. 430 func (ec *Client) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { 431 var result hexutil.Uint64 432 err := ec.c.CallContext(ctx, &result, "eth_getTransactionCount", account, "pending") 433 return uint64(result), err 434 } 435 436 // PendingTransactionCount returns the total number of transactions in the pending state. 437 func (ec *Client) PendingTransactionCount(ctx context.Context) (uint, error) { 438 var num hexutil.Uint 439 err := ec.c.CallContext(ctx, &num, "eth_getBlockTransactionCountByNumber", "pending") 440 return uint(num), err 441 } 442 443 // GetPendingHeader gets the latest pending header from the chain. 444 func (ec *Client) GetPendingHeader(ctx context.Context) (*types.Header, error) { 445 var pendingHeader *types.Header 446 err := ec.c.CallContext(ctx, &pendingHeader, "quai_getPendingHeader") 447 if err != nil { 448 return nil, err 449 } 450 return pendingHeader, nil 451 } 452 453 // ReceiveMinedHeader sends a mined block back to the node 454 func (ec *Client) ReceiveMinedHeader(ctx context.Context, header *types.Header) error { 455 data := header.RPCMarshalHeader() 456 return ec.c.CallContext(ctx, nil, "quai_receiveMinedHeader", data) 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 quai.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 quai.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 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 quai.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 quai.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 }