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