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