1use std::fmt;
16use std::future::IntoFuture;
17
18use heika_block::Block;
19use heika_core::address::Address;
20use heika_core::hash::Hash256;
21use heika_core::patricia::{self, SubCache};
22use serde::Deserialize;
23use serde::de::DeserializeOwned;
24
25use crate::RestError;
26use crate::block::BlockInfo;
27use crate::merkle::MerkleStateInfo;
28use crate::state::{AccountInfo, AccountJson, MosaicInfo, id};
29
30const ATTEMPTS: usize = 5;
32
33#[derive(Clone, Debug)]
35pub struct VerifiedBalance {
36 pub address: Address,
37 pub block: Block,
39 pub account: Option<VerifiedAccount>,
41}
42
43#[derive(Clone, Debug)]
45pub struct VerifiedAccount {
46 pub state: AccountJson,
48 pub mosaics: Vec<VerifiedMosaic>,
50}
51
52#[derive(Clone, Copy, PartialEq, Eq, Debug)]
54pub struct VerifiedMosaic {
55 pub id: u64,
56 pub amount: u64,
58 pub divisibility: Option<u8>,
60}
61
62impl VerifiedMosaic {
63 pub fn decimal(&self) -> Option<String> {
65 let divisibility = usize::from(self.divisibility?);
66 if divisibility == 0 {
67 return Some(self.amount.to_string());
68 }
69 let digits = format!("{:0>width$}", self.amount, width = divisibility + 1);
70 let (whole, fraction) = digits.split_at(digits.len() - divisibility);
71 Some(format!("{whole}.{fraction}"))
72 }
73}
74
75#[derive(Clone, Debug)]
77pub struct MosaicParts {
78 pub id: u64,
79 pub info: Option<MosaicInfo>,
81 pub proof: MerkleStateInfo,
83}
84
85#[derive(Clone, PartialEq, Eq, Debug)]
87pub enum VerifyError {
88 WrongNetwork,
90 NoStateHash,
92 MissingMosaic(u64),
94 Invalid { what: String, error: Mismatch },
96}
97
98#[derive(Clone, PartialEq, Eq, Debug)]
100pub enum Mismatch {
101 Rest(RestError),
103 StateHash,
105 UnexpectedAbsence,
107 UnexpectedPresence,
109 WrongEntity,
111}
112
113#[derive(Debug)]
115pub enum BalanceError<E> {
116 Fetch(E),
118 NotFound { path: String },
120 Json { path: String, error: String },
122 Verify(VerifyError),
124}
125
126impl fmt::Display for Mismatch {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 match self {
129 Self::Rest(error) => error.fmt(f),
130 Self::StateHash => f.write_str("状態のハッシュが、状態の経路の葉と合いません"),
131 Self::UnexpectedAbsence => {
132 f.write_str("REST は状態を返しましたが、状態の経路はないことを示しています")
133 }
134 Self::UnexpectedPresence => {
135 f.write_str("REST は状態を返しませんでしたが、状態の経路はあることを示しています")
136 }
137 Self::WrongEntity => f.write_str("問い合わせたものと違うものが返ってきました"),
138 }
139 }
140}
141
142impl fmt::Display for VerifyError {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 match self {
145 Self::WrongNetwork => {
146 f.write_str("アドレスのネットワークが、REST のネットワークと違います")
147 }
148 Self::NoStateHash => f.write_str(
149 "この REST のノードは状態のハッシュを使っていないので、状態を確かめられません",
150 ),
151 Self::MissingMosaic(id) => write!(f, "モザイク {id:016X} の定義がありません"),
152 Self::Invalid { what, error } => write!(f, "{what}を確かめられません: {error}"),
153 }
154 }
155}
156
157impl std::error::Error for VerifyError {}
158
159impl<E: fmt::Display> fmt::Display for BalanceError<E> {
160 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161 match self {
162 Self::Fetch(error) => error.fmt(f),
163 Self::NotFound { path } => write!(f, "REST に {path} がありません"),
164 Self::Json { path, error } => write!(f, "{path} を読めません: {error}"),
165 Self::Verify(error) => error.fmt(f),
166 }
167 }
168}
169
170impl<E: fmt::Debug + fmt::Display> std::error::Error for BalanceError<E> {}
171
172pub fn account_paths(address: &Address) -> [String; 2] {
174 let path = format!("/accounts/{address}");
175 let merkle = format!("{path}/merkle");
176 [path, merkle]
177}
178
179pub fn mosaic_paths(id: u64) -> [String; 2] {
181 let path = format!("/mosaics/{id:016X}");
182 let merkle = format!("{path}/merkle");
183 [path, merkle]
184}
185
186pub fn mosaic_ids(account: &AccountInfo) -> Result<Vec<u64>, RestError> {
188 account
189 .account
190 .mosaics
191 .iter()
192 .map(|balance| id(&balance.id, "mosaics.id"))
193 .collect()
194}
195
196pub fn verify_balance_parts(
202 address: &Address,
203 block: &BlockInfo,
204 account: Option<&AccountInfo>,
205 account_proof: &MerkleStateInfo,
206 mosaics: &[MosaicParts],
207) -> Result<VerifiedBalance, VerifyError> {
208 let verified_block = block.verify().map_err(|error| invalid("ブロック", error))?;
209 if verified_block.network != address.network() {
210 return Err(VerifyError::WrongNetwork);
211 }
212 let roots = block
213 .sub_cache_merkle_roots()
214 .map_err(|error| invalid("ブロック", error))?;
215 if roots.is_empty() {
216 return Err(VerifyError::NoStateHash);
217 }
218
219 let key = patricia::address_key(address);
220 let leaf = prove(
221 "アカウント",
222 account_proof,
223 &key,
224 &roots[SubCache::AccountState.index()],
225 )?;
226 let account = match (account, leaf) {
227 (None, None) => None,
228 (None, Some(_)) => return Err(mismatch("アカウント", Mismatch::UnexpectedPresence)),
229 (Some(_), None) => return Err(mismatch("アカウント", Mismatch::UnexpectedAbsence)),
230 (Some(info), Some(leaf)) => {
231 let state = &info.account;
232 let rest = |error| invalid("アカウント", error);
233 if state.tree_key().map_err(rest)? != key {
234 return Err(mismatch("アカウント", Mismatch::WrongEntity));
235 }
236 if state.state_hash().map_err(rest)? != leaf {
237 return Err(mismatch("アカウント", Mismatch::StateHash));
238 }
239 let mut verified = Vec::with_capacity(state.mosaics.len());
240 for (mosaic_id, balance) in mosaic_ids(info)
241 .map_err(rest)?
242 .into_iter()
243 .zip(&state.mosaics)
244 {
245 let parts = mosaics
246 .iter()
247 .find(|parts| parts.id == mosaic_id)
248 .ok_or(VerifyError::MissingMosaic(mosaic_id))?;
249 verified.push(VerifiedMosaic {
250 id: mosaic_id,
251 amount: crate::number(&balance.amount, "mosaics.amount").map_err(rest)?,
252 divisibility: verify_divisibility(parts, &roots)?,
253 });
254 }
255 Some(VerifiedAccount {
256 state: state.clone(),
257 mosaics: verified,
258 })
259 }
260 };
261 Ok(VerifiedBalance {
262 address: *address,
263 block: verified_block,
264 account,
265 })
266}
267
268fn verify_divisibility(parts: &MosaicParts, roots: &[Hash256]) -> Result<Option<u8>, VerifyError> {
270 let what = format!("モザイク {:016X} ", parts.id);
271 let key = patricia::id_key(parts.id);
272 let leaf = prove(&what, &parts.proof, &key, &roots[SubCache::Mosaic.index()])?;
273 match (&parts.info, leaf) {
274 (None, None) => Ok(None),
275 (None, Some(_)) => Err(mismatch(&what, Mismatch::UnexpectedPresence)),
276 (Some(_), None) => Err(mismatch(&what, Mismatch::UnexpectedAbsence)),
277 (Some(info), Some(leaf)) => {
278 let state = &info.mosaic;
279 if state.tree_key().map_err(|error| invalid(&what, error))? != key {
280 return Err(mismatch(&what, Mismatch::WrongEntity));
281 }
282 if state.state_hash().map_err(|error| invalid(&what, error))? != leaf {
283 return Err(mismatch(&what, Mismatch::StateHash));
284 }
285 Ok(Some(state.divisibility))
286 }
287 }
288}
289
290pub async fn verify_balance<F, R, P, S, E>(
301 address: &Address,
302 mut fetch: F,
303 mut pause: P,
304) -> Result<VerifiedBalance, BalanceError<E>>
305where
306 F: FnMut(String) -> R,
307 R: IntoFuture<Output = Result<Option<Vec<u8>>, E>>,
308 P: FnMut() -> S,
309 S: IntoFuture<Output = ()>,
310{
311 let mut attempt = 0;
312 loop {
313 attempt += 1;
314 match attempt_once(address, &mut fetch).await {
315 Err(BalanceError::Verify(VerifyError::Invalid { .. })) if attempt < ATTEMPTS => {
316 pause().await;
317 }
318 result => return result,
319 }
320 }
321}
322
323async fn attempt_once<F, R, E>(
324 address: &Address,
325 fetch: &mut F,
326) -> Result<VerifiedBalance, BalanceError<E>>
327where
328 F: FnMut(String) -> R,
329 R: IntoFuture<Output = Result<Option<Vec<u8>>, E>>,
330{
331 #[derive(Deserialize)]
332 struct ChainInfo {
333 height: String,
334 }
335 let chain: ChainInfo = required(fetch, "/chain/info".to_owned()).await?;
336 let block: BlockInfo = required(fetch, format!("/blocks/{}", chain.height)).await?;
337 if block.block.network != address.network().0 {
339 return Err(BalanceError::Verify(VerifyError::WrongNetwork));
340 }
341 let [account_path, account_merkle] = account_paths(address);
342 let account: Option<AccountInfo> = optional(fetch, account_path).await?;
343 let account_proof: MerkleStateInfo = required(fetch, account_merkle).await?;
344
345 let ids = match &account {
346 Some(info) => {
347 mosaic_ids(info).map_err(|error| BalanceError::Verify(invalid("アカウント", error)))?
348 }
349 None => Vec::new(),
350 };
351 let mut mosaics = Vec::with_capacity(ids.len());
352 for id in ids {
353 let [path, merkle] = mosaic_paths(id);
354 mosaics.push(MosaicParts {
355 id,
356 info: optional(fetch, path).await?,
357 proof: required(fetch, merkle).await?,
358 });
359 }
360 verify_balance_parts(address, &block, account.as_ref(), &account_proof, &mosaics)
361 .map_err(BalanceError::Verify)
362}
363
364fn prove(
365 what: &str,
366 proof: &MerkleStateInfo,
367 key: &Hash256,
368 root: &Hash256,
369) -> Result<Option<Hash256>, VerifyError> {
370 proof.prove(key, root).map_err(|error| invalid(what, error))
371}
372
373fn invalid(what: &str, error: RestError) -> VerifyError {
374 mismatch(what, Mismatch::Rest(error))
375}
376
377fn mismatch(what: &str, error: Mismatch) -> VerifyError {
378 VerifyError::Invalid {
379 what: what.to_owned(),
380 error,
381 }
382}
383
384pub(crate) async fn optional<T, F, R, E>(
385 fetch: &mut F,
386 path: String,
387) -> Result<Option<T>, BalanceError<E>>
388where
389 T: DeserializeOwned,
390 F: FnMut(String) -> R,
391 R: IntoFuture<Output = Result<Option<Vec<u8>>, E>>,
392{
393 let Some(body) = fetch(path.clone()).await.map_err(BalanceError::Fetch)? else {
394 return Ok(None);
395 };
396 serde_json::from_slice(&body)
397 .map(Some)
398 .map_err(|error| BalanceError::Json {
399 path,
400 error: error.to_string(),
401 })
402}
403
404pub(crate) async fn required<T, F, R, E>(fetch: &mut F, path: String) -> Result<T, BalanceError<E>>
405where
406 T: DeserializeOwned,
407 F: FnMut(String) -> R,
408 R: IntoFuture<Output = Result<Option<Vec<u8>>, E>>,
409{
410 match optional(fetch, path.clone()).await? {
411 Some(value) => Ok(value),
412 None => Err(BalanceError::NotFound { path }),
413 }
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 fn mosaic(amount: u64, divisibility: Option<u8>) -> VerifiedMosaic {
421 VerifiedMosaic {
422 id: 1,
423 amount,
424 divisibility,
425 }
426 }
427
428 #[test]
429 fn splits_amounts_by_divisibility() {
430 let decimal = |amount, divisibility| mosaic(amount, divisibility).decimal();
431 assert_eq!(decimal(1_234_567_890, Some(6)).unwrap(), "1234.567890");
432 assert_eq!(decimal(5, Some(6)).unwrap(), "0.000005");
433 assert_eq!(decimal(0, Some(2)).unwrap(), "0.00");
434 assert_eq!(decimal(42, Some(0)).unwrap(), "42");
435 assert_eq!(decimal(u64::MAX, Some(255)).unwrap().len(), 2 + 255);
437 assert_eq!(decimal(7, None), None);
438 }
439}