forked from witnet/witnet-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
7721 lines (6875 loc) · 274 KB
/
mod.rs
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
cell::{Cell, RefCell},
cmp::Ordering,
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
convert::{TryFrom, TryInto},
fmt,
fmt::Write as _,
ops::{AddAssign, SubAssign},
str::FromStr,
};
use bech32::{FromBase32, ToBase32};
use bls_signatures_rs::{bn256, bn256::Bn256, MultiSignature};
use ethereum_types::U256;
use failure::Fail;
use futures::future::BoxFuture;
use ordered_float::OrderedFloat;
use serde::{Deserialize, Serialize};
use partial_struct::PartialStruct;
use witnet_crypto::{
hash::{calculate_sha256, Sha256},
key::ExtendedSK,
merkle::merkle_tree_root as crypto_merkle_tree_root,
secp256k1::{
self,
ecdsa::{RecoverableSignature, RecoveryId, Signature as Secp256k1_Signature},
Message, PublicKey as Secp256k1_PublicKey, SecretKey as Secp256k1_SecretKey,
},
};
use witnet_protected::Protected;
use witnet_reputation::{ActiveReputationSet, TotalReputationSet};
use crate::{
chain::{
tapi::{ActiveWips, TapiEngine},
Signature::Secp256k1,
},
data_request::{calculate_reward_collateral_ratio, DataRequestPool},
error::{
DataRequestError, EpochCalculationError, OutputPointerParseError, Secp256k1ConversionError,
TransactionError,
},
get_environment, get_protocol_version, get_protocol_version_activation_epoch,
proto::{
versioning::{ProtocolInfo, ProtocolVersion, Versioned, VersionedHashable},
ProtobufConvert,
},
staking::prelude::*,
superblock::SuperBlockState,
transaction::{
CommitTransaction, DRTransaction, DRTransactionBody, Memoized, MintTransaction,
RevealTransaction, StakeTransaction, TallyTransaction, Transaction, TxInclusionProof,
UnstakeTransaction, VTTransaction,
},
transaction::{
MemoHash, MemoizedHashable, BETA, COMMIT_WEIGHT, OUTPUT_SIZE, REVEAL_WEIGHT, TALLY_WEIGHT,
},
utxo_pool::{OldUnspentOutputsPool, OwnUnspentOutputsPool, UnspentOutputsPool},
vrf::{BlockEligibilityClaim, DataRequestEligibilityClaim},
wit::{Wit, WIT_DECIMAL_PLACES},
};
/// Keeps track of priority being used by transactions included in recent blocks, and provides
/// methods for estimating sensible priority values for future transactions.
pub mod priority;
/// Contains all TAPI related structures and business logic
pub mod tapi;
/// Define how the different structures should be hashed.
pub trait Hashable {
/// Calculate the hash of `self`
fn hash(&self) -> Hash;
}
/// Data structure holding critical information about the chain state and protocol constants
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Default)]
pub struct ChainInfo {
/// Keeps track of protocol versions and their related data (e.g. activation epoch)
pub protocol: ProtocolInfo,
/// Blockchain valid environment
pub environment: Environment,
/// Blockchain Protocol constants
pub consensus_constants: ConsensusConstants,
/// Checkpoint of the last block in the blockchain
pub highest_block_checkpoint: CheckpointBeacon,
/// Checkpoint hash of the highest superblock in the blockchain
pub highest_superblock_checkpoint: CheckpointBeacon,
/// Checkpoint and VRF hash of the highest block in the blockchain
pub highest_vrf_output: CheckpointVRF,
}
/// State machine for the synchronization status of a Witnet node
#[derive(Copy, Clone, Default, Deserialize, Debug, Eq, PartialEq, Serialize)]
pub enum StateMachine {
/// First state, ChainManager is waiting for reaching consensus between its peers
#[default]
WaitingConsensus,
/// Second state, ChainManager synchronization process
Synchronizing,
/// Third state, `ChainManager` has all the blocks in the chain and is ready to start
/// consolidating block candidates in real time.
AlmostSynced,
/// Fourth state, `ChainManager` can consolidate block candidates, propose its own
/// candidates (mining) and participate in resolving data requests (witnessing).
Synced,
}
/// Node synchronization status
#[derive(Debug, Default, Deserialize, Serialize)]
pub struct SyncStatus {
/// The hash of the top consolidated block and the epoch of that block
pub chain_beacon: CheckpointBeacon,
/// The current epoch, or None if the epoch 0 is in the future
pub current_epoch: Option<u32>,
/// Node State
pub node_state: StateMachine,
}
/// Possible values for the "environment" configuration param.
// The variants are explicitly tagged so that bincode serialization does not break
#[derive(Serialize, Deserialize, Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum Environment {
/// "mainnet" environment
#[default]
#[serde(rename = "mainnet")]
Mainnet = 0,
/// "testnet" environment
#[serde(rename = "testnet")]
Testnet = 1,
/// "development" environment
#[serde(rename = "development")]
Development = 2,
}
impl fmt::Display for Environment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Environment::Development => "development",
Environment::Mainnet => "mainnet",
Environment::Testnet => "testnet",
};
f.write_str(s)
}
}
impl Environment {
/// Returns the Bech32 prefix used in this environment: "wit" in mainnet and "twit" elsewhere
pub fn bech32_prefix(&self) -> &str {
match self {
Environment::Mainnet => "wit",
_ => "twit",
}
}
/// Returns true if the consensus constants can be overriden in this environment.
/// This is only allowed in a development environment.
pub fn can_override_consensus_constants(self) -> bool {
matches!(self, Environment::Development)
}
}
/// Consensus-critical configuration
#[derive(
PartialStruct, Debug, Clone, PartialEq, Serialize, Deserialize, ProtobufConvert, Default,
)]
#[partial_struct(derive(Deserialize, Serialize, Default, Debug, Clone, PartialEq))]
#[protobuf_convert(pb = "crate::proto::schema::witnet::ConsensusConstants")]
pub struct ConsensusConstants {
/// Timestamp at checkpoint 0 (the start of epoch 0)
pub checkpoint_zero_timestamp: i64,
/// Seconds between the start of an epoch and the start of the next one
pub checkpoints_period: u16,
/// Auxiliary bootstrap block hash value
pub bootstrap_hash: Hash,
/// Genesis block hash value
pub genesis_hash: Hash,
/// Maximum weight a block can have, this affects the number of
/// transactions a block can contain: there will be as many
/// transactions as the sum of _their_ weights is less than, or
/// equal to, this maximum block weight parameter.
///
/// Maximum aggregated weight of all the value transfer transactions in one block
pub max_vt_weight: u32,
/// Maximum aggregated weight of all the data requests transactions in one block
pub max_dr_weight: u32,
/// An identity is considered active if it participated in the witnessing protocol at least once in the last `activity_period` epochs
pub activity_period: u32,
/// Reputation will expire after N witnessing acts
pub reputation_expire_alpha_diff: u32,
/// Reputation issuance
pub reputation_issuance: u32,
/// When to stop issuing new reputation
pub reputation_issuance_stop: u32,
/// Penalization factor: fraction of reputation lost by liars for out of consensus claims
// FIXME(#172): Use fixed point arithmetic
pub reputation_penalization_factor: f64,
/// Backup factor for mining: valid VRFs under this factor will result in broadcasting a block
pub mining_backup_factor: u32,
/// Replication factor for mining: valid VRFs under this factor will have priority
pub mining_replication_factor: u32,
/// Minimum value in nanowits for a collateral value
pub collateral_minimum: u64,
/// Minimum input age of an UTXO for being a valid collateral
pub collateral_age: u32,
/// Build a superblock every `superblock_period` epochs
pub superblock_period: u16,
/// Extra rounds for commitments and reveals
pub extra_rounds: u16,
/// Minimum difficulty
pub minimum_difficulty: u32,
/// Number of epochs with the minimum difficulty active
/// (This number represent the last epoch where the minimum difficulty is active)
pub epochs_with_minimum_difficulty: u32,
/// Superblock signing committee for the first superblocks
pub bootstrapping_committee: Vec<String>,
/// Size of the superblock signing committee
pub superblock_signing_committee_size: u32,
/// Period after which the committee size should decrease (in superblock periods)
pub superblock_committee_decreasing_period: u32,
/// Step by which the committee should be reduced after superblock_agreement_decreasing_period
pub superblock_committee_decreasing_step: u32,
/// Initial block reward
pub initial_block_reward: u64,
/// Halving period
pub halving_period: u32,
}
impl ConsensusConstants {
/// Return the "magic number" for this consensus constants.
/// The magic number is the first 16 bits of the hash of the consensus constants serialized
/// using `ProtocolBuffers`.
/// This magic number is used in the handshake protocol to prevent nodes with different
/// consensus constants from peering with each other.
pub fn get_magic(&self) -> u16 {
let magic = calculate_sha256(&self.to_pb_bytes().unwrap());
u16::from(magic.0[0]) << 8 | (u16::from(magic.0[1]))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, ProtobufConvert, Default)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::ConsensusConstantsWit2")]
pub struct ConsensusConstantsWit2 {
/// Timestamp at checkpoint 0 (the start of epoch 0)
pub checkpoint_zero_timestamp: i64,
/// Seconds between the start of an epoch and the start of the next one
pub checkpoints_period: u16,
}
impl ConsensusConstantsWit2 {
/// Timestamp when wit/2 activates
pub fn get_checkpoint_zero_timestamp_wit2(self) -> i64 {
self.checkpoint_zero_timestamp
+ i64::from(self.checkpoints_period)
* i64::from(get_protocol_version_activation_epoch(ProtocolVersion::V2_0))
}
/// Seconds between the start of an epoch and the start of the next one in wit/2
pub fn get_checkpoints_period_wit2(self) -> u16 {
20
}
/// Minimum amount of nanoWits which need to be staked before wit/2 activation
pub fn get_wit2_minimum_total_stake_nanowits(self) -> u64 {
match get_environment() {
Environment::Development | Environment::Testnet => 30_000_000_000_000_000,
_ => 300_000_000_000_000_000,
}
}
/// Number of epochs before wit/2 activates after enough Wit have been staked
pub fn get_wit2_activation_delay_epochs(self) -> u32 {
match get_environment() {
Environment::Development | Environment::Testnet => {
80 + 21 // One hour + one superepoch for final confirmation
}
_ => {
13_440 + 21 // 1 week + one superepoch for final confirmation
}
}
}
/// Replication factor for data request solving
pub fn get_replication_factor(self, epoch: Epoch, prev_epoch: Epoch) -> u16 {
if get_protocol_version(Some(epoch)) >= ProtocolVersion::V2_0 {
// linearly increasing replication factor
if epoch >= prev_epoch {
4u16.saturating_mul(2u16.saturating_pow(epoch - prev_epoch))
} else {
0
}
} else {
0
}
}
/// Maximum weight units that a block can devote to `StakeTransaction`s.
pub fn get_maximum_stake_block_weight(self, epoch: Epoch) -> u32 {
if get_protocol_version(Some(epoch)) > ProtocolVersion::V1_7 {
10_000_000
} else {
0
}
}
/// Maximum weight units that a block can devote to `UnstakeTransaction`s.
pub fn get_maximum_unstake_block_weight(self, epoch: Epoch) -> u32 {
if get_protocol_version(Some(epoch)) >= ProtocolVersion::V2_0 {
5_000
} else {
0
}
}
/// Unstake transactions are only spendable after below specified time lock expires
pub fn get_unstaking_delay_seconds(self, epoch: Epoch) -> u64 {
if get_protocol_version(Some(epoch)) >= ProtocolVersion::V2_0 {
match get_environment() {
Environment::Development | Environment::Testnet => {
3_600 // 1 hour
}
_ => {
1_209_600 // 2 weeks
}
}
} else {
0
}
}
/// Minimum amount of nanoWits that a `StakeTransaction` can add, and minimum amount that can be
/// left in stake by an `UnstakeTransaction`.
pub fn get_validator_min_stake_nanowits(self, epoch: Epoch) -> u64 {
if get_protocol_version(Some(epoch)) > ProtocolVersion::V1_7 {
10_000_000_000_000 // 10,000 Wit
} else {
0
}
}
/// Maximum amount of nanoWits that a `StakeTransaction` can add (and can be staked on a single validator).
pub fn get_validator_max_stake_nanowits(self, epoch: Epoch) -> u64 {
if get_protocol_version(Some(epoch)) > ProtocolVersion::V1_7 {
10_000_000_000_000_000
} else {
0
}
}
/// Validator reward for a proposed and accepted block
pub fn get_validator_block_reward(self, epoch: Epoch) -> u64 {
if get_protocol_version(Some(epoch)) >= ProtocolVersion::V2_0 {
50_000_000_000
} else {
0
}
}
/// Get the minimum age of a UTXO before it can be used for collateral (during V1.7 and V1.8)
pub fn get_collateral_age(self, active_wips: &ActiveWips) -> u32 {
if get_environment() == Environment::Mainnet {
if active_wips.wip0027() {
13440 // 1 week
} else {
1000 // ~ 12 hours, default from mainnet genesis
}
} else {
80 // 1 hour
}
}
}
#[derive(Debug, Fail)]
/// The various reasons creating a genesis block can fail
pub enum GenesisBlockInfoError {
/// Failed to read file
#[fail(display = "Failed to read file `{}`: {}", path, inner)]
Read {
/// Path of the `genesis_block.json` file
path: String,
/// Inner io error
inner: std::io::Error,
},
/// Failed to deserialize
#[fail(display = "Failed to deserialize `GenesisBlockInfo`: {}", _0)]
Deserialize(serde_json::Error),
/// The hash of the created genesis block does not match the hash set in the configuration
#[fail(
display = "Genesis block hash mismatch\nExpected: {}\nFound: {}",
expected, created
)]
HashMismatch {
/// Hash of the genesis block as created by reading the `genesis_block.json` file
created: Hash,
/// Hash of the genesis block specified in the configuration
expected: Hash,
},
}
/// Information needed to create the genesis block.
///
/// To prevent deserialization issues, the JSON file only contains string types: all integers
/// must be surrounded by quotes.
///
/// This is the format of `genesis_block.json`:
///
/// ```ignore
/// {
/// "alloc":[
/// [
/// {
/// "address": "twit1adgt8t2h3xnu358f76zxlph0urf2ev7cd78ggc",
/// "value": "500000000000",
/// "timelock": "0"
/// },
/// ]
/// ]
/// }
/// ```
///
/// The `alloc` field has two levels of arrays: the outer array is the list of transactions,
/// and the inner arrays are lists of `ValueTransferOutput` inside that transaction.
///
/// Note that in order to be valid:
/// * All transactions must have at least one output (but there can be 0 transactions)
/// * All the outputs must have some value (value cannot be 0)
/// * The sum of the value of all the outputs and the total block reward must be below 2^64
#[derive(Clone, Debug, Deserialize)]
#[serde(from = "crate::serialization_helpers::GenesisBlock")]
pub struct GenesisBlockInfo {
/// The outer array is the list of transactions
/// and the inner arrays are lists of `ValueTransferOutput` inside that transaction.
pub alloc: Vec<Vec<ValueTransferOutput>>,
}
impl GenesisBlockInfo {
/// Create a genesis block with the transactions from `self.alloc`.
pub fn build_genesis_block(self, bootstrap_hash: Hash) -> Block {
Block::genesis(
bootstrap_hash,
self.alloc.into_iter().map(VTTransaction::genesis).collect(),
)
}
/// Read `GenesisBlockInfo` from `genesis_block.json` file
pub fn from_path(
path: &str,
bootstrap_hash: Hash,
genesis_block_hash: Hash,
) -> Result<Self, GenesisBlockInfoError> {
let response = std::fs::read_to_string(path).map_err(|e| GenesisBlockInfoError::Read {
path: path.to_string(),
inner: e,
})?;
let genesis_block: GenesisBlockInfo =
serde_json::from_str(&response).map_err(GenesisBlockInfoError::Deserialize)?;
// TODO: the genesis block should only be created once
let built_genesis_block_hash = genesis_block
.clone()
.build_genesis_block(bootstrap_hash)
.versioned_hash(get_protocol_version(Some(0)));
if built_genesis_block_hash != genesis_block_hash {
Err(GenesisBlockInfoError::HashMismatch {
created: built_genesis_block_hash,
expected: genesis_block_hash,
})
} else {
Ok(genesis_block)
}
}
}
/// Checkpoint beacon structure
#[derive(
Copy, Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, ProtobufConvert,
)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::CheckpointBeacon")]
#[serde(rename_all = "camelCase")]
pub struct CheckpointBeacon {
/// The serial number for an epoch
pub checkpoint: Epoch,
/// The 256-bit hash of the previous block header
pub hash_prev_block: Hash,
}
/// Checkpoint VRF structure
#[derive(
Copy, Clone, Debug, Default, Eq, Hash, PartialEq, Serialize, Deserialize, ProtobufConvert,
)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::CheckpointVRF")]
#[serde(rename_all = "camelCase")]
pub struct CheckpointVRF {
/// The serial number for an epoch
pub checkpoint: Epoch,
/// The 256-bit hash of the VRF used in the previous block
pub hash_prev_vrf: Hash,
}
/// Epoch id (starting from 0)
pub type Epoch = u32;
/// Block data structure
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, ProtobufConvert, Default, Hash)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::Block")]
pub struct Block {
/// The header of the block
pub block_header: BlockHeader,
/// A miner-provided signature of the block header, for the sake of integrity
pub block_sig: KeyedSignature,
/// A non-empty list of signed transactions
pub txns: BlockTransactions,
#[protobuf_convert(skip)]
#[serde(skip)]
hash: MemoHash,
}
/// Block transactions
#[derive(Debug, Default, Eq, PartialEq, Clone, Serialize, Deserialize, ProtobufConvert, Hash)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::Block_BlockTransactions")]
pub struct BlockTransactions {
/// Mint transaction,
pub mint: MintTransaction,
/// A list of signed value transfer transactions
pub value_transfer_txns: Vec<VTTransaction>,
/// A list of signed data request transactions
pub data_request_txns: Vec<DRTransaction>,
/// A list of signed commit transactions
pub commit_txns: Vec<CommitTransaction>,
/// A list of signed reveal transactions
pub reveal_txns: Vec<RevealTransaction>,
/// A list of signed tally transactions
pub tally_txns: Vec<TallyTransaction>,
/// A list of signed stake transactions
#[serde(default)]
pub stake_txns: Vec<StakeTransaction>,
/// A list of signed unstake transactions
#[serde(default)]
pub unstake_txns: Vec<UnstakeTransaction>,
}
impl Block {
/// Simple factory for the `Block` data structure that automatically initiates the hash field
/// without actually performing the hash operation, just in case it is never used.
pub fn new(
block_header: BlockHeader,
block_sig: KeyedSignature,
txns: BlockTransactions,
) -> Self {
Self {
block_header,
block_sig,
txns,
hash: Default::default(),
}
}
/// Construct the genesis block.
/// This is a special block that is only valid for checkpoint 0, because it creates value.
pub fn genesis(bootstrap_hash: Hash, value_transfer_txns: Vec<VTTransaction>) -> Block {
let txns = BlockTransactions {
mint: MintTransaction::default(),
value_transfer_txns,
data_request_txns: vec![],
commit_txns: vec![],
reveal_txns: vec![],
tally_txns: vec![],
stake_txns: vec![],
unstake_txns: vec![],
};
/// Function to calculate a merkle tree from a transaction vector
pub fn merkle_tree_root<T>(transactions: &[T]) -> Hash
where
T: Hashable,
{
let transactions_hashes: Vec<Sha256> = transactions
.iter()
.map(|x| match x.hash() {
Hash::SHA256(x) => Sha256(x),
})
.collect();
Hash::from(crypto_merkle_tree_root(&transactions_hashes))
}
let merkle_roots = BlockMerkleRoots {
mint_hash: txns.mint.hash(),
vt_hash_merkle_root: merkle_tree_root(&txns.value_transfer_txns),
dr_hash_merkle_root: merkle_tree_root(&txns.data_request_txns),
commit_hash_merkle_root: merkle_tree_root(&txns.commit_txns),
reveal_hash_merkle_root: merkle_tree_root(&txns.reveal_txns),
tally_hash_merkle_root: merkle_tree_root(&txns.tally_txns),
stake_hash_merkle_root: Hash::default(),
unstake_hash_merkle_root: Hash::default(),
};
Block::new(
BlockHeader {
signals: 1,
beacon: CheckpointBeacon {
checkpoint: 0,
hash_prev_block: bootstrap_hash,
},
merkle_roots,
proof: Default::default(),
bn256_public_key: Default::default(),
},
Default::default(),
txns,
)
}
pub fn dr_weight(&self) -> u32 {
let mut dr_weight = 0;
for dr_txn in self.txns.data_request_txns.iter() {
dr_weight += dr_txn.weight();
}
dr_weight
}
pub fn vt_weight(&self) -> u32 {
let mut vt_weight = 0;
for vt_txn in self.txns.value_transfer_txns.iter() {
vt_weight += vt_txn.weight();
}
vt_weight
}
pub fn st_weight(&self) -> u32 {
let mut st_weight = 0;
for st_txn in self.txns.stake_txns.iter() {
st_weight += st_txn.weight();
}
st_weight
}
pub fn ut_weight(&self) -> u32 {
let mut ut_weight = 0;
for ut_txn in self.txns.unstake_txns.iter() {
ut_weight += ut_txn.weight();
}
ut_weight
}
pub fn weight(&self) -> u32 {
self.dr_weight() + self.vt_weight() + self.st_weight() + self.ut_weight()
}
pub fn is_genesis(&self, genesis: &Hash) -> bool {
self.hash().eq(genesis)
}
}
impl BlockTransactions {
/// Return the number of transactions inside this block. This value includes the mint
/// transaction, as well as all the data requests, commits, reveals and tallies.
pub fn len(&self) -> usize {
self.mint.len()
+ self.value_transfer_txns.len()
+ self.data_request_txns.len()
+ self.commit_txns.len()
+ self.reveal_txns.len()
+ self.tally_txns.len()
+ self.stake_txns.len()
+ self.unstake_txns.len()
}
/// Returns true if this block contains no transactions
// TODO: this is impossible, remove this method
pub fn is_empty(&self) -> bool {
self.mint.is_empty()
&& self.value_transfer_txns.is_empty()
&& self.data_request_txns.is_empty()
&& self.commit_txns.is_empty()
&& self.reveal_txns.is_empty()
&& self.tally_txns.is_empty()
&& self.stake_txns.is_empty()
&& self.unstake_txns.is_empty()
}
/// Get a transaction given the `TransactionPointer`
pub fn get(&self, index: TransactionPointer) -> Option<Transaction> {
match index {
TransactionPointer::Mint => Some(&self.mint).cloned().map(Transaction::Mint),
TransactionPointer::ValueTransfer(i) => self
.value_transfer_txns
.get(i as usize)
.cloned()
.map(Transaction::ValueTransfer),
TransactionPointer::DataRequest(i) => self
.data_request_txns
.get(i as usize)
.cloned()
.map(Transaction::DataRequest),
TransactionPointer::Commit(i) => self
.commit_txns
.get(i as usize)
.cloned()
.map(Transaction::Commit),
TransactionPointer::Reveal(i) => self
.reveal_txns
.get(i as usize)
.cloned()
.map(Transaction::Reveal),
TransactionPointer::Tally(i) => self
.tally_txns
.get(i as usize)
.cloned()
.map(Transaction::Tally),
TransactionPointer::Stake(i) => self
.stake_txns
.get(i as usize)
.cloned()
.map(Transaction::Stake),
TransactionPointer::Unstake(i) => self
.unstake_txns
.get(i as usize)
.cloned()
.map(Transaction::Unstake),
}
}
/// Create a list of `(transaction_hash, pointer_to_block)` for all the transactions inside
/// this block
pub fn create_pointers_to_transactions(&self, block_hash: Hash) -> Vec<(Hash, PointerToBlock)> {
// Store all the transactions as well
let mut pointer_to_block = PointerToBlock {
block_hash,
transaction_index: TransactionPointer::Mint,
};
let mut items_to_add = Vec::with_capacity(self.len());
// Push mint transaction
{
let tx_hash = self.mint.hash();
items_to_add.push((tx_hash, pointer_to_block.clone()));
}
for (i, tx) in self.value_transfer_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::ValueTransfer(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.data_request_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::DataRequest(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.commit_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::Commit(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.reveal_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::Reveal(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.tally_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::Tally(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.stake_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::Stake(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
for (i, tx) in self.unstake_txns.iter().enumerate() {
pointer_to_block.transaction_index =
TransactionPointer::Unstake(u32::try_from(i).unwrap());
items_to_add.push((tx.hash(), pointer_to_block.clone()));
}
items_to_add
}
}
impl Hashable for BlockHeader {
fn hash(&self) -> Hash {
calculate_sha256(&self.to_pb_bytes().unwrap()).into()
}
}
impl MemoizedHashable for Block {
fn hashable_bytes(&self) -> Vec<u8> {
self.block_header
.to_versioned_pb_bytes(ProtocolVersion::guess())
.unwrap()
}
fn memoized_hash(&self) -> &MemoHash {
&self.hash
}
}
impl Hashable for CheckpointBeacon {
fn hash(&self) -> Hash {
calculate_sha256(&self.to_pb_bytes().unwrap()).into()
}
}
impl Hashable for CheckpointVRF {
fn hash(&self) -> Hash {
calculate_sha256(&self.to_pb_bytes().unwrap()).into()
}
}
impl Hashable for DataRequestOutput {
fn hash(&self) -> Hash {
calculate_sha256(&self.to_pb_bytes().unwrap()).into()
}
}
impl Hashable for PublicKey {
fn hash(&self) -> Hash {
let mut v = vec![];
v.extend([self.compressed]);
v.extend(self.bytes);
calculate_sha256(&v).into()
}
}
/// Block header structure
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, ProtobufConvert, Default, Hash)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::Block_BlockHeader")]
pub struct BlockHeader {
/// 32 bits for binary signaling new witnet protocol improvements.
/// See [WIP-0014](https://github.com/witnet/WIPs/blob/master/wip-0014.md) for more info.
pub signals: u32,
/// A checkpoint beacon for the epoch that this block is closing
pub beacon: CheckpointBeacon,
/// 256-bit hashes of all of the transactions committed to this block, so as to prove their belonging and integrity
pub merkle_roots: BlockMerkleRoots,
/// A miner-provided proof of leadership
pub proof: BlockEligibilityClaim,
/// The Bn256 public key
pub bn256_public_key: Option<Bn256PublicKey>,
}
/// Block merkle tree roots
#[derive(Debug, Eq, PartialEq, Clone, Serialize, Deserialize, ProtobufConvert, Default, Hash)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::Block_BlockHeader_BlockMerkleRoots")]
pub struct BlockMerkleRoots {
/// A 256-bit hash based on the mint transaction committed to this block
pub mint_hash: Hash,
/// A 256-bit hash based on all the value transfer transactions committed to this block
pub vt_hash_merkle_root: Hash,
/// A 256-bit hash based on all the data request transactions committed to this block
pub dr_hash_merkle_root: Hash,
/// A 256-bit hash based on all the commit transactions committed to this block
pub commit_hash_merkle_root: Hash,
/// A 256-bit hash based on all the reveal transactions committed to this block
pub reveal_hash_merkle_root: Hash,
/// A 256-bit hash based on all the tally transactions committed to this block
pub tally_hash_merkle_root: Hash,
/// A 256-bit hash based on all the stake transactions committed to this block
#[serde(default)]
pub stake_hash_merkle_root: Hash,
/// A 256-bit hash based on all the unstake transactions committed to this block
#[serde(default)]
pub unstake_hash_merkle_root: Hash,
}
/// Function to calculate a merkle tree from a transaction vector
pub fn merkle_tree_root<T>(transactions: &[T], protocol_version: ProtocolVersion) -> Hash
where
T: VersionedHashable,
{
let transactions_hashes: Vec<Sha256> = transactions
.iter()
.map(|x| match x.versioned_hash(protocol_version) {
Hash::SHA256(x) => Sha256(x),
})
.collect();
Hash::from(witnet_crypto::merkle::merkle_tree_root(
&transactions_hashes,
))
}
impl BlockMerkleRoots {
pub fn from_transactions(txns: &BlockTransactions, protocol_version: ProtocolVersion) -> Self {
BlockMerkleRoots {
mint_hash: txns.mint.versioned_hash(protocol_version),
vt_hash_merkle_root: merkle_tree_root(&txns.value_transfer_txns, protocol_version),
dr_hash_merkle_root: merkle_tree_root(&txns.data_request_txns, protocol_version),
commit_hash_merkle_root: merkle_tree_root(&txns.commit_txns, protocol_version),
reveal_hash_merkle_root: merkle_tree_root(&txns.reveal_txns, protocol_version),
tally_hash_merkle_root: merkle_tree_root(&txns.tally_txns, protocol_version),
stake_hash_merkle_root: {
if protocol_version < ProtocolVersion::V1_8 {
Hash::default()
} else {
merkle_tree_root(&txns.stake_txns, protocol_version)
}
},
unstake_hash_merkle_root: {
if protocol_version < ProtocolVersion::V2_0 {
Hash::default()
} else {
merkle_tree_root(&txns.unstake_txns, protocol_version)
}
},
}
}
}
/// `SuperBlock` abridges the tally and data request information that happened during a
/// `superblock_period` number of Witnet epochs as well the ARS members merkle root
/// as of the last block in that period.
/// This is needed to ensure that the security and trustlessness properties of Witnet will
/// be relayed to bridges with other block chains.
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, ProtobufConvert, Serialize)]
#[protobuf_convert(pb = "crate::proto::schema::witnet::SuperBlock")]
pub struct SuperBlock {
/// Number of signing committee members,
pub signing_committee_length: u32,
/// Merkle root of the Active Reputation Set members included into the previous SuperBlock
pub ars_root: Hash,
/// Merkle root of the data requests in the blocks created since the last SuperBlock
pub data_request_root: Hash,
/// Superblock index,
pub index: u32,
/// Hash of the block that this SuperBlock is attesting as the latest block in the block chain,
pub last_block: Hash,
/// Hash of the block that the previous SuperBlock used for its own `last_block` field,
pub last_block_in_previous_superblock: Hash,
/// Merkle root of the tallies in the blocks created since the last SuperBlock
pub tally_root: Hash,
#[protobuf_convert(skip)]
#[serde(skip)]
hash: MemoHash,
}
impl MemoizedHashable for SuperBlock {
fn hashable_bytes(&self) -> Vec<u8> {
self.serialize_as_bytes()
}
fn memoized_hash(&self) -> &MemoHash {
&self.hash
}
}
impl SuperBlock {
/// Simple factory for the `SuperBlock` data structure that automatically initiates the hash
/// field without actually performing the hash operation, just in case it is never used.
pub fn new(
signing_committee_length: u32,
ars_root: Hash,
data_request_root: Hash,
index: u32,
last_block: Hash,
last_block_in_previous_superblock: Hash,
tally_root: Hash,
) -> Self {
Self {
signing_committee_length,
ars_root,
data_request_root,
index,
last_block,
last_block_in_previous_superblock,
tally_root,
hash: Default::default(),
}