1use std::fmt;
6use std::time::Duration;
7
8use heika_block::finalization::{FinalizationRound, FinalizedBlockHeader};
9use heika_packet::partial::{
10 COSIGNATURE_SIZE, PartialInfo, ShortHashPair, pull_partial_request, read_partial_infos,
11};
12use heika_packet::{
13 ChainStatistics, DecodeError, NetworkNode, NetworkTime, extension, packet_type,
14 pull_blocks_request, pull_transactions_request, split_size_prefixed,
15};
16use heika_tls::{ConnectError, Connection, Identity, RequestError};
17
18const MAX_BODY_SIZE: usize = 32 * 1024 * 1024;
21
22#[derive(Debug)]
24pub struct ClientConnection {
25 connection: Connection,
26}
27
28impl ClientConnection {
29 pub fn connect(
31 address: &str,
32 identity: &Identity,
33 timeout: Duration,
34 ) -> Result<Self, ConnectError> {
35 Connection::open(address, identity, timeout).map(|connection| Self { connection })
36 }
37
38 pub fn peer_certificates(&self) -> Vec<Vec<u8>> {
40 self.connection.peer_certificates()
41 }
42
43 pub fn is_heika(&self) -> bool {
45 self.connection.is_heika()
46 }
47
48 pub fn peer_capabilities(&self) -> Option<&[String]> {
51 self.connection.peer_capabilities()
52 }
53
54 pub fn chain_statistics(&mut self) -> Result<ChainStatistics, QueryError> {
56 let body = self.request(packet_type::CHAIN_STATISTICS, &[])?;
57 Ok(ChainStatistics::decode(&body)?)
58 }
59
60 pub fn info(&mut self) -> Result<NetworkNode, QueryError> {
62 let body = self.request(packet_type::NODE_DISCOVERY_PULL_PING, &[])?;
63 Ok(NetworkNode::decode(&body)?)
64 }
65
66 pub fn network_time(&mut self) -> Result<NetworkTime, QueryError> {
69 let body = self.request(packet_type::TIME_SYNC_NETWORK_TIME, &[])?;
70 Ok(NetworkTime::decode(&body)?)
71 }
72
73 pub fn peers(&mut self) -> Result<Vec<NetworkNode>, QueryError> {
75 let body = self.request(packet_type::NODE_DISCOVERY_PULL_PEERS, &[])?;
76 Ok(NetworkNode::decode_list(&body)?)
77 }
78
79 pub fn pull_blocks(
85 &mut self,
86 height: u64,
87 num_blocks: u32,
88 num_response_bytes: u32,
89 ) -> Result<Vec<Vec<u8>>, QueryError> {
90 let request = pull_blocks_request(height, num_blocks, num_response_bytes);
91 let body = self.request(packet_type::PULL_BLOCKS, &request)?;
92 Ok(split_size_prefixed(&body)?
94 .into_iter()
95 .map(<[u8]>::to_vec)
96 .collect())
97 }
98
99 pub fn pull_block_hashes(
104 &mut self,
105 height: u64,
106 num_hashes: u32,
107 ) -> Result<Vec<[u8; 32]>, QueryError> {
108 let mut request = Vec::with_capacity(12);
109 request.extend_from_slice(&height.to_le_bytes());
110 request.extend_from_slice(&num_hashes.to_le_bytes());
111 let body = self.request(packet_type::BLOCK_HASHES, &request)?;
112 if body.len() % 32 != 0 || body.len() / 32 > num_hashes as usize {
113 return Err(QueryError::Decode(DecodeError::BodySize {
114 expected: num_hashes as usize * 32,
115 actual: body.len(),
116 }));
117 }
118 Ok(body.as_chunks::<32>().0.to_vec())
119 }
120
121 pub fn pull_transactions(
127 &mut self,
128 min_deadline: u64,
129 min_fee_multiplier: u32,
130 known_short_hashes: &[u32],
131 ) -> Result<Vec<Vec<u8>>, QueryError> {
132 let request =
133 pull_transactions_request(min_deadline, min_fee_multiplier, known_short_hashes);
134 let body = self.request(packet_type::PULL_TRANSACTIONS, &request)?;
135 Ok(split_size_prefixed(&body)?
137 .into_iter()
138 .map(<[u8]>::to_vec)
139 .collect())
140 }
141
142 pub fn finalization_statistics(&mut self) -> Result<FinalizedBlockHeader, QueryError> {
144 let body = self.request(packet_type::FINALIZATION_STATISTICS, &[])?;
145 FinalizedBlockHeader::from_bytes(&body).map_err(|error| {
146 QueryError::Decode(DecodeError::BodySize {
147 expected: FinalizedBlockHeader::SIZE,
148 actual: error.0,
149 })
150 })
151 }
152
153 pub fn pull_finalization_messages(
157 &mut self,
158 min: FinalizationRound,
159 max: FinalizationRound,
160 known: &[u32],
161 ) -> Result<Vec<Vec<u8>>, QueryError> {
162 let mut request = Vec::with_capacity(16 + 4 * known.len());
164 for round in [min, max] {
165 request.extend_from_slice(&round.epoch.to_le_bytes());
166 request.extend_from_slice(&round.point.to_le_bytes());
167 }
168 for short_hash in known {
169 request.extend_from_slice(&short_hash.to_le_bytes());
170 }
171 let body = self.request(packet_type::PULL_FINALIZATION_MESSAGES, &request)?;
172 Ok(split_size_prefixed(&body)?
173 .into_iter()
174 .map(<[u8]>::to_vec)
175 .collect())
176 }
177
178 pub fn finalization_proof_at_epoch(
181 &mut self,
182 epoch: u32,
183 ) -> Result<Option<Vec<u8>>, QueryError> {
184 self.connection.send_packet(
186 packet_type::FINALIZATION_PROOF_AT_EPOCH,
187 &epoch.to_le_bytes(),
188 )?;
189 let (response_type, body) = self.connection.receive_packet(MAX_BODY_SIZE)?;
190 if response_type != packet_type::PULL_FINALIZATION_PROOF {
191 return Err(QueryError::Request(RequestError::UnexpectedType(
192 response_type,
193 )));
194 }
195 Ok((!body.is_empty()).then_some(body))
197 }
198
199 pub fn pull_partial_infos(
204 &mut self,
205 min_deadline: u64,
206 known: &[ShortHashPair],
207 ) -> Result<Vec<PulledPartial>, QueryError> {
208 let body = self.request(
209 packet_type::PULL_PARTIAL_TRANSACTION_INFOS,
210 &pull_partial_request(min_deadline, known),
211 )?;
212 Ok(read_partial_infos(&body)?
213 .into_iter()
214 .map(|info| PulledPartial {
215 transaction: match info.info {
216 PartialInfo::Transaction(bytes) => Ok(bytes.to_vec()),
217 PartialInfo::Hash(hash) => Err(hash),
218 },
219 cosignatures: info.cosignatures.into_iter().copied().collect(),
220 })
221 .collect())
222 }
223
224 pub fn push(&mut self, packet_type: u32, body: &[u8]) -> Result<(), QueryError> {
225 Ok(self.connection.send_packet(packet_type, body)?)
226 }
227
228 pub fn source_zip(&mut self) -> Result<Option<Vec<u8>>, QueryError> {
231 if !self.connection.is_heika() {
232 return Ok(None);
233 }
234 if self.connection.peer_capabilities().is_none() {
236 self.chain_statistics()?;
237 }
238 let offered = self
239 .connection
240 .peer_capabilities()
241 .is_some_and(|capabilities| {
242 capabilities
243 .iter()
244 .any(|capability| capability == extension::SOURCE_ZIP)
245 });
246 if !offered {
247 return Ok(None);
248 }
249 let body = self.request(
250 extension::ENVELOPE,
251 &extension::envelope_body(extension::SOURCE_ZIP, &[]),
252 )?;
253 match extension::read_envelope(&body)? {
254 (extension::SOURCE_ZIP, zip) => Ok(Some(zip.to_vec())),
255 _ => Err(DecodeError::InvalidValue("違う名前の封筒が返ってきました").into()),
256 }
257 }
258
259 fn request(&mut self, packet_type: u32, body: &[u8]) -> Result<Vec<u8>, QueryError> {
260 Ok(self.connection.request(packet_type, body, MAX_BODY_SIZE)?)
261 }
262}
263
264#[derive(Clone, Debug)]
267pub struct PulledPartial {
268 pub transaction: Result<Vec<u8>, heika_core::hash::Hash256>,
270 pub cosignatures: Vec<[u8; COSIGNATURE_SIZE]>,
272}
273
274#[derive(Debug)]
275pub enum QueryError {
276 Request(RequestError),
277 Decode(DecodeError),
278}
279
280impl From<RequestError> for QueryError {
281 fn from(error: RequestError) -> Self {
282 Self::Request(error)
283 }
284}
285
286impl From<DecodeError> for QueryError {
287 fn from(error: DecodeError) -> Self {
288 Self::Decode(error)
289 }
290}
291
292impl fmt::Display for QueryError {
293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
294 match self {
295 Self::Request(error) => error.fmt(f),
296 Self::Decode(error) => write!(f, "応答を読めませんでした: {error}"),
297 }
298 }
299}
300
301impl std::error::Error for QueryError {}