1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
//! # Casper client library
//!
//! The crate provides functions for interacting with a Casper network.
//!
//! Most of the functions involve sending a JSON-RPC request to a specified node on the chosen
//! network, and providing the RPC response.
//!
//! # Common Parameters
//!
//! Many of the functions have similar parameters. Descriptions for these common ones follow:
//!
//! * <code>rpc_id: <a href="enum.JsonRpcId.html">JsonRpcId</a></code> - The JSON-RPC identifier,
//! applied to the request and returned in the response.
//! * <code>node_address: &<a href="https://doc.rust-lang.org/std/primitive.str.html">str</a></code> -
//! The hostname or IP and port of the server, e.g. `http://127.0.0.1:7777`.
//! * <code>verbosity: <a href="enum.Verbosity.html">Verbosity</a></code> - When `Low`, nothing is
//! printed to stdout. For `Medium`, the request and response are printed to `stdout` with long
//! string fields (e.g. hex-formatted raw Wasm bytes) shortened to a string indicating the char
//! count of the field. `High` verbosity is the same as `Medium` except without abbreviation of
//! long fields.
//! * <code>maybe_block_identifier: <a href="https://doc.rust-lang.org/core/option/enum.Option.html">Option</a><<a href="rpcs/common/enum.BlockIdentifier.html">BlockIdentifier</a>></code> -
//! The identifier of the [`Block`] to use, either block height or block hash. If `None`, the
//! latest `Block` known on the server will be used.
#![doc(
html_root_url = "https://docs.rs/casper-client/2.0.0",
html_favicon_url = "https://raw.githubusercontent.com/CasperLabs/casper-node/master/images/CasperLabs_Logo_Favicon_RGB_50px.png",
html_logo_url = "https://raw.githubusercontent.com/CasperLabs/casper-node/master/images/CasperLabs_Logo_Symbol_RGB.png",
test(attr(forbid(warnings)))
)]
#![warn(
missing_docs,
trivial_casts,
trivial_numeric_casts,
unused_qualifications
)]
pub mod cli;
mod error;
mod json_rpc;
pub mod keygen;
mod output_kind;
pub mod rpcs;
mod transfer_target;
pub mod types;
mod validation;
mod verbosity;
use std::{
fs,
io::{Cursor, Read, Write},
path::Path,
};
use serde::Serialize;
use casper_hashing::Digest;
#[cfg(doc)]
use casper_types::Transfer;
use casper_types::{Key, PublicKey, SecretKey, URef};
pub use error::Error;
use json_rpc::JsonRpcCall;
pub use json_rpc::{JsonRpcId, SuccessResponse};
pub use output_kind::OutputKind;
use rpcs::{
common::{BlockIdentifier, GlobalStateIdentifier},
results::{
GetAccountResult, GetAuctionInfoResult, GetBalanceResult, GetBlockResult,
GetBlockTransfersResult, GetChainspecResult, GetDeployResult, GetDictionaryItemResult,
GetEraInfoResult, GetEraSummaryResult, GetNodeStatusResult, GetPeersResult,
GetStateRootHashResult, GetValidatorChangesResult, ListRpcsResult, PutDeployResult,
QueryBalanceResult, QueryGlobalStateResult, SpeculativeExecResult,
},
v1_5_0::{
get_account::{GetAccountParams, GET_ACCOUNT_METHOD},
get_auction_info::{GetAuctionInfoParams, GET_AUCTION_INFO_METHOD},
get_balance::{GetBalanceParams, GET_BALANCE_METHOD},
get_block::{GetBlockParams, GET_BLOCK_METHOD},
get_block_transfers::{GetBlockTransfersParams, GET_BLOCK_TRANSFERS_METHOD},
get_chainspec::GET_CHAINSPEC_METHOD,
get_deploy::{GetDeployParams, GET_DEPLOY_METHOD},
get_dictionary_item::{GetDictionaryItemParams, GET_DICTIONARY_ITEM_METHOD},
get_era_info::{GetEraInfoParams, GET_ERA_INFO_METHOD},
get_era_summary::{GetEraSummaryParams, GET_ERA_SUMMARY_METHOD},
get_node_status::GET_NODE_STATUS_METHOD,
get_peers::GET_PEERS_METHOD,
get_state_root_hash::{GetStateRootHashParams, GET_STATE_ROOT_HASH_METHOD},
get_validator_changes::GET_VALIDATOR_CHANGES_METHOD,
list_rpcs::LIST_RPCS_METHOD,
put_deploy::{PutDeployParams, PUT_DEPLOY_METHOD},
query_balance::{PurseIdentifier, QueryBalanceParams, QUERY_BALANCE_METHOD},
query_global_state::{QueryGlobalStateParams, QUERY_GLOBAL_STATE_METHOD},
speculative_exec::{SpeculativeExecParams, SPECULATIVE_EXEC_METHOD},
},
DictionaryItemIdentifier,
};
pub use transfer_target::TransferTarget;
#[cfg(doc)]
use types::{Account, Block, StoredValue};
use types::{Deploy, DeployHash, MAX_SERIALIZED_SIZE_OF_DEPLOY};
pub use validation::ValidateResponseError;
pub use verbosity::Verbosity;
/// Puts a [`Deploy`] to the network for execution.
///
/// Sends a JSON-RPC `account_put_deploy` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn put_deploy(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
deploy: Deploy,
) -> Result<SuccessResponse<PutDeployResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(PUT_DEPLOY_METHOD, Some(PutDeployParams::new(deploy)))
.await
}
/// Puts a [`Deploy`] to a single node for speculative execution on that node only.
///
/// Sends a JSON-RPC `speculative_exec` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn speculative_exec(
rpc_id: JsonRpcId,
node_address: &str,
block_identifier: Option<BlockIdentifier>,
verbosity: Verbosity,
deploy: Deploy,
) -> Result<SuccessResponse<SpeculativeExecResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(
SPECULATIVE_EXEC_METHOD,
Some(SpeculativeExecParams::new(block_identifier, deploy)),
)
.await
}
/// Outputs a [`Deploy`] to a file or stdout.
///
/// As a file, the `Deploy` can subsequently be signed by other parties using [`sign_deploy_file`]
/// and then read and sent to the network for execution using [`read_deploy_file`] and
/// [`put_deploy`] respectively.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if
/// `OutputKind::Stdout`, causes the `Deploy` to be printed `stdout`.
pub fn output_deploy(output: OutputKind, deploy: &Deploy) -> Result<(), Error> {
write_deploy(deploy, output.get()?)?;
output.commit()
}
/// Reads a previously-saved [`Deploy`] from a file.
pub fn read_deploy_file<P: AsRef<Path>>(deploy_path: P) -> Result<Deploy, Error> {
let input = fs::read(deploy_path.as_ref()).map_err(|error| Error::IoError {
context: format!(
"unable to read deploy file at '{}'",
deploy_path.as_ref().display()
),
error,
})?;
read_deploy(Cursor::new(input))
}
/// Reads a previously-saved [`Deploy`] from a file, cryptographically signs it, and outputs it
/// to a file or stdout.
///
/// `output` specifies the output file and corresponding overwrite behaviour, or if
/// `OutputKind::Stdout`, causes the `Deploy` to be printed `stdout`.
///
/// The same path can be specified for input and output, and if the operation fails, the original
/// input file will be left unmodified.
pub fn sign_deploy_file<P: AsRef<Path>>(
input_path: P,
secret_key: &SecretKey,
output: OutputKind,
) -> Result<(), Error> {
let mut deploy = read_deploy_file(input_path)?;
deploy.sign(secret_key);
deploy.is_valid_size(MAX_SERIALIZED_SIZE_OF_DEPLOY)?;
write_deploy(&deploy, output.get()?)?;
output.commit()
}
/// Retrieves a [`Deploy`] and its metadata (i.e. execution results) from the network.
///
/// Sends a JSON-RPC `info_get_deploy` request to the specified node.
///
/// `finalized_approvals` defines whether to return the `Deploy` with its approvals as finalized by
/// consensus of the validators on the network, or as originally received by the specified node.
///
/// For details of the other parameters, see [the module docs](crate#common-parameters).
pub async fn get_deploy(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
deploy_hash: DeployHash,
finalized_approvals: bool,
) -> Result<SuccessResponse<GetDeployResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(
GET_DEPLOY_METHOD,
Some(GetDeployParams::new(deploy_hash, finalized_approvals)),
)
.await
}
/// Retrieves a [`Block`] from the network.
///
/// Sends a JSON-RPC `chain_get_block` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_block(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetBlockResult>, Error> {
let params = maybe_block_identifier.map(GetBlockParams::new);
let success_response = JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_BLOCK_METHOD, params)
.await?;
validation::validate_get_block_result(maybe_block_identifier, &success_response.result)?;
Ok(success_response)
}
/// Retrieves all [`Transfer`] items for a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_block_transfers` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_block_transfers(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetBlockTransfersResult>, Error> {
let params = maybe_block_identifier.map(GetBlockTransfersParams::new);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_BLOCK_TRANSFERS_METHOD, params)
.await
}
/// Retrieves a state root hash at a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_state_root_hash` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_state_root_hash(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetStateRootHashResult>, Error> {
let params = maybe_block_identifier.map(GetStateRootHashParams::new);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_STATE_ROOT_HASH_METHOD, params)
.await
}
/// Retrieves era information from the network at a given [`Block`].
///
/// Sends a JSON-RPC `chain_get_era_summary` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_era_summary(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetEraSummaryResult>, Error> {
let params = maybe_block_identifier.map(GetEraSummaryParams::new);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_ERA_SUMMARY_METHOD, params)
.await
}
/// Retrieves a [`StoredValue`] from global state at a given [`Block`] or state root hash.
///
/// Sends a JSON-RPC `query_global_state` request to the specified node.
///
/// `key` specifies the key under which the value is stored in global state.
///
/// `path` defines the further path (if any) from `key` to navigate to during the query. This is
/// only applicable in the case where the value under `key` is an account or contract. In this
/// case, the first `path` element represents a name in the account/contract's named keys. If that
/// second `Key` also points to an account or contract, then a second path element can be added to
/// continue the query into that account/contract's named keys. This can continue up to the
/// server's configured maximum query depth (5 by default).
///
/// For details of the other parameters, see [the module docs](crate#common-parameters).
pub async fn query_global_state(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
global_state_identifier: GlobalStateIdentifier,
key: Key,
path: Vec<String>,
) -> Result<SuccessResponse<QueryGlobalStateResult>, Error> {
let params = QueryGlobalStateParams::new(global_state_identifier, key, path);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(QUERY_GLOBAL_STATE_METHOD, Some(params))
.await
}
/// Retrieves a purse's balance from global state at a given [`Block`] or state root hash.
///
/// Sends a JSON-RPC `query_balance` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn query_balance(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_global_state_identifier: Option<GlobalStateIdentifier>,
purse_identifier: PurseIdentifier,
) -> Result<SuccessResponse<QueryBalanceResult>, Error> {
let params = QueryBalanceParams::new(maybe_global_state_identifier, purse_identifier);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(QUERY_BALANCE_METHOD, Some(params))
.await
}
/// Retrieves a [`StoredValue`] from a dictionary at a given state root hash.
///
/// Sends a JSON-RPC `state_get_dictionary_item` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_dictionary_item(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
state_root_hash: Digest,
dictionary_item_identifier: DictionaryItemIdentifier,
) -> Result<SuccessResponse<GetDictionaryItemResult>, Error> {
let params = GetDictionaryItemParams::new(state_root_hash, dictionary_item_identifier);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_DICTIONARY_ITEM_METHOD, Some(params))
.await
}
/// Retrieves a purse's balance at a given state root hash.
///
/// Sends a JSON-RPC `state_get_balance` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_balance(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
state_root_hash: Digest,
purse: URef,
) -> Result<SuccessResponse<GetBalanceResult>, Error> {
let params = GetBalanceParams::new(state_root_hash, purse);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_BALANCE_METHOD, Some(params))
.await
}
/// Retrieves an [`Account`] at a given [`Block`].
///
/// Sends a JSON-RPC `state_get_account_info` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_account(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
account_identifier: PublicKey,
) -> Result<SuccessResponse<GetAccountResult>, Error> {
let params = GetAccountParams::new(account_identifier, maybe_block_identifier);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_ACCOUNT_METHOD, Some(params))
.await
}
/// Retrieves the bids and validators at a given [`Block`].
///
/// Sends a JSON-RPC `state_get_auction_info` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_auction_info(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetAuctionInfoResult>, Error> {
let params = maybe_block_identifier.map(GetAuctionInfoParams::new);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_AUCTION_INFO_METHOD, params)
.await
}
/// Retrieves the status changes of the active validators on the network.
///
/// Sends a JSON-RPC `info_get_validator_changes` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_validator_changes(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
) -> Result<SuccessResponse<GetValidatorChangesResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request::<(), _>(GET_VALIDATOR_CHANGES_METHOD, None)
.await
}
/// Retrieves the IDs and addresses of the specified node's peers.
///
/// Sends a JSON-RPC `info_get_peers` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_peers(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
) -> Result<SuccessResponse<GetPeersResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request::<(), _>(GET_PEERS_METHOD, None)
.await
}
/// Retrieves the status of the specified node.
///
/// Sends a JSON-RPC `info_get_status` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_node_status(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
) -> Result<SuccessResponse<GetNodeStatusResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request::<(), _>(GET_NODE_STATUS_METHOD, None)
.await
}
/// Retrieves the Chainspec of the network.
///
/// Sends a JSON-RPC `info_get_chainspec` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn get_chainspec(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
) -> Result<SuccessResponse<GetChainspecResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request::<(), _>(GET_CHAINSPEC_METHOD, None)
.await
}
/// Retrieves the interface description (the schema including examples in OpenRPC format) of the
/// JSON-RPC server's API.
///
/// Sends a JSON-RPC `rpc.discover` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters).
pub async fn list_rpcs(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
) -> Result<SuccessResponse<ListRpcsResult>, Error> {
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request::<(), _>(LIST_RPCS_METHOD, None)
.await
}
/// JSON-encode and pretty-print the given value to stdout at the given verbosity level.
///
/// When `verbosity` is `Low`, nothing is printed. For `Medium`, the value is printed with long
/// string fields shortened to a string indicating the character count of the field. `High`
/// verbosity is the same as `Medium` except without abbreviation of long fields.
pub(crate) fn json_pretty_print<T: ?Sized + Serialize>(
value: &T,
verbosity: Verbosity,
) -> Result<(), Error> {
let output = match verbosity {
Verbosity::Low => return Ok(()),
Verbosity::Medium => casper_types::json_pretty_print(value),
Verbosity::High => serde_json::to_string_pretty(value),
}
.map_err(|error| Error::FailedToEncodeToJson {
context: "in json_pretty_print",
error,
})?;
println!("{}", output);
Ok(())
}
fn write_deploy<W: Write>(deploy: &Deploy, mut output: W) -> Result<(), Error> {
let content =
serde_json::to_string_pretty(deploy).map_err(|error| Error::FailedToEncodeToJson {
context: "writing deploy",
error,
})?;
output
.write_all(content.as_bytes())
.map_err(|error| Error::IoError {
context: "unable to write deploy".to_owned(),
error,
})
}
fn read_deploy<R: Read>(input: R) -> Result<Deploy, Error> {
let deploy: Deploy =
serde_json::from_reader(input).map_err(|error| Error::FailedToDecodeFromJson {
context: "reading deploy",
error,
})?;
deploy.is_valid_size(MAX_SERIALIZED_SIZE_OF_DEPLOY)?;
Ok(deploy)
}
/// Retrieves era information from the network at a given switch [`Block`].
///
/// Sends a JSON-RPC `chain_get_era_info_by_switch_block` request to the specified node.
///
/// For details of the parameters, see [the module docs](crate#common-parameters). Note that if the
/// specified block is not a switch block then the response will have no era info.
#[deprecated(
since = "2.0.0",
note = "prefer 'get_era_summary' as it doesn't require a switch block"
)]
pub async fn get_era_info(
rpc_id: JsonRpcId,
node_address: &str,
verbosity: Verbosity,
maybe_block_identifier: Option<BlockIdentifier>,
) -> Result<SuccessResponse<GetEraInfoResult>, Error> {
let params = maybe_block_identifier.map(GetEraInfoParams::new);
JsonRpcCall::new(rpc_id, node_address, verbosity)
.send_request(GET_ERA_INFO_METHOD, params)
.await
}