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