-
Notifications
You must be signed in to change notification settings - Fork 315
/
lib.rs
1848 lines (1610 loc) · 57 KB
/
lib.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 candid::CandidType;
use dfn_protobuf::ProtoBuf;
use ic_crypto_sha256::Sha256;
use ic_types::{CanisterId, PrincipalId};
use intmap::IntMap;
use lazy_static::lazy_static;
use on_wire::{FromWire, IntoWire};
use phantom_newtype::Id;
use serde::{
de::{Deserializer, MapAccess, Visitor},
ser::SerializeMap,
Deserialize, Serialize, Serializer,
};
use std::borrow::Cow;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::convert::TryFrom;
use std::convert::TryInto;
use std::fmt;
use std::hash::Hash;
use std::marker::PhantomData;
use std::str::FromStr;
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime};
pub mod account_identifier;
pub mod http_request;
pub mod icpts;
pub mod metrics_encoder;
#[path = "../gen/ic_ledger.pb.v1.rs"]
#[rustfmt::skip]
pub mod protobuf;
pub mod timestamp;
pub mod validate_endpoints;
pub mod archive;
use archive::Archive;
pub use archive::ArchiveOptions;
use dfn_core::api::now;
pub mod spawn;
pub use account_identifier::{AccountIdentifier, Subaccount};
pub use icpts::{ICPTs, DECIMAL_PLACES, ICP_SUBDIVIDABLE_BY, MIN_BURN_AMOUNT, TRANSACTION_FEE};
pub use protobuf::TimeStamp;
// Helper to print messages in magenta
pub fn print<S: std::convert::AsRef<str>>(s: S)
where
yansi::Paint<S>: std::string::ToString,
{
dfn_core::api::print(yansi::Paint::magenta(s).to_string());
}
pub const HASH_LENGTH: usize = 32;
#[derive(CandidType, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct HashOf<T> {
inner: Id<T, [u8; HASH_LENGTH]>,
}
impl<T: std::clone::Clone> Copy for HashOf<T> {}
impl<T> HashOf<T> {
pub fn into_bytes(self) -> [u8; HASH_LENGTH] {
self.inner.get()
}
pub fn new(bs: [u8; HASH_LENGTH]) -> Self {
HashOf { inner: Id::new(bs) }
}
}
impl<T> fmt::Display for HashOf<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let res = hex::encode(self.inner.get());
write!(f, "{}", res)
}
}
impl<T> FromStr for HashOf<T> {
type Err = String;
fn from_str(s: &str) -> Result<HashOf<T>, String> {
let v = hex::decode(s).map_err(|e| e.to_string())?;
let slice = v.as_slice();
match slice.try_into() {
Ok(ba) => Ok(HashOf::new(ba)),
Err(_) => Err(format!(
"Expected a Vec of length {} but it was {}",
HASH_LENGTH,
v.len(),
)),
}
}
}
impl<T> Serialize for HashOf<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
if serializer.is_human_readable() {
serializer.serialize_str(&self.to_string())
} else {
serializer.serialize_bytes(self.inner.get_ref())
}
}
}
impl<'de, T> Deserialize<'de> for HashOf<T> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct HashOfVisitor<T> {
phantom: PhantomData<T>,
}
impl<'de, T> Visitor<'de> for HashOfVisitor<T> {
type Value = HashOf<T>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"a hash of type {}: a blob with at most {} bytes",
std::any::type_name::<T>(),
HASH_LENGTH
)
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(HashOf::new(
v.try_into().expect("hash does not have correct length"),
))
}
fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
HashOf::from_str(s).map_err(E::custom)
}
}
if deserializer.is_human_readable() {
deserializer.deserialize_str(HashOfVisitor {
phantom: PhantomData,
})
} else {
deserializer.deserialize_bytes(HashOfVisitor {
phantom: PhantomData,
})
}
}
}
#[derive(
Serialize, Deserialize, CandidType, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
#[serde(transparent)]
pub struct EncodedBlock(pub Box<[u8]>);
impl From<Box<[u8]>> for EncodedBlock {
fn from(bytes: Box<[u8]>) -> Self {
Self(bytes)
}
}
impl EncodedBlock {
pub fn hash(&self) -> HashOf<Self> {
let mut state = Sha256::new();
state.write(&self.0);
HashOf::new(state.finish())
}
pub fn decode(&self) -> Result<Block, String> {
let bytes = self.0.to_vec();
Ok(ProtoBuf::from_bytes(bytes)?.get())
}
pub fn size_bytes(&self) -> usize {
self.0.len()
}
}
#[derive(
Serialize, Deserialize, CandidType, Clone, Copy, Hash, Debug, PartialEq, Eq, PartialOrd, Ord,
)]
pub struct Memo(pub u64);
impl Default for Memo {
fn default() -> Memo {
Memo(0)
}
}
/// Position of a block in the chain. The first block has position 0.
pub type BlockHeight = u64;
pub type Certification = Option<Vec<u8>>;
pub type LedgerBalances = Balances<HashMap<AccountIdentifier, ICPTs>>;
pub trait BalancesStore {
fn get_balance(&self, k: &AccountIdentifier) -> Option<&ICPTs>;
// Update balance for an account using function f.
// Its arg is previous balance or None if not found and
// return value is the new balance.
fn update<F>(&mut self, acc: AccountIdentifier, action_on_acc: F)
where
F: FnMut(Option<&ICPTs>) -> ICPTs;
}
impl BalancesStore for HashMap<AccountIdentifier, ICPTs> {
fn get_balance(&self, k: &AccountIdentifier) -> Option<&ICPTs> {
self.get(k)
}
fn update<F>(&mut self, k: AccountIdentifier, mut f: F)
where
F: FnMut(Option<&ICPTs>) -> ICPTs,
{
match self.entry(k) {
Occupied(mut entry) => {
let new_v = f(Some(entry.get()));
if new_v != ICPTs::ZERO {
*entry.get_mut() = new_v;
} else {
entry.remove_entry();
}
}
Vacant(entry) => {
let new_v = f(None);
if new_v != ICPTs::ZERO {
entry.insert(new_v);
}
}
};
}
}
/// Describes the state of users accounts at the tip of the chain
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Balances<S: BalancesStore> {
// This uses a mutable map because we don't want to risk a space leak and we only require the
// account balances at the tip of the chain
pub store: S,
pub icpt_pool: ICPTs,
}
impl<S: Default + BalancesStore> Default for Balances<S> {
fn default() -> Self {
Self::new()
}
}
impl<S: Default + BalancesStore> Balances<S> {
pub fn new() -> Self {
Self {
store: S::default(),
icpt_pool: ICPTs::MAX,
}
}
pub fn add_payment(&mut self, payment: &Transfer) {
match payment {
Transfer::Send {
from,
to,
amount,
fee,
} => {
let debit_amount = (*amount + *fee).expect("amount + fee failed");
self.debit(from, debit_amount);
self.credit(to, *amount);
self.icpt_pool += *fee;
}
Transfer::Burn { from, amount, .. } => {
self.debit(from, *amount);
self.icpt_pool += *amount;
}
Transfer::Mint { to, amount, .. } => {
self.credit(to, *amount);
self.icpt_pool -= *amount;
}
}
}
// Debiting an account will automatically remove it from the `inner`
// HashMap if the balance reaches zero.
pub fn debit(&mut self, from: &AccountIdentifier, amount: ICPTs) {
self.store.update(*from, |prev| {
let mut balance = match prev {
Some(x) => *x,
None => panic!("You tried to withdraw funds from empty account {}", from),
};
if balance < amount {
panic!(
"You have tried to spend more than the balance of account {}",
from
);
}
balance -= amount;
balance
});
}
// Crediting an account will automatically add it to the `inner` HashMap if
// not already present.
pub fn credit(&mut self, to: &AccountIdentifier, amount: ICPTs) {
self.store.update(*to, |prev| {
let mut balance = match prev {
Some(x) => *x,
None => ICPTs::ZERO,
};
balance += amount;
balance
});
}
pub fn account_balance(&self, account: &AccountIdentifier) -> ICPTs {
self.store
.get_balance(account)
.cloned()
.unwrap_or(ICPTs::ZERO)
}
/// Returns the total quantity of ICPs that are "in existence" -- that
/// is, excluding un-minted "potential" ICPs.
pub fn total_supply(&self) -> ICPTs {
(ICPTs::MAX - self.icpt_pool).unwrap_or_else(|e| {
panic!(
"It is expected that the icpt_pool is always smaller than \
or equal to ICPTs::MAX, yet subtracting it lead to the following error: {}",
e
)
})
}
}
impl LedgerBalances {
// Find the specified number of accounts with lowest balances so that their
// balances can be reclaimed.
fn select_accounts_to_trim(&mut self, num_accounts: usize) -> Vec<(ICPTs, AccountIdentifier)> {
let mut to_trim: std::collections::BinaryHeap<(ICPTs, AccountIdentifier)> =
std::collections::BinaryHeap::new();
let mut iter = self.store.iter();
// Accumulate up to `trim_quantity` accounts
for (account, balance) in iter.by_ref().take(num_accounts) {
to_trim.push((*balance, *account));
}
for (account, balance) in iter {
// If any account's balance is lower than the maximum in our set,
// include that account, and remove the current maximum
if let Some((greatest_balance, _)) = to_trim.peek() {
if balance < greatest_balance {
to_trim.push((*balance, *account));
to_trim.pop();
}
}
}
to_trim.into_vec()
}
}
/// An operation which modifies account balances
#[derive(
Serialize, Deserialize, CandidType, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord,
)]
pub enum Transfer {
Burn {
from: AccountIdentifier,
amount: ICPTs,
},
Mint {
to: AccountIdentifier,
amount: ICPTs,
},
Send {
from: AccountIdentifier,
to: AccountIdentifier,
amount: ICPTs,
fee: ICPTs,
},
}
/// A transfer with the metadata the client generated attached to it
#[derive(
Serialize, Deserialize, CandidType, Clone, Hash, Debug, PartialEq, Eq, PartialOrd, Ord,
)]
pub struct Transaction {
pub transfer: Transfer,
pub memo: Memo,
/// The time this transaction was created.
pub created_at_time: TimeStamp,
}
impl Transaction {
pub fn new(
from: AccountIdentifier,
to: AccountIdentifier,
amount: ICPTs,
fee: ICPTs,
memo: Memo,
created_at_time: TimeStamp,
) -> Self {
let transfer = Transfer::Send {
from,
to,
amount,
fee,
};
Transaction {
transfer,
memo,
created_at_time,
}
}
pub fn hash(&self) -> HashOf<Self> {
let mut state = Sha256::new();
state.write(&serde_cbor::ser::to_vec_packed(&self).unwrap());
HashOf::new(state.finish())
}
}
/// A transaction with the metadata the canister generated attached to it
#[derive(CandidType, Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Block {
pub parent_hash: Option<HashOf<EncodedBlock>>,
pub transaction: Transaction,
/// Nanoseconds since the Unix epoch.
pub timestamp: TimeStamp,
}
impl Block {
pub fn new(
parent_hash: Option<HashOf<EncodedBlock>>,
transfer: Transfer,
memo: Memo,
created_at_time: TimeStamp, // transaction timestamp
timestamp: TimeStamp, // block timestamp
) -> Result<Self, String> {
let transaction = Transaction {
transfer,
memo,
created_at_time,
};
Ok(Self::new_from_transaction(
parent_hash,
transaction,
timestamp,
))
}
pub fn new_from_transaction(
parent_hash: Option<HashOf<EncodedBlock>>,
transaction: Transaction,
timestamp: TimeStamp,
) -> Self {
Self {
parent_hash,
transaction,
timestamp,
}
}
pub fn encode(self) -> Result<EncodedBlock, String> {
let slice = ProtoBuf::new(self).into_bytes()?.into_boxed_slice();
Ok(EncodedBlock(slice))
}
pub fn parent_hash(&self) -> Option<HashOf<EncodedBlock>> {
self.parent_hash
}
pub fn transaction(&self) -> Cow<Transaction> {
Cow::Borrowed(&self.transaction)
}
pub fn timestamp(&self) -> TimeStamp {
self.timestamp
}
}
/// Stores a chain of transactions with their metadata
#[derive(Serialize, Deserialize, Debug)]
pub struct Blockchain {
pub blocks: Vec<EncodedBlock>,
pub last_hash: Option<HashOf<EncodedBlock>>,
/// The timestamp of the most recent block. Must be monotonically
/// non-decreasing.
pub last_timestamp: TimeStamp,
pub archive: Arc<RwLock<Option<Archive>>>,
/// How many blocks have been sent to the archive
pub num_archived_blocks: u64,
}
impl Default for Blockchain {
fn default() -> Self {
Self {
blocks: vec![],
last_hash: None,
last_timestamp: SystemTime::UNIX_EPOCH.into(),
archive: Arc::new(RwLock::new(None)),
num_archived_blocks: 0,
}
}
}
impl Blockchain {
pub fn add_block(&mut self, block: Block) -> Result<BlockHeight, String> {
let raw_block = block.clone().encode()?;
self.add_block_with_encoded(block, raw_block)
}
pub fn add_block_with_encoded(
&mut self,
block: Block,
encoded_block: EncodedBlock,
) -> Result<BlockHeight, String> {
if block.parent_hash != self.last_hash {
return Err("Cannot apply block because its parent hash doesn't match.".to_string());
}
if block.timestamp < self.last_timestamp {
return Err(
"Cannot apply block because its timestamp is older than the previous tip."
.to_owned(),
);
}
self.last_hash = Some(encoded_block.hash());
self.last_timestamp = block.timestamp;
self.blocks.push(encoded_block);
Ok(self.chain_length().checked_sub(1).unwrap())
}
pub fn get(&self, height: BlockHeight) -> Option<&EncodedBlock> {
if height < self.num_archived_blocks() {
None
} else {
self.blocks
.get(usize::try_from(height - self.num_archived_blocks()).unwrap())
}
}
pub fn last(&self) -> Option<&EncodedBlock> {
self.blocks.last()
}
pub fn num_archived_blocks(&self) -> u64 {
self.num_archived_blocks
}
/// This is used when we try to archive a chunk
pub fn add_num_archived_blocks(&mut self, to_add: u64) {
self.num_archived_blocks += to_add;
}
/// This is used when we fail to archive a chunk
pub fn sub_num_archived_blocks(&mut self, to_sub: u64) {
self.num_archived_blocks -= to_sub;
}
pub fn num_unarchived_blocks(&self) -> u64 {
self.blocks.len().try_into().unwrap()
}
pub fn chain_length(&self) -> BlockHeight {
self.num_archived_blocks() + self.num_unarchived_blocks() as BlockHeight
}
}
/// Similar to Vec::split_off. Splits the Vec into two at the given index. `vec`
/// contains elements [at, len), and the returned Vec contains elements [0, at).
pub fn split_off_front(vec: &mut Vec<EncodedBlock>, at: usize) -> Vec<EncodedBlock> {
let len = vec.len();
assert!(at <= len, "`at` out of bounds");
let returned = vec[0..at].to_vec();
*vec = vec[at..].to_vec();
returned
}
fn serialize_int_map<S>(im: &IntMap<()>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(im.len()))?;
for (k, v) in im.iter() {
map.serialize_entry(k, v)?;
}
map.end()
}
struct IntMapVisitor<V> {
marker: PhantomData<fn() -> IntMap<V>>,
}
impl<V> IntMapVisitor<V> {
fn new() -> Self {
IntMapVisitor {
marker: PhantomData,
}
}
}
impl<'de, V> Visitor<'de> for IntMapVisitor<V>
where
V: Deserialize<'de>,
{
type Value = IntMap<V>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a very special map")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut map = IntMap::with_capacity(access.size_hint().unwrap_or(0));
while let Some((key, value)) = access.next_entry()? {
map.insert(key, value);
}
Ok(map)
}
}
fn deserialize_int_map<'de, D>(deserializer: D) -> Result<IntMap<()>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(IntMapVisitor::new())
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Ledger {
pub balances: LedgerBalances,
pub blockchain: Blockchain,
// A cap on the maximum number of accounts
maximum_number_of_accounts: usize,
// When maximum number of accounts is exceeded, a specified number of
// accounts with lowest balances are removed
accounts_overflow_trim_quantity: usize,
pub minting_account_id: Option<AccountIdentifier>,
// This is a set of blockheights that have been notified
#[serde(
serialize_with = "serialize_int_map",
deserialize_with = "deserialize_int_map",
default = "IntMap::new"
)]
pub blocks_notified: IntMap<()>,
/// How long transactions are remembered to detect duplicates.
pub transaction_window: Duration,
/// For each transaction, record the block in which the
/// transaction was created. This only contains transactions from
/// the last `transaction_window` period.
transactions_by_hash: BTreeMap<HashOf<Transaction>, BlockHeight>,
/// The transactions in the transaction window, sorted by block
/// index / block timestamp. (Block timestamps are monotonically
/// non-decreasing, so this is the same.)
transactions_by_height: VecDeque<TransactionInfo>,
/// Used to prevent non-whitelisted canisters from sending tokens
send_whitelist: HashSet<CanisterId>,
}
#[derive(Serialize, Deserialize, Debug)]
struct TransactionInfo {
block_timestamp: TimeStamp,
transaction_hash: HashOf<Transaction>,
}
impl Default for Ledger {
fn default() -> Self {
Self {
balances: LedgerBalances::default(),
blockchain: Blockchain::default(),
maximum_number_of_accounts: 50_000_000,
accounts_overflow_trim_quantity: 100_000,
minting_account_id: None,
blocks_notified: IntMap::new(),
transaction_window: Duration::from_secs(24 * 60 * 60),
transactions_by_hash: BTreeMap::new(),
transactions_by_height: VecDeque::new(),
send_whitelist: HashSet::new(),
}
}
}
impl Ledger {
/// This creates a block and adds it to the ledger
pub fn add_payment(
&mut self,
memo: Memo,
payment: Transfer,
created_at_time: Option<TimeStamp>,
) -> Result<(BlockHeight, HashOf<EncodedBlock>), String> {
self.add_payment_with_timestamp(memo, payment, created_at_time, dfn_core::api::now().into())
}
/// Internal version of `add_payment` that takes a timestamp, for
/// testing.
fn add_payment_with_timestamp(
&mut self,
memo: Memo,
payment: Transfer,
created_at_time: Option<TimeStamp>,
now: TimeStamp,
) -> Result<(BlockHeight, HashOf<EncodedBlock>), String> {
self.purge_old_transactions(now);
let created_at_time = created_at_time.unwrap_or(now);
if created_at_time + self.transaction_window < now {
return Err("Rejecting expired transaction.".to_owned());
}
if created_at_time > now + ic_types::ingress::PERMITTED_DRIFT {
return Err("Rejecting transaction with timestamp in the future.".to_owned());
}
let transaction = Transaction {
transfer: payment.clone(),
memo,
created_at_time,
};
let transaction_hash = transaction.hash();
if self.transactions_by_hash.contains_key(&transaction_hash) {
return Err("Transaction already exists on chain.".to_owned());
}
let block = Block::new_from_transaction(self.blockchain.last_hash, transaction, now);
let block_timestamp = block.timestamp;
self.balances.add_payment(&payment);
let height = self.blockchain.add_block(block)?;
self.transactions_by_hash.insert(transaction_hash, height);
self.transactions_by_height.push_back(TransactionInfo {
block_timestamp,
transaction_hash,
});
let to_trim = if self.balances.store.len()
>= self.maximum_number_of_accounts + self.accounts_overflow_trim_quantity
{
self.balances
.select_accounts_to_trim(self.accounts_overflow_trim_quantity)
} else {
vec![]
};
for (balance, account) in to_trim {
let transfer = Transfer::Burn {
from: account,
amount: balance,
};
self.balances.add_payment(&transfer);
self.blockchain
.add_block(Block::new_from_transaction(
self.blockchain.last_hash,
Transaction {
transfer,
memo: Memo::default(),
created_at_time: now,
},
now,
))
.unwrap();
}
Ok((height, self.blockchain.last_hash.unwrap()))
}
/// Remove transactions older than `transaction_window`.
fn purge_old_transactions(&mut self, now: TimeStamp) {
while let Some(TransactionInfo {
block_timestamp,
transaction_hash,
}) = self.transactions_by_height.front()
{
if *block_timestamp + self.transaction_window > now {
// Stop at a sufficiently recent block.
break;
}
let removed = self.transactions_by_hash.remove(&transaction_hash);
assert!(removed.is_some());
// After 24 hours we don't need to store notification state because it isn't
// accessible. We don't inspect the result because we don't care whether a
// notification at this block height was made or not.
match removed {
Some(bh) => self.blocks_notified.remove(bh),
None => None,
};
self.transactions_by_height.pop_front();
}
}
/// This adds a pre created block to the ledger. This should only be used
/// during canister migration or upgrade
pub fn add_block(&mut self, block: Block) -> Result<BlockHeight, String> {
self.balances.add_payment(&block.transaction.transfer);
self.blockchain.add_block(block)
}
pub fn from_init(
&mut self,
initial_values: HashMap<AccountIdentifier, ICPTs>,
minting_account: AccountIdentifier,
timestamp: TimeStamp,
transaction_window: Option<Duration>,
send_whitelist: HashSet<CanisterId>,
) {
self.balances.icpt_pool = ICPTs::MAX;
self.minting_account_id = Some(minting_account);
if let Some(t) = transaction_window {
self.transaction_window = t;
}
for (to, amount) in initial_values.into_iter() {
self.add_payment_with_timestamp(
Memo::default(),
Transfer::Mint { to, amount },
None,
timestamp,
)
.expect(&format!("Creating account {:?} failed", to)[..]);
}
self.send_whitelist = send_whitelist;
}
pub fn change_notification_state(
&mut self,
height: BlockHeight,
block_timestamp: TimeStamp,
new_state: bool,
now: TimeStamp,
) -> Result<(), String> {
if block_timestamp + self.transaction_window <= now {
return Err(format!(
"You cannot send a notification for a transaction that is more than {} seconds old",
self.transaction_window.as_secs(),
));
}
let is_notified = self.blocks_notified.get(height).is_some();
match (is_notified, new_state) {
(true, true) | (false, false) => {
Err(format!("The notification state is already {}", is_notified))
}
(true, false) => {
self.blocks_notified.remove(height);
Ok(())
}
(false, true) => {
self.blocks_notified.insert(height, ());
Ok(())
}
}
}
pub fn find_block_in_archive(&self, block_height: u64) -> Option<CanisterId> {
let index = self
.blockchain
.archive
.try_read()
.expect("Failed to get lock on archive")
.as_ref()
.expect("archiving not enabled")
.index();
let result = index.binary_search_by(|((from, to), _)| {
// If within the range we've found the right node
if *from <= block_height && block_height <= *to {
std::cmp::Ordering::Equal
} else if *from < block_height {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Greater
}
});
match result {
Ok(i) => Some(index[i].1),
Err(_) => None,
}
}
pub fn split_off_blocks_to_archive(&mut self, at: usize) -> VecDeque<EncodedBlock> {
if self
.blockchain
.archive
.try_read()
.expect("Failed to get lock on archive")
.is_none()
{
VecDeque::new()
} else {
VecDeque::from(split_off_front(&mut self.blockchain.blocks, at))
}
}
#[allow(clippy::type_complexity)]
pub fn archive_blocks(
&mut self,
) -> Option<(VecDeque<EncodedBlock>, Arc<RwLock<Option<Archive>>>)> {
let (trigger_threshold, num_blocks_to_archive) = match &self.blockchain.archive.try_read() {
Ok(l) => match l.as_ref() {
Some(a) => (a.trigger_threshold, a.num_blocks_to_archive),
None => {
print("[ledger] archive not enabled. skipping archive_blocks()");
return None;
}
},
Err(_) => {
print("[ledger] ledger is currently archiving. skipping archive_blocks()");
return None;
}
};
// Upon reaching the `trigger_threshold` we will archive
// `num_blocks_to_archive`. For example, when set to (2000, 1000)
// archiving will trigger when there are 2000 blocks in the ledger and
// the 1000 oldest bocks will be archived, leaving the remaining 1000
// blocks in place.
let num_blocks_before = self.blockchain.num_unarchived_blocks();
if (num_blocks_before as usize) < trigger_threshold {
return None;
}
let blocks_to_archive: VecDeque<EncodedBlock> =
self.split_off_blocks_to_archive(num_blocks_to_archive);
let num_blocks_after = self.blockchain.num_unarchived_blocks();
print(format!(
"[ledger] archive_blocks(): trigger_threshold: {}, num_blocks: {}, blocks before split: {}, blocks to archive: {}, blocks after split: {}",
trigger_threshold,
num_blocks_to_archive,
num_blocks_before,
blocks_to_archive.len(),
num_blocks_after,
));
Some((blocks_to_archive, self.blockchain.archive.clone()))
}
pub fn can_send(&self, principal_id: &PrincipalId) -> bool {
principal_id.is_self_authenticating()
|| LEDGER
.read()
.unwrap()
.send_whitelist
.contains(&CanisterId::new(*principal_id).unwrap())
}
pub fn transactions_by_hash_len(&self) -> usize {
self.transactions_by_hash.len()
}
pub fn transactions_by_height_len(&self) -> usize {
self.transactions_by_height.len()
}
}
lazy_static! {
pub static ref LEDGER: RwLock<Ledger> = RwLock::new(Ledger::default());
// Maximum inter-canister message size in bytes
pub static ref MAX_MESSAGE_SIZE_BYTES: RwLock<usize> = RwLock::new(1024 * 1024);
}
pub fn add_payment(
memo: Memo,
payment: Transfer,
created_at_time: Option<TimeStamp>,
) -> (BlockHeight, HashOf<EncodedBlock>) {
LEDGER
.write()
.unwrap()
.add_payment(memo, payment, created_at_time)
.expect("Transfer failed")
}
pub fn change_notification_state(