-
Notifications
You must be signed in to change notification settings - Fork 44
test(dapi): dapi-cli example in dapi-grpc #2801
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
lklimek
wants to merge
2
commits into
v2.1-dev
Choose a base branch
from
test/dapi-cli
base: v2.1-dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| use clap::Args; | ||
| use dapi_grpc::core::v0::{core_client::CoreClient, GetBlockRequest}; | ||
| use dapi_grpc::tonic::transport::Channel; | ||
| use tracing::info; | ||
|
|
||
| use crate::error::{CliError, CliResult}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct BlockHashCommand { | ||
| /// Block height to query (>= 1) | ||
| #[arg(long)] | ||
| pub height: u32, | ||
| } | ||
|
|
||
| pub async fn run(url: &str, cmd: BlockHashCommand) -> CliResult<()> { | ||
| if cmd.height < 1 { | ||
| return Err( | ||
| std::io::Error::new(std::io::ErrorKind::InvalidInput, "height must be >= 1").into(), | ||
| ); | ||
| } | ||
|
|
||
| info!(url = %url, height = cmd.height, "Querying block hash"); | ||
|
|
||
| let channel = Channel::from_shared(url.to_string()) | ||
| .map_err(|source| CliError::InvalidUrl { | ||
| url: url.to_string(), | ||
| source: Box::new(source), | ||
| })? | ||
| .connect() | ||
| .await?; | ||
| let mut client = CoreClient::new(channel); | ||
|
|
||
| let request = GetBlockRequest { | ||
| block: Some(dapi_grpc::core::v0::get_block_request::Block::Height( | ||
| cmd.height, | ||
| )), | ||
| }; | ||
|
|
||
| let response = client.get_block(request).await?; | ||
| let block_bytes = response.into_inner().block; | ||
|
|
||
| // Deserialize and compute hash | ||
| use dashcore::consensus::encode::deserialize; | ||
| use dashcore::Block; | ||
|
|
||
| let block: Block = match deserialize(&block_bytes) { | ||
| Ok(b) => b, | ||
| Err(e) => { | ||
| tracing::error!(block_bytes = hex::encode(&block_bytes), error = %e, "Failed to deserialize block"); | ||
| return Err(CliError::DashCoreEncoding(e)); | ||
| } | ||
| }; | ||
| let block_json = serde_json::to_string_pretty(&block)?; | ||
| let hash_hex = block.block_hash().to_string(); | ||
|
|
||
| println!("Block {} hash: {}\n{}\n", cmd.height, hash_hex, block_json); | ||
| Ok(()) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| use clap::Args; | ||
| use dapi_grpc::core::v0::{ | ||
| block_headers_with_chain_locks_request::FromBlock, core_client::CoreClient, | ||
| BlockHeadersWithChainLocksRequest, | ||
| }; | ||
| use dapi_grpc::tonic::transport::Channel; | ||
| use tracing::{info, warn}; | ||
|
|
||
| use crate::error::{CliError, CliResult}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct ChainLocksCommand { | ||
| /// Optional starting block height for historical context | ||
| #[arg(long)] | ||
| pub from_height: Option<u32>, | ||
| } | ||
|
|
||
| pub async fn run(url: &str, cmd: ChainLocksCommand) -> CliResult<()> { | ||
| info!(url = %url, "Connecting to DAPI Core gRPC for chain locks"); | ||
|
|
||
| let channel = Channel::from_shared(url.to_string()) | ||
| .map_err(|source| CliError::InvalidUrl { | ||
| url: url.to_string(), | ||
| source: Box::new(source), | ||
| })? | ||
| .connect() | ||
| .await?; | ||
| let mut client = CoreClient::new(channel); | ||
|
|
||
| let request = BlockHeadersWithChainLocksRequest { | ||
| count: 0, | ||
| from_block: cmd.from_height.map(FromBlock::FromBlockHeight), | ||
| }; | ||
|
|
||
| println!("📡 Subscribing to chain locks at {}", url); | ||
| if let Some(height) = cmd.from_height { | ||
| println!( | ||
| " Requesting history starting from block height {}", | ||
| height | ||
| ); | ||
| } else { | ||
| println!(" Streaming live chain locks\n"); | ||
| } | ||
|
|
||
| let response = client | ||
| .subscribe_to_block_headers_with_chain_locks(request) | ||
| .await?; | ||
|
|
||
| let mut stream = response.into_inner(); | ||
| let mut block_header_batches = 0usize; | ||
| let mut chain_locks = 0usize; | ||
|
|
||
| while let Some(message) = stream.message().await? { | ||
| use dapi_grpc::core::v0::block_headers_with_chain_locks_response::Responses; | ||
|
|
||
| match message.responses { | ||
| Some(Responses::BlockHeaders(headers)) => { | ||
| block_header_batches += 1; | ||
| let header_count = headers.headers.len(); | ||
| let total_bytes: usize = headers.headers.iter().map(|h| h.len()).sum(); | ||
| println!( | ||
| "🧱 Received block headers batch #{} ({} header(s), {} bytes)", | ||
| block_header_batches, header_count, total_bytes | ||
| ); | ||
| } | ||
| Some(Responses::ChainLock(data)) => { | ||
| chain_locks += 1; | ||
| println!( | ||
| "🔒 Received chain lock #{}, payload size {} bytes", | ||
| chain_locks, | ||
| data.len() | ||
| ); | ||
| } | ||
| None => { | ||
| warn!("Received empty chain lock response message"); | ||
| } | ||
| } | ||
| println!(); | ||
| } | ||
|
|
||
| println!("👋 Chain lock stream ended"); | ||
| Ok(()) | ||
| } |
158 changes: 158 additions & 0 deletions
158
packages/dapi-grpc/examples/dapi-cli/core/masternode.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| use ciborium::de::from_reader; | ||
| use clap::Args; | ||
| use dapi_grpc::core::v0::{core_client::CoreClient, MasternodeListRequest}; | ||
| use dapi_grpc::tonic::transport::Channel; | ||
| use serde::Deserialize; | ||
| use serde_json::Value; | ||
| use std::io::Cursor; | ||
| use tracing::warn; | ||
|
|
||
| use crate::error::{CliError, CliResult}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct MasternodeCommand {} | ||
|
|
||
| pub async fn run(url: &str, _cmd: MasternodeCommand) -> CliResult<()> { | ||
| let channel = Channel::from_shared(url.to_string()) | ||
| .map_err(|source| CliError::InvalidUrl { | ||
| url: url.to_string(), | ||
| source: Box::new(source), | ||
| })? | ||
| .connect() | ||
| .await?; | ||
|
|
||
| let mut client = CoreClient::new(channel); | ||
|
|
||
| println!("📡 Subscribing to masternode list updates at {}", url); | ||
|
|
||
| let response = client | ||
| .subscribe_to_masternode_list(MasternodeListRequest {}) | ||
| .await?; | ||
|
|
||
| let mut stream = response.into_inner(); | ||
| let mut update_index = 0usize; | ||
|
|
||
| while let Some(update) = stream.message().await? { | ||
| update_index += 1; | ||
| let diff_bytes = update.masternode_list_diff; | ||
|
|
||
| println!("🔁 Masternode list update #{}", update_index); | ||
| println!(" Diff payload size: {} bytes", diff_bytes.len()); | ||
|
|
||
| match from_reader::<MasternodeListDiff, _>(Cursor::new(&diff_bytes)) { | ||
| Ok(diff) => print_diff_summary(&diff), | ||
| Err(err) => { | ||
| warn!(error = %err, "Failed to decode masternode diff payload"); | ||
| println!(" Unable to decode diff payload (see logs for details).\n"); | ||
| continue; | ||
| } | ||
| } | ||
|
|
||
| println!(); | ||
| } | ||
|
|
||
| println!("👋 Stream ended"); | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn print_diff_summary(diff: &MasternodeListDiff) { | ||
| let base_hash = diff.base_block_hash.as_deref().unwrap_or("<unknown>"); | ||
| let block_hash = diff.block_hash.as_deref().unwrap_or("<unknown>"); | ||
|
|
||
| println!(" Base block hash : {}", base_hash); | ||
| println!(" Target block hash: {}", block_hash); | ||
|
|
||
| let added = diff.added_mns.len(); | ||
| let updated = diff.updated_mns.len(); | ||
| let removed = diff.removed_mns.len(); | ||
|
|
||
| if added > 0 || updated > 0 || removed > 0 { | ||
| println!( | ||
| " Added: {} | Updated: {} | Removed: {}", | ||
| added, updated, removed | ||
| ); | ||
| } | ||
|
|
||
| let snapshot = if !diff.full_list.is_empty() { | ||
| diff.full_list.len() | ||
| } else if !diff.masternode_list.is_empty() { | ||
| diff.masternode_list.len() | ||
| } else { | ||
| 0 | ||
| }; | ||
|
|
||
| if snapshot > 0 { | ||
| println!(" Snapshot size: {} masternodes", snapshot); | ||
| } | ||
|
|
||
| if let Some(total) = diff.total_mn_count { | ||
| println!(" Reported total masternodes: {}", total); | ||
| } | ||
|
|
||
| let quorum_updates = diff.quorum_diff_updates(); | ||
| if quorum_updates > 0 { | ||
| println!(" Quorum updates: {}", quorum_updates); | ||
| } | ||
|
|
||
| if added == 0 && updated == 0 && removed == 0 && snapshot == 0 && quorum_updates == 0 { | ||
| println!( | ||
| " No masternode or quorum changes detected in this diff (metadata update only)." | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Deserialize)] | ||
| struct MasternodeListDiff { | ||
| #[serde(rename = "baseBlockHash")] | ||
| base_block_hash: Option<String>, | ||
| #[serde(rename = "blockHash")] | ||
| block_hash: Option<String>, | ||
| #[serde(rename = "addedMNs", default)] | ||
| added_mns: Vec<Value>, | ||
| #[serde(rename = "updatedMNs", default)] | ||
| updated_mns: Vec<Value>, | ||
| #[serde(rename = "removedMNs", default)] | ||
| removed_mns: Vec<Value>, | ||
| #[serde(rename = "mnList", default)] | ||
| full_list: Vec<Value>, | ||
| #[serde(rename = "masternodeList", default)] | ||
| masternode_list: Vec<Value>, | ||
| #[serde(rename = "totalMnCount")] | ||
| total_mn_count: Option<u64>, | ||
| #[serde(rename = "quorumDiffs", default)] | ||
| quorum_diffs: Vec<QuorumDiffEntry>, | ||
| #[serde(rename = "newQuorums", default)] | ||
| new_quorums: Vec<Value>, | ||
| #[serde(rename = "deletedQuorums", default)] | ||
| deleted_quorums: Vec<Value>, | ||
| #[serde(default)] | ||
| quorums: Vec<Value>, | ||
| } | ||
|
|
||
| impl MasternodeListDiff { | ||
| fn quorum_diff_updates(&self) -> usize { | ||
| let nested: usize = self | ||
| .quorum_diffs | ||
| .iter() | ||
| .map(|entry| entry.quorum_updates()) | ||
| .sum(); | ||
|
|
||
| nested + self.new_quorums.len() + self.deleted_quorums.len() + self.quorums.len() | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Deserialize)] | ||
| struct QuorumDiffEntry { | ||
| #[serde(rename = "newQuorums", default)] | ||
| new_quorums: Vec<Value>, | ||
| #[serde(rename = "deletedQuorums", default)] | ||
| deleted_quorums: Vec<Value>, | ||
| #[serde(default)] | ||
| quorums: Vec<Value>, | ||
| } | ||
|
|
||
| impl QuorumDiffEntry { | ||
| fn quorum_updates(&self) -> usize { | ||
| self.new_quorums.len() + self.deleted_quorums.len() + self.quorums.len() | ||
| } | ||
| } |
65 changes: 65 additions & 0 deletions
65
packages/dapi-grpc/examples/dapi-cli/core/masternode_status.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| use clap::Args; | ||
| use dapi_grpc::core::v0::{ | ||
| core_client::CoreClient, get_masternode_status_response::Status as GrpcStatus, | ||
| GetMasternodeStatusRequest, | ||
| }; | ||
| use dapi_grpc::tonic::transport::Channel; | ||
|
|
||
| use crate::error::{CliError, CliResult}; | ||
|
|
||
| #[derive(Args, Debug)] | ||
| pub struct MasternodeStatusCommand {} | ||
|
|
||
| pub async fn run(url: &str, _cmd: MasternodeStatusCommand) -> CliResult<()> { | ||
| let channel = Channel::from_shared(url.to_string()) | ||
| .map_err(|source| CliError::InvalidUrl { | ||
| url: url.to_string(), | ||
| source: Box::new(source), | ||
| })? | ||
| .connect() | ||
| .await?; | ||
|
|
||
| let mut client = CoreClient::new(channel); | ||
|
|
||
| let response = client | ||
| .get_masternode_status(GetMasternodeStatusRequest {}) | ||
| .await? | ||
| .into_inner(); | ||
|
|
||
| let status = GrpcStatus::try_from(response.status).unwrap_or(GrpcStatus::Unknown); | ||
| let pro_tx_hash = if response.pro_tx_hash.is_empty() { | ||
| "<unset>".to_string() | ||
| } else { | ||
| hex::encode(response.pro_tx_hash) | ||
| }; | ||
|
|
||
| println!("Masternode status via {}", url); | ||
| println!("Status : {}", human_status(status)); | ||
| println!("ProTx Hash : {}", pro_tx_hash); | ||
| println!("PoSe Penalty : {}", response.pose_penalty); | ||
| println!("Core Synced : {}", yes_no(response.is_synced)); | ||
| println!("Sync Progress : {:.2}%", response.sync_progress * 100.0); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| fn human_status(status: GrpcStatus) -> &'static str { | ||
| match status { | ||
| GrpcStatus::Unknown => "Unknown", | ||
| GrpcStatus::WaitingForProtx => "Waiting for ProTx", | ||
| GrpcStatus::PoseBanned => "PoSe banned", | ||
| GrpcStatus::Removed => "Removed", | ||
| GrpcStatus::OperatorKeyChanged => "Operator key changed", | ||
| GrpcStatus::ProtxIpChanged => "ProTx IP changed", | ||
| GrpcStatus::Ready => "Ready", | ||
| GrpcStatus::Error => "Error", | ||
| } | ||
| } | ||
|
|
||
| fn yes_no(flag: bool) -> &'static str { | ||
| if flag { | ||
| "yes" | ||
| } else { | ||
| "no" | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
Fix enum conversion: use from_i32, not try_from
Prost enums expose from_i32; TryFrom isn’t implemented by default and will not compile.
🏁 Script executed:
Length of output: 48
-->
🏁 Script executed:
Length of output: 1716
Replace enum conversion: use from_i32, not try_from
Prost-generated enums provide
from_i32;TryFrom<i32>isn’t implemented by default and will not compile.📝 Committable suggestion
🤖 Prompt for AI Agents