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