avalanche_types/subnet/rpc/snow/validators/
client.rs1use std::{
2 collections::BTreeMap,
3 io::{Error, ErrorKind, Result},
4};
5
6use bytes::Bytes;
7use tonic::transport::Channel;
8
9use super::*;
10use crate::{
11 ids,
12 proto::{
13 google::protobuf::Empty,
14 validatorstate::{validator_state_client, GetSubnetIdRequest, GetValidatorSetRequest},
15 },
16};
17
18#[derive(Clone, Debug)]
19pub struct ValidatorStateClient {
20 inner: validator_state_client::ValidatorStateClient<Channel>,
21}
22
23impl ValidatorStateClient {
24 pub fn new(client_conn: Channel) -> Self {
25 Self {
26 inner: validator_state_client::ValidatorStateClient::new(client_conn)
27 .max_decoding_message_size(usize::MAX)
28 .max_encoding_message_size(usize::MAX),
29 }
30 }
31}
32
33#[tonic::async_trait]
34impl super::State for ValidatorStateClient {
35 async fn get_minimum_height(&self) -> Result<u64> {
36 let mut client = self.inner.clone();
37 let resp = client
38 .get_minimum_height(Empty {})
39 .await
40 .map_err(|e| Error::new(ErrorKind::Other, format!("get_minimum_height failed: {e}")))?
41 .into_inner();
42
43 Ok(resp.height)
44 }
45
46 async fn get_current_height(&self) -> Result<u64> {
47 let mut client = self.inner.clone();
48 let resp = client
49 .get_current_height(Empty {})
50 .await
51 .map_err(|e| Error::new(ErrorKind::Other, format!("get_current_height failed: {e}")))?
52 .into_inner();
53
54 Ok(resp.height)
55 }
56
57 async fn get_subnet_id(&self, chain_id: crate::ids::Id) -> Result<ids::Id> {
58 let mut client = self.inner.clone();
59 let resp = client
60 .get_subnet_id(GetSubnetIdRequest {
61 chain_id: Bytes::from(chain_id.to_vec()),
62 })
63 .await
64 .map_err(|e| Error::new(ErrorKind::Other, format!("get_subnet_id failed: {e}")))?
65 .into_inner();
66
67 Ok(ids::Id::from_slice(&resp.subnet_id))
68 }
69
70 async fn get_validator_set(
71 &self,
72 height: u64,
73 subnet_id: crate::ids::Id,
74 ) -> std::io::Result<BTreeMap<ids::node::Id, GetValidatorOutput>> {
75 let mut client = self.inner.clone();
76 let resp = client
77 .get_validator_set(GetValidatorSetRequest {
78 height,
79 subnet_id: Bytes::from(subnet_id.to_vec()),
80 })
81 .await
82 .map_err(|e| Error::new(ErrorKind::Other, format!("get_validator_set failed: {e}")))?
83 .into_inner();
84
85 let mut validators: BTreeMap<ids::node::Id, GetValidatorOutput> = BTreeMap::new();
86
87 for validator in resp.validators.iter() {
88 let node_id = ids::node::Id::from_slice(&validator.node_id);
89
90 let public_key = if !validator.public_key.is_empty() {
91 Some(Key::from_bytes(&validator.public_key)?)
92 } else {
93 None
94 };
95 validators.insert(
96 node_id,
97 GetValidatorOutput {
98 node_id,
99 public_key,
100 weight: validator.weight,
101 },
102 );
103 }
104
105 Ok(validators)
106 }
107}