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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
use derivative::Derivative;
use melnet::MelnetError;
use novasmt::{CompressedProof, Database, FullProof, InMemoryCas};
use serde::{de::DeserializeOwned, Serialize};
use std::{
collections::{BTreeMap, HashSet},
net::SocketAddr,
str::FromStr,
sync::Arc,
};
use themelio_stf::{PoolKey, SmtMapping, StakeMapping};
use themelio_structs::{
AbbrBlock, Address, Block, BlockHeight, CoinDataHeight, CoinID, ConsensusProof, Header, NetID,
PoolState, StakeDoc, Transaction, TxHash, STAKE_EPOCH,
};
use thiserror::Error;
use tmelcrypt::{HashVal, Hashable};
use crate::{cache::AsyncCache, InMemoryTrustStore, NodeRequest, StateSummary, Substate};
#[derive(Debug, Clone)]
pub struct TrustedHeight {
pub height: BlockHeight,
pub header_hash: HashVal,
}
#[derive(Error, Debug)]
pub enum ParseTrustedHeightError {
#[error("expected a ':' character to split the height and header hash")]
ParseSplitError,
#[error("height is not an integer")]
ParseIntError(#[from] std::num::ParseIntError),
#[error("failed to parse header hash as a hash")]
ParseHeaderHash(#[from] hex::FromHexError),
}
impl FromStr for TrustedHeight {
type Err = ParseTrustedHeightError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let (height_str, hash_str) = s
.split_once(':')
.ok_or(ParseTrustedHeightError::ParseSplitError)?;
let height = BlockHeight::from_str(height_str)?;
let header_hash = HashVal::from_str(hash_str)?;
Ok(Self {
height,
header_hash,
})
}
}
pub trait TrustStore {
fn set(&self, netid: NetID, trusted: TrustedHeight);
fn get(&self, netid: NetID) -> Option<TrustedHeight>;
}
#[derive(Clone, Derivative)]
#[derivative(Debug)]
pub struct ValClient<T = InMemoryTrustStore> {
netid: NetID,
raw: NodeClient,
trust_store: T,
#[derivative(Debug = "ignore")]
cache: Arc<AsyncCache>,
}
impl ValClient<InMemoryTrustStore> {
pub fn new(netid: NetID, remote: SocketAddr) -> Self {
Self::new_with_truststore(netid, remote, InMemoryTrustStore::new())
}
}
impl<T: TrustStore> ValClient<T> {
pub fn new_with_truststore(netid: NetID, remote: SocketAddr, trust_store: T) -> Self {
let raw = NodeClient::new(netid, remote);
Self {
netid,
raw,
trust_store,
cache: Arc::new(AsyncCache::new(10000)),
}
}
pub fn netid(&self) -> NetID {
self.netid
}
pub fn trust(&self, trusted: TrustedHeight) {
self.trust_store.set(self.netid, trusted);
}
#[deprecated]
pub async fn insecure_latest_snapshot(&self) -> melnet::Result<ValClientSnapshot> {
self.trust_latest().await?;
self.snapshot().await
}
async fn trust_latest(&self) -> melnet::Result<()> {
let summary = self.raw.get_summary().await?;
self.trust(TrustedHeight {
height: summary.height,
header_hash: summary.header.hash(),
});
Ok(())
}
pub async fn snapshot(&self) -> melnet::Result<ValClientSnapshot> {
let mut summary = self.raw.get_summary().await?;
if summary.height != summary.header.height {
return Err(MelnetError::Custom(
"self-contradictory summary".to_string(),
));
}
let (safe_height, safe_stakers) = self.get_trusted_stakers().await?;
if summary.height.epoch() > safe_height.epoch() + 1 {
return Err(MelnetError::Custom(format!(
"trusted height {} in epoch {} but remote height {} in epoch {}",
safe_height,
safe_height.epoch(),
summary.height,
summary.height.epoch()
)));
}
if summary.height.epoch() > safe_height.epoch()
&& safe_height.epoch() == (safe_height + BlockHeight(1)).epoch()
{
let epoch_ending_height = BlockHeight((safe_height.epoch() + 1) * STAKE_EPOCH - 1);
let (ending_abbr_block, ending_cproof) =
self.raw.get_abbr_block(epoch_ending_height).await?;
log::warn!(
"fast-forwarding proof from {} to {}",
safe_height,
epoch_ending_height
);
summary.height = epoch_ending_height;
summary.header = ending_abbr_block.header;
summary.proof = ending_cproof;
}
let mut total_votes = 0.0;
for doc in safe_stakers.val_iter() {
if let Some(sig) = summary.proof.get(&doc.pubkey) {
if doc.pubkey.verify(&summary.header.hash(), sig) {
total_votes += safe_stakers.vote_power(summary.height.epoch(), doc.pubkey);
}
}
}
if total_votes < 0.7 {
return Err(MelnetError::Custom(format!(
"remote height {} has insufficient votes (total_votes = {}, stakers = {:?})",
summary.height,
total_votes,
safe_stakers.val_iter().collect::<Vec<_>>()
)));
}
self.trust(TrustedHeight {
height: summary.height,
header_hash: summary.header.hash(),
});
Ok(ValClientSnapshot {
height: summary.height,
header: summary.header,
raw: self.raw.clone(),
cache: self.cache.clone(),
})
}
async fn get_trusted_stakers(
&self,
) -> melnet::Result<(BlockHeight, StakeMapping<InMemoryCas>)> {
let checkpoint = self.trust_store.get(self.netid).ok_or_else(|| {
MelnetError::Custom(
"Expected to find a trusted block when fetching trusted stakers".into(),
)
})?;
let temp_forest = Database::new(InMemoryCas::default());
let stakers = self.raw.get_stakers_raw(checkpoint.height).await?;
let (abbr_block, _) = self.raw.get_abbr_block(checkpoint.height).await?;
if abbr_block.header.hash() != checkpoint.header_hash {
return Err(MelnetError::Custom(format!(
"remote block contradicted trusted block hash: trusted {}, yet got {}:{}:{}",
checkpoint.header_hash,
checkpoint.height,
abbr_block.header.hash(),
abbr_block.header.height
)));
}
let trusted_stake_hash = abbr_block.header.stakes_hash;
let mut mapping = temp_forest.get_tree(Default::default()).unwrap();
for (k, v) in stakers {
mapping.insert(k.0, &v);
}
if mapping.root_hash() != trusted_stake_hash.0 {
return Err(MelnetError::Custom(
"remote staker set contradicted valid header".into(),
));
}
Ok((checkpoint.height, SmtMapping::new(mapping)))
}
}
#[derive(Clone)]
pub struct ValClientSnapshot {
height: BlockHeight,
header: Header,
raw: NodeClient,
cache: Arc<AsyncCache>,
}
impl ValClientSnapshot {
pub fn get_raw(&self) -> &NodeClient {
&self.raw
}
pub async fn get_older(&self, old_height: BlockHeight) -> melnet::Result<Self> {
if old_height > self.height {
return Err(MelnetError::Custom("cannot travel into the future".into()));
}
if old_height == self.height {
return Ok(self.clone());
}
let old_elem: Header = self
.cache
.get_or_try_fill(("header", old_height), async {
let val = self
.get_smt_value(
Substate::History,
tmelcrypt::hash_single(&stdcode::serialize(&old_height).unwrap()),
)
.await?;
let old_elem: Header = stdcode::deserialize(&val).map_err(|e| {
MelnetError::Custom(format!("could not deserialize old header: {}", e))
})?;
Ok::<_, melnet::MelnetError>(old_elem)
})
.await?;
assert_eq!(old_elem.height, old_height);
Ok(Self {
height: old_height,
header: old_elem,
raw: self.raw.clone(),
cache: self.cache.clone(),
})
}
pub fn current_header(&self) -> Header {
self.header
}
pub async fn current_block(&self) -> melnet::Result<Block> {
self.cache
.get_or_try_fill(("block", self.height), async {
let header = self.current_header();
let (block, _) = get_full_block(self.raw.clone(), self.height).await?;
if block.header != header {
return Err(MelnetError::Custom("block header does not match".into()));
}
Ok(block)
})
.await
}
pub async fn current_block_with_known(
&self,
get_known_tx: impl Fn(TxHash) -> Option<Transaction>,
) -> melnet::Result<Block> {
let header = self.current_header();
let (block, _) = self.raw.get_full_block(header.height, get_known_tx).await?;
if block.header != header {
return Err(MelnetError::Custom("block header does not match".into()));
}
Ok(block)
}
pub async fn get_history(&self, height: BlockHeight) -> melnet::Result<Option<Header>> {
self.get_smt_value_serde(Substate::History, height).await
}
pub async fn get_coin(&self, coinid: CoinID) -> melnet::Result<Option<CoinDataHeight>> {
self.get_smt_value_serde(Substate::Coins, coinid).await
}
pub async fn get_coin_count(&self, covhash: Address) -> melnet::Result<Option<u64>> {
let val = self
.get_smt_value(Substate::Coins, covhash.0.hash_keyed(b"coin_count"))
.await?;
if val.is_empty() {
Ok(None)
} else {
Ok(Some(stdcode::deserialize(&val).map_err(|e| {
MelnetError::Custom(format!("bad coin count {:?} {:?}", val, e.to_string()))
})?))
}
}
pub async fn get_coins(
&self,
covhash: Address,
) -> melnet::Result<Option<BTreeMap<CoinID, CoinDataHeight>>> {
self.cache
.get_or_try_fill(("coins", self.height, covhash), async {
let coins = self.raw.get_some_coins(self.height, covhash).await?;
if let Some(coins) = coins {
let coins: HashSet<CoinID> = coins.into_iter().collect();
let count = self.get_coin_count(covhash).await?;
if let Some(count) = count {
if count != coins.len() as u64 {
return Err(MelnetError::Custom(format!(
"got incomplete list of {} coins rather than {}",
coins.len(),
count
)));
}
}
let mut coin_futs = BTreeMap::new();
for coin in coins {
let this = self.clone();
let fut_data = smolscale::spawn(async move {
let r = this
.get_coin(coin)
.await?
.expect("invalid data received while getting coin list");
Ok::<_, melnet::MelnetError>(r)
});
coin_futs.insert(coin, fut_data);
}
let mut toret = BTreeMap::new();
for (i, (k, v)) in coin_futs.into_iter().enumerate() {
let v = v.await?;
log::debug!("loading coin {}", i);
toret.insert(k, v);
}
Ok(Some(toret))
} else {
Ok(None)
}
})
.await
}
pub async fn get_coin_spent_here(
&self,
coinid: CoinID,
) -> melnet::Result<Option<CoinDataHeight>> {
if let Some(tx) = self.get_transaction(coinid.txhash).await? {
return Ok(tx
.outputs
.get(coinid.index as usize)
.map(|v| CoinDataHeight {
coin_data: v.clone(),
height: self.height,
}));
}
self.get_older(self.height.0.saturating_sub(1).into())
.await?
.get_coin(coinid)
.await
}
pub async fn get_pool(&self, denom: PoolKey) -> melnet::Result<Option<PoolState>> {
self.get_smt_value_serde(Substate::Pools, denom).await
}
pub async fn get_stake(&self, staking_txhash: HashVal) -> melnet::Result<Option<StakeDoc>> {
self.get_smt_value_serde(Substate::Stakes, staking_txhash)
.await
}
pub async fn get_transaction(&self, txhash: TxHash) -> melnet::Result<Option<Transaction>> {
self.get_smt_value_serde(Substate::Transactions, txhash)
.await
}
async fn get_smt_value_serde<S: Serialize, D: DeserializeOwned + Serialize>(
&self,
substate: Substate,
key: S,
) -> melnet::Result<Option<D>> {
let val = self
.get_smt_value(
substate,
tmelcrypt::hash_single(&stdcode::serialize(&key).unwrap()),
)
.await?;
if val.is_empty() {
return Ok(None);
}
let val = stdcode::deserialize(&val)
.map_err(|_| MelnetError::Custom("fatal deserialization error".into()))?;
Ok(Some(val))
}
pub async fn get_smt_value(&self, substate: Substate, key: HashVal) -> melnet::Result<Vec<u8>> {
let verify_against = match substate {
Substate::Coins => self.header.coins_hash,
Substate::History => self.header.history_hash,
Substate::Pools => self.header.pools_hash,
Substate::Stakes => self.header.stakes_hash,
Substate::Transactions => self.header.transactions_hash,
};
self.cache.get_or_try_fill((verify_against, key), async {
let (val, branch) = self.raw.get_smt_branch(self.height, substate, key).await?;
if !branch.verify(verify_against.0, key.0, &val) {
return Err(MelnetError::Custom(format!(
"unable to verify merkle proof for height {:?}, substate {:?}, key {:?}, value {:?}, branch {:?}",
self.height, substate, key, val, branch
)));
}
Ok(val)
}).await
}
}
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct NodeClient {
remote: SocketAddr,
netname: String,
}
impl NodeClient {
pub fn new(netid: NetID, remote: SocketAddr) -> Self {
let netname = match netid {
NetID::Mainnet => "mainnet-node".to_string(),
NetID::Testnet => "testnet-node".to_string(),
_ => format!("{:?}", netid),
};
Self { remote, netname }
}
async fn request(&self, req: NodeRequest) -> melnet::Result<Vec<u8>> {
let res: Vec<u8> = melnet::request(self.remote, &self.netname, "node", req).await?;
Ok(res)
}
pub async fn send_tx(&self, tx: Transaction) -> melnet::Result<()> {
self.request(NodeRequest::SendTx(tx)).await?;
Ok(())
}
pub async fn get_summary(&self) -> melnet::Result<StateSummary> {
get_summary(self.clone()).await
}
pub async fn get_abbr_block(
&self,
height: BlockHeight,
) -> melnet::Result<(AbbrBlock, ConsensusProof)> {
get_abbr_block(self.clone(), height).await
}
pub async fn get_full_block(
&self,
height: BlockHeight,
get_known_tx: impl Fn(TxHash) -> Option<Transaction>,
) -> melnet::Result<(Block, ConsensusProof)> {
let (abbr, cproof) = self.get_abbr_block(height).await?;
let mut known = vec![];
let mut unknown = vec![];
for txhash in abbr.txhashes.iter() {
if let Some(tx) = get_known_tx(*txhash) {
known.push(tx);
} else {
unknown.push(*txhash);
}
}
let mut response: Block = if unknown.is_empty() {
Block {
header: abbr.header,
transactions: HashSet::new(),
proposer_action: abbr.proposer_action,
}
} else {
let req = NodeRequest::GetPartialBlock(height, unknown);
stdcode::deserialize(&self.request(req).await?)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))?
};
for known in known {
response.transactions.insert(known);
}
let new_abbr = response.abbreviate();
if new_abbr.header != abbr.header || new_abbr.txhashes != abbr.txhashes {
return Err(melnet::MelnetError::Custom(
"mismatched abbreviation".into(),
));
}
Ok((response, cproof))
}
pub async fn get_smt_branch(
&self,
height: BlockHeight,
elem: Substate,
key: HashVal,
) -> melnet::Result<(Vec<u8>, FullProof)> {
get_smt_branch(self.clone(), height, elem, key).await
}
pub async fn get_stakers_raw(
&self,
height: BlockHeight,
) -> melnet::Result<BTreeMap<HashVal, Vec<u8>>> {
get_stakers_raw(self.clone(), height).await
}
pub async fn get_some_coins(
&self,
height: BlockHeight,
owner: Address,
) -> melnet::Result<Option<Vec<CoinID>>> {
stdcode::deserialize(
&self
.request(NodeRequest::GetSomeCoins(height, owner))
.await?,
)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))
}
}
async fn get_stakers_raw(
this: NodeClient,
height: BlockHeight,
) -> melnet::Result<BTreeMap<HashVal, Vec<u8>>> {
stdcode::deserialize(&this.request(NodeRequest::GetStakersRaw(height)).await?)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))
}
async fn get_abbr_block(
this: NodeClient,
height: BlockHeight,
) -> melnet::Result<(AbbrBlock, ConsensusProof)> {
stdcode::deserialize(&this.request(NodeRequest::GetAbbrBlock(height)).await?)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))
}
async fn get_summary(this: NodeClient) -> melnet::Result<StateSummary> {
stdcode::deserialize(&this.request(NodeRequest::GetSummary).await?)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))
}
async fn get_smt_branch(
this: NodeClient,
height: BlockHeight,
elem: Substate,
keyhash: HashVal,
) -> melnet::Result<(Vec<u8>, FullProof)> {
let tuple: (Vec<u8>, CompressedProof) = stdcode::deserialize(
&this
.request(NodeRequest::GetSmtBranch(height, elem, keyhash))
.await?,
)
.map_err(|e| melnet::MelnetError::Custom(e.to_string()))?;
let decompressed = tuple
.1
.decompress()
.ok_or_else(|| melnet::MelnetError::Custom("could not decompress proof".into()))?;
Ok((tuple.0, decompressed))
}
async fn get_full_block(
this: NodeClient,
height: BlockHeight,
) -> melnet::Result<(Block, ConsensusProof)> {
this.get_full_block(height, |_| None).await
}