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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
pub use crate::stake::*;
use crate::{constants::*, melvm::Covenant, preseal_melmint, CoinDataHeight, Denom};
use crate::{smtmapping::*, CoinData};
use crate::{transaction as txn, CoinID};
use applytx::StateHandle;
use defmac::defmac;
use num_enum::{IntoPrimitive, TryFromPrimitive};
use serde_repr::{Deserialize_repr, Serialize_repr};
use arbitrary::Arbitrary;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::{collections::BTreeMap, convert::TryInto};
use std::{collections::BTreeSet, io::Read};
use thiserror::Error;
use tmelcrypt::{Ed25519PK, HashVal};
use txn::Transaction;
use self::melswap::PoolMapping;
mod applytx;
pub(crate) mod melmint;
pub(crate) mod melswap;
#[derive(Error, Debug)]
pub enum StateError {
#[error("malformed transaction")]
MalformedTx,
#[error("attempted to spend non-existent coin {:?}", .0)]
NonexistentCoin(txn::CoinID),
#[error("unbalanced inputs and outputs")]
UnbalancedInOut,
#[error("insufficient fees (requires {0})")]
InsufficientFees(u128),
#[error("referenced non-existent script {:?}", .0)]
NonexistentScript(tmelcrypt::HashVal),
#[error("does not satisfy script {:?}", .0)]
ViolatesScript(tmelcrypt::HashVal),
#[error("invalid sequential proof of work")]
InvalidMelPoW,
#[error("auction bid at wrong time")]
BidWrongTime,
#[error("block has wrong header after applying to previous block")]
WrongHeader,
#[error("tried to spend locked coin")]
CoinLocked,
#[error("duplicate transaction")]
DuplicateTx,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct GenesisConfig {
pub network: NetID,
pub init_coindata: CoinData,
pub stakes: BTreeMap<HashVal, StakeDoc>,
pub init_fee_pool: u128,
}
impl GenesisConfig {
pub fn std_mainnet() -> Self {
Self {
network: NetID::Mainnet,
init_coindata: CoinData {
covhash: Covenant::std_ed25519_pk_legacy(Ed25519PK(
hex::decode("7323dcb65513b84470a76339cdf0062d47d82e205e834f2d7159684a0cb3b5ba")
.unwrap()
.try_into()
.unwrap(),
))
.hash(),
value: 1000000 * MICRO_CONVERTER,
denom: Denom::Sym,
additional_data: vec![],
},
stakes: ["7323dcb65513b84470a76339cdf0062d47d82e205e834f2d7159684a0cb3b5ba"]
.iter()
.map(|v| Ed25519PK(hex::decode(v).unwrap().try_into().unwrap()))
.map(|pubkey| {
(
tmelcrypt::hash_single(&pubkey.0),
StakeDoc {
pubkey,
e_start: 0,
e_post_end: 3,
syms_staked: 1,
},
)
})
.collect(),
init_fee_pool: 6553600 * MICRO_CONVERTER,
}
}
pub fn std_testnet() -> Self {
Self {
network: NetID::Testnet,
init_coindata: CoinData {
covhash: Covenant::always_true().hash(),
value: 1 << 32,
denom: Denom::Mel,
additional_data: vec![],
},
stakes: [
"fae1ff56a62639c7959bf200465f4e06291e4e4dbd751cf4d2c13a8a6bea537c",
"2ae54755b2e98a3059c68334af97b38603032be53bb2a1a3a183ae0f9d3bdaaf",
"3aa3b5e2d64916a055da79635a4406999b66dfbe25afb10fa306aa01e42308a6",
"85e374cc3e4dbf47b9a9697126e2e2ae90011b78a54b84adeb2ffe516b79769a",
]
.iter()
.map(|v| Ed25519PK(hex::decode(v).unwrap().try_into().unwrap()))
.map(|pubkey| {
(
tmelcrypt::hash_single(&pubkey.0),
StakeDoc {
pubkey,
e_start: 0,
e_post_end: 1 << 32,
syms_staked: 1,
},
)
})
.collect(),
init_fee_pool: 1 << 64,
}
}
}
#[derive(
Clone,
Copy,
IntoPrimitive,
TryFromPrimitive,
Eq,
PartialEq,
Debug,
Serialize_repr,
Deserialize_repr,
Hash,
Arbitrary,
)]
#[repr(u8)]
pub enum NetID {
Testnet = 0x01,
Mainnet = 0xff,
}
#[derive(Clone, Debug)]
pub struct State {
pub network: NetID,
pub height: u64,
pub history: SmtMapping<u64, Header>,
pub coins: SmtMapping<txn::CoinID, txn::CoinDataHeight>,
pub transactions: SmtMapping<HashVal, txn::Transaction>,
pub fee_pool: u128,
pub fee_multiplier: u128,
pub tips: u128,
pub dosc_speed: u128,
pub pools: PoolMapping,
pub stakes: SmtMapping<HashVal, StakeDoc>,
}
fn read_bts(r: &mut impl Read, n: usize) -> Option<Vec<u8>> {
let mut buf: Vec<u8> = vec![0; n];
r.read_exact(&mut buf).ok()?;
Some(buf)
}
impl State {
pub fn genesis(db: &novasmt::Forest, cfg: GenesisConfig) -> Self {
let empty_tree = db.open_tree(HashVal::default().0).unwrap();
let mut new_state = Self {
network: cfg.network,
height: 0,
history: SmtMapping::new(empty_tree.clone()),
coins: SmtMapping::new(empty_tree.clone()),
transactions: SmtMapping::new(empty_tree.clone()),
fee_pool: cfg.init_fee_pool,
fee_multiplier: MICRO_CONVERTER,
tips: 0,
dosc_speed: MICRO_CONVERTER,
pools: SmtMapping::new(empty_tree.clone()),
stakes: {
let mut stakes = SmtMapping::new(empty_tree);
for (k, v) in cfg.stakes.iter() {
stakes.insert(*k, *v);
}
dbg!(stakes.root_hash());
stakes
},
};
new_state.coins.insert(
CoinID::zero_zero(),
CoinDataHeight {
height: 0,
coin_data: cfg.init_coindata,
},
);
new_state
}
pub fn partial_encoding(&self) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(&[self.network.into()]);
out.extend_from_slice(&self.height.to_be_bytes());
out.extend_from_slice(&self.history.root_hash());
out.extend_from_slice(&self.coins.root_hash());
out.extend_from_slice(&self.transactions.root_hash());
out.extend_from_slice(&self.fee_pool.to_be_bytes());
out.extend_from_slice(&self.fee_multiplier.to_be_bytes());
out.extend_from_slice(&self.tips.to_be_bytes());
out.extend_from_slice(&self.dosc_speed.to_be_bytes());
out.extend_from_slice(&self.pools.root_hash());
out.extend_from_slice(&self.stakes.root_hash());
out
}
pub fn from_partial_encoding_infallible(mut encoding: &[u8], db: &novasmt::Forest) -> Self {
defmac!(readu8 => u8::from_be_bytes(read_bts(&mut encoding, 1).unwrap().as_slice().try_into().unwrap()));
defmac!(readu64 => u64::from_be_bytes(read_bts(&mut encoding, 8).unwrap().as_slice().try_into().unwrap()));
defmac!(readu128 => u128::from_be_bytes(read_bts(&mut encoding, 16).unwrap().as_slice().try_into().unwrap()));
defmac!(readtree => SmtMapping::new(db.open_tree(
read_bts(&mut encoding, 32).unwrap().as_slice().try_into().unwrap(),
).unwrap()));
let network: NetID = readu8!().try_into().unwrap();
let height = readu64!();
let history = readtree!();
let coins = readtree!();
let transactions = readtree!();
let fee_pool = readu128!();
let fee_multiplier = readu128!();
let tips = readu128!();
let dosc_multiplier = readu128!();
let pools = readtree!();
let stakes = readtree!();
State {
network,
height,
history,
coins,
transactions,
fee_pool,
fee_multiplier,
tips,
dosc_speed: dosc_multiplier,
pools,
stakes,
}
}
pub fn test_genesis(
db: novasmt::Forest,
start_micro_mels: u128,
start_cov_hash: tmelcrypt::HashVal,
start_stakeholders: &[tmelcrypt::Ed25519PK],
) -> Self {
assert!(start_micro_mels <= MAX_COINVAL);
let mut empty = Self::new_empty_testnet(db);
let init_coin = txn::CoinData {
covhash: start_cov_hash,
value: start_micro_mels,
denom: Denom::Mel,
additional_data: vec![],
};
empty.coins.insert(
txn::CoinID {
txhash: tmelcrypt::HashVal([0; 32]),
index: 0,
},
txn::CoinDataHeight {
coin_data: init_coin,
height: 0,
},
);
for (i, stakeholder) in start_stakeholders.iter().enumerate() {
empty.stakes.insert(
tmelcrypt::hash_single(&(i as u128).to_be_bytes()),
StakeDoc {
pubkey: *stakeholder,
e_start: 0,
e_post_end: 1000000000,
syms_staked: 100,
},
);
}
empty
}
pub fn apply_tx(&mut self, tx: &txn::Transaction) -> Result<(), StateError> {
self.apply_tx_batch(std::slice::from_ref(tx))
}
pub fn save_smts(&mut self) {
self.history.mapping.save();
self.coins.mapping.save();
self.pools.mapping.save();
self.transactions.mapping.save();
self.stakes.mapping.save();
}
pub fn apply_tx_batch(&mut self, txx: &[txn::Transaction]) -> Result<(), StateError> {
let old_hash = self.coins.root_hash();
StateHandle::new(self).apply_tx_batch(&txx)?.commit();
log::debug!(
"applied a batch of {} txx to {:?} => {:?}",
txx.len(),
old_hash,
self.coins.root_hash()
);
Ok(())
}
pub fn seal(mut self, action: Option<ProposerAction>) -> SealedState {
self = preseal_melmint(self);
assert!(self.pools.val_iter().count() >= 2);
let after_tip_901 = self.height >= 42700;
if let Some(action) = action {
let max_movement = if after_tip_901 {
((self.fee_multiplier >> 7) as i64).max(2)
} else {
(self.fee_multiplier >> 7) as i64
};
let scaled_movement = max_movement * action.fee_multiplier_delta as i64 / 128;
log::debug!(
"changing fee multiplier {} by {}",
self.fee_multiplier,
scaled_movement
);
if scaled_movement >= 0 {
self.fee_multiplier += scaled_movement as u128;
} else {
self.fee_multiplier -= scaled_movement.abs() as u128;
}
let base_fees = self.fee_pool >> 16;
self.fee_pool -= base_fees;
let tips = self.tips;
self.tips = 0;
let pseudocoin_id = CoinID::proposer_reward(self.height);
let pseudocoin_data = CoinDataHeight {
coin_data: CoinData {
covhash: action.reward_dest,
value: base_fees + tips,
denom: Denom::Mel,
additional_data: vec![],
},
height: self.height,
};
self.coins.insert(pseudocoin_id, pseudocoin_data);
}
SealedState(self, action)
}
pub(crate) fn new_empty_testnet(db: novasmt::Forest) -> Self {
let empty_tree = db.open_tree(Default::default()).unwrap();
State {
network: NetID::Testnet,
height: 0,
history: SmtMapping::new(empty_tree.clone()),
coins: SmtMapping::new(empty_tree.clone()),
transactions: SmtMapping::new(empty_tree.clone()),
fee_pool: 1000000,
fee_multiplier: 1000,
dosc_speed: 1,
tips: 0,
pools: SmtMapping::new(empty_tree.clone()),
stakes: SmtMapping::new(empty_tree),
}
}
}
#[derive(Clone, Debug)]
pub struct SealedState(State, Option<ProposerAction>);
impl SealedState {
pub(crate) fn force_new(state: State) -> Self {
Self(state, None)
}
pub fn inner_ref(&self) -> &State {
&self.0
}
pub fn save_smts(&mut self) {
self.0.save_smts()
}
pub fn is_empty(&self) -> bool {
self.1.is_none() && self.inner_ref().transactions.root_hash() == Default::default()
}
pub fn partial_encoding(&self) -> Vec<u8> {
let tmp = (self.0.partial_encoding(), &self.1);
stdcode::serialize(&tmp).unwrap()
}
pub fn from_partial_encoding_infallible(bts: &[u8], db: &novasmt::Forest) -> Self {
let tmp: (Vec<u8>, Option<ProposerAction>) = stdcode::deserialize(&bts).unwrap();
SealedState(State::from_partial_encoding_infallible(&tmp.0, db), tmp.1)
}
pub fn header(&self) -> Header {
let inner = &self.0;
Header {
network: inner.network,
previous: (inner.height.checked_sub(1))
.map(|height| inner.history.get(&height).0.unwrap().hash())
.unwrap_or_default(),
height: inner.height,
history_hash: inner.history.root_hash(),
coins_hash: inner.coins.root_hash(),
transactions_hash: inner.transactions.root_hash(),
fee_pool: inner.fee_pool,
fee_multiplier: inner.fee_multiplier,
dosc_speed: inner.dosc_speed,
pools_hash: inner.pools.root_hash(),
stakes_hash: inner.stakes.root_hash(),
}
}
pub fn proposer_action(&self) -> Option<&ProposerAction> {
self.1.as_ref()
}
pub fn to_block(&self) -> Block {
let mut txx = im::HashSet::new();
for tx in self.0.transactions.val_iter() {
txx.insert(tx);
}
for tx in self.0.transactions.val_iter() {
assert!(txx.contains(&tx));
}
Block {
header: self.header(),
transactions: txx,
proposer_action: self.1,
}
}
pub fn next_state(&self) -> State {
let mut new = self.inner_ref().clone();
new.history.insert(self.0.height, self.header());
new.height += 1;
new.stakes.remove_stale(new.height / STAKE_EPOCH);
new.transactions.clear();
new
}
pub fn apply_block(&self, block: &Block) -> Result<SealedState, StateError> {
let mut basis = self.next_state();
assert!(basis.pools.val_iter().count() >= 2);
let transactions = block.transactions.iter().cloned().collect::<Vec<_>>();
basis.apply_tx_batch(&transactions)?;
assert!(basis.pools.val_iter().count() >= 2);
let basis = basis.seal(block.proposer_action);
assert!(basis.inner_ref().pools.val_iter().count() >= 2);
if basis.header() != block.header {
log::warn!(
"post-apply header {:#?} doesn't match declared header {:#?} with {} txx",
basis.header(),
block.header,
transactions.len()
);
assert!(basis.inner_ref().pools.val_iter().count() >= 2);
for pool_info in basis.inner_ref().pools.val_iter() {
dbg!(pool_info);
}
return Err(StateError::WrongHeader);
}
Ok(basis)
}
pub fn confirm(
self,
cproof: ConsensusProof,
previous_state: Option<&State>,
) -> Option<ConfirmedState> {
Some(ConfirmedState {
state: self,
cproof,
})
}
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq)]
pub struct ProposerAction {
pub fee_multiplier_delta: i8,
pub reward_dest: HashVal,
}
pub type ConsensusProof = BTreeMap<Ed25519PK, Vec<u8>>;
#[derive(Clone, Debug)]
pub struct ConfirmedState {
state: SealedState,
cproof: ConsensusProof,
}
impl ConfirmedState {
pub fn inner(&self) -> &SealedState {
&self.state
}
pub fn cproof(&self) -> &ConsensusProof {
&self.cproof
}
}
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Eq, PartialEq, Hash, Arbitrary)]
pub struct Header {
pub network: NetID,
pub previous: HashVal,
pub height: u64,
pub history_hash: HashVal,
pub coins_hash: HashVal,
pub transactions_hash: HashVal,
pub fee_pool: u128,
pub fee_multiplier: u128,
pub dosc_speed: u128,
pub pools_hash: HashVal,
pub stakes_hash: HashVal,
}
impl Header {
pub fn hash(&self) -> tmelcrypt::HashVal {
tmelcrypt::hash_single(&stdcode::serialize(self).unwrap())
}
pub fn validate_cproof(
&self,
_cproof: &ConsensusProof,
previous_state: Option<&State>,
) -> bool {
if previous_state.is_none() && self.height != 0 {
return false;
}
true
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Block {
pub header: Header,
pub transactions: im::HashSet<Transaction>,
pub proposer_action: Option<ProposerAction>,
}
impl Block {
pub fn abbreviate(&self) -> AbbrBlock {
AbbrBlock {
header: self.header,
txhashes: self.transactions.iter().map(|v| v.hash_nosigs()).collect(),
proposer_action: self.proposer_action,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AbbrBlock {
pub header: Header,
pub txhashes: BTreeSet<HashVal>,
pub proposer_action: Option<ProposerAction>,
}
#[cfg(test)]
pub(crate) mod tests {
use crate::testing::fixtures::valid_txx;
use crate::Transaction;
use rstest::*;
#[rstest]
#[ignore]
fn test_apply_tx_batch_not_well_formed_errors() {
}
#[rstest]
#[ignore]
fn test_apply_tx_batch(valid_txx: Vec<Transaction>) {
}
}