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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use crate::vm::analysis::ContractAnalysis;
use crate::vm::contracts::Contract;
use crate::vm::database::ClarityDatabase;
use crate::vm::errors::{Error, InterpreterError, RuntimeErrorType};
use crate::vm::types::{PrincipalData, TypeSignature};
use serde::Deserialize;
use stacks_common::util::hash::{hex_bytes, to_hex};
use std::convert::TryInto;
use std::io::Write;

pub trait ClaritySerializable {
    fn serialize(&self) -> String;
}

pub trait ClarityDeserializable<T> {
    fn deserialize(json: &str) -> T;
}

impl ClaritySerializable for String {
    fn serialize(&self) -> String {
        self.into()
    }
}

impl ClarityDeserializable<String> for String {
    fn deserialize(serialized: &str) -> String {
        serialized.into()
    }
}

macro_rules! clarity_serializable {
    ($Name:ident) => {
        impl ClaritySerializable for $Name {
            fn serialize(&self) -> String {
                serde_json::to_string(self).expect("Failed to serialize vm.Value")
            }
        }
        impl ClarityDeserializable<$Name> for $Name {
            #[cfg(not(feature = "wasm"))]
            fn deserialize(json: &str) -> Self {
                let mut deserializer = serde_json::Deserializer::from_str(&json);
                // serde's default 128 depth limit can be exhausted
                //  by a 64-stack-depth AST, so disable the recursion limit
                deserializer.disable_recursion_limit();
                // use stacker to prevent the deserializer from overflowing.
                //  this will instead spill to the heap
                let deserializer = serde_stacker::Deserializer::new(&mut deserializer);
                Deserialize::deserialize(deserializer).expect("Failed to deserialize vm.Value")
            }

            #[cfg(feature = "wasm")]
            fn deserialize(json: &str) -> Self {
                serde_json::from_str(json).expect("Failed to serialize vm.Value")
            }
        }
    };
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FungibleTokenMetadata {
    pub total_supply: Option<u128>,
}

clarity_serializable!(FungibleTokenMetadata);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NonFungibleTokenMetadata {
    pub key_type: TypeSignature,
}

clarity_serializable!(NonFungibleTokenMetadata);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DataMapMetadata {
    pub key_type: TypeSignature,
    pub value_type: TypeSignature,
}

clarity_serializable!(DataMapMetadata);

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DataVariableMetadata {
    pub value_type: TypeSignature,
}

clarity_serializable!(DataVariableMetadata);

#[derive(Serialize, Deserialize)]
pub struct ContractMetadata {
    pub contract: Contract,
}

clarity_serializable!(ContractMetadata);

#[derive(Serialize, Deserialize)]
pub struct SimmedBlock {
    pub block_height: u64,
    pub block_time: u64,
    pub block_header_hash: [u8; 32],
    pub burn_chain_header_hash: [u8; 32],
    pub vrf_seed: [u8; 32],
}

clarity_serializable!(SimmedBlock);

clarity_serializable!(PrincipalData);
clarity_serializable!(i128);
clarity_serializable!(u128);
clarity_serializable!(u64);
clarity_serializable!(Contract);
clarity_serializable!(ContractAnalysis);

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum STXBalance {
    Unlocked {
        amount: u128,
    },
    LockedPoxOne {
        amount_unlocked: u128,
        amount_locked: u128,
        unlock_height: u64,
    },
    LockedPoxTwo {
        amount_unlocked: u128,
        amount_locked: u128,
        unlock_height: u64,
    },
    LockedPoxThree {
        amount_unlocked: u128,
        amount_locked: u128,
        unlock_height: u64,
    },
}

/// Lifetime-limited handle to an uncommitted balance structure.
/// All balance mutations (debits, credits, locks, unlocks) must go through this structure.
pub struct STXBalanceSnapshot<'db, 'conn> {
    principal: PrincipalData,
    balance: STXBalance,
    burn_block_height: u64,
    db_ref: &'conn mut ClarityDatabase<'db>,
}

type Result<T> = std::result::Result<T, Error>;

impl ClaritySerializable for STXBalance {
    fn serialize(&self) -> String {
        let mut buffer = Vec::new();
        match self {
            STXBalance::Unlocked { amount } => {
                buffer
                    .write_all(&amount.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_unlocked.");
                buffer
                    .write_all(&0u128.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_locked.");
                buffer
                    .write_all(&0u64.to_be_bytes())
                    .expect("STXBalance serialization: failed writing unlock_height.");
            }
            STXBalance::LockedPoxOne {
                amount_unlocked,
                amount_locked,
                unlock_height,
            } => {
                buffer
                    .write_all(&amount_unlocked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_unlocked.");
                buffer
                    .write_all(&amount_locked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_locked.");
                buffer
                    .write_all(&unlock_height.to_be_bytes())
                    .expect("STXBalance serialization: failed writing unlock_height.");
            }
            STXBalance::LockedPoxTwo {
                amount_unlocked,
                amount_locked,
                unlock_height,
            } => {
                buffer
                    .write_all(&[STXBalance::pox_2_version])
                    .expect("STXBalance serialization: failed to write PoX version byte");
                buffer
                    .write_all(&amount_unlocked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_unlocked.");
                buffer
                    .write_all(&amount_locked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_locked.");
                buffer
                    .write_all(&unlock_height.to_be_bytes())
                    .expect("STXBalance serialization: failed writing unlock_height.");
            }
            STXBalance::LockedPoxThree {
                amount_unlocked,
                amount_locked,
                unlock_height,
            } => {
                buffer
                    .write_all(&[STXBalance::pox_3_version])
                    .expect("STXBalance serialization: failed to write PoX version byte");
                buffer
                    .write_all(&amount_unlocked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_unlocked.");
                buffer
                    .write_all(&amount_locked.to_be_bytes())
                    .expect("STXBalance serialization: failed writing amount_locked.");
                buffer
                    .write_all(&unlock_height.to_be_bytes())
                    .expect("STXBalance serialization: failed writing unlock_height.");
            }
        }
        to_hex(buffer.as_slice())
    }
}

impl ClarityDeserializable<STXBalance> for STXBalance {
    fn deserialize(input: &str) -> Self {
        let bytes = hex_bytes(&input).expect("STXBalance deserialization: failed decoding bytes.");
        if bytes.len() == STXBalance::unlocked_and_v1_size {
            let amount_unlocked = u128::from_be_bytes(
                bytes[0..16]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading amount_unlocked."),
            );
            let amount_locked = u128::from_be_bytes(
                bytes[16..32]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading amount_locked."),
            );
            let unlock_height = u64::from_be_bytes(
                bytes[32..40]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading unlock_height."),
            );

            if amount_locked == 0 {
                STXBalance::Unlocked {
                    amount: amount_unlocked,
                }
            } else {
                STXBalance::LockedPoxOne {
                    amount_unlocked,
                    amount_locked,
                    unlock_height,
                }
            }
        } else if bytes.len() == STXBalance::v2_and_v3_size {
            let version = &bytes[0];
            if version != &STXBalance::pox_2_version && version != &STXBalance::pox_3_version {
                panic!(
                    "Bad version byte in STX Balance serialization = {}",
                    version
                );
            }
            let amount_unlocked = u128::from_be_bytes(
                bytes[1..17]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading amount_unlocked."),
            );
            let amount_locked = u128::from_be_bytes(
                bytes[17..33]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading amount_locked."),
            );
            let unlock_height = u64::from_be_bytes(
                bytes[33..41]
                    .try_into()
                    .expect("STXBalance deserialization: failed reading unlock_height."),
            );

            if amount_locked == 0 {
                STXBalance::Unlocked {
                    amount: amount_unlocked,
                }
            } else if version == &STXBalance::pox_2_version {
                STXBalance::LockedPoxTwo {
                    amount_unlocked,
                    amount_locked,
                    unlock_height,
                }
            } else if version == &STXBalance::pox_3_version {
                STXBalance::LockedPoxThree {
                    amount_unlocked,
                    amount_locked,
                    unlock_height,
                }
            } else {
                unreachable!("Version is checked for pox_3 or pox_2 version compliance above");
            }
        } else {
            panic!("Bad STX Balance serialization size = {}", bytes.len());
        }
    }
}

impl<'db, 'conn> STXBalanceSnapshot<'db, 'conn> {
    pub fn new(
        principal: &PrincipalData,
        balance: STXBalance,
        burn_height: u64,
        db_ref: &'conn mut ClarityDatabase<'db>,
    ) -> STXBalanceSnapshot<'db, 'conn> {
        STXBalanceSnapshot {
            principal: principal.clone(),
            balance,
            burn_block_height: burn_height,
            db_ref,
        }
    }

    pub fn balance(&self) -> &STXBalance {
        &self.balance
    }

    pub fn save(self) -> () {
        let key = ClarityDatabase::make_key_for_account_balance(&self.principal);
        self.db_ref.put(&key, &self.balance)
    }

    pub fn transfer_to(mut self, recipient: &PrincipalData, amount: u128) -> Result<()> {
        if !self.can_transfer(amount) {
            return Err(InterpreterError::InsufficientBalance.into());
        }

        let recipient_key = ClarityDatabase::make_key_for_account_balance(recipient);
        let mut recipient_balance = self
            .db_ref
            .get(&recipient_key)
            .unwrap_or(STXBalance::zero());

        recipient_balance
            .checked_add_unlocked_amount(amount)
            .ok_or(Error::Runtime(RuntimeErrorType::ArithmeticOverflow, None))?;

        self.debit(amount);
        self.db_ref.put(&recipient_key, &recipient_balance);
        self.save();
        Ok(())
    }

    pub fn get_available_balance(&mut self) -> u128 {
        let v1_unlock_height = self.db_ref.get_v1_unlock_height();
        let v2_unlock_height = self.db_ref.get_v2_unlock_height();
        self.balance.get_available_balance_at_burn_block(
            self.burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        )
    }

    pub fn canonical_balance_repr(&mut self) -> STXBalance {
        let v1_unlock_height = self.db_ref.get_v1_unlock_height();
        let v2_unlock_height = self.db_ref.get_v2_unlock_height();
        self.balance
            .canonical_repr_at_block(self.burn_block_height, v1_unlock_height, v2_unlock_height)
            .0
    }

    pub fn has_locked_tokens(&mut self) -> bool {
        let v1_unlock_height = self.db_ref.get_v1_unlock_height();
        let v2_unlock_height = self.db_ref.get_v2_unlock_height();
        self.balance.has_locked_tokens_at_burn_block(
            self.burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        )
    }

    pub fn has_unlockable_tokens(&mut self) -> bool {
        let v1_unlock_height = self.db_ref.get_v1_unlock_height();
        let v2_unlock_height = self.db_ref.get_v2_unlock_height();
        self.balance.has_unlockable_tokens_at_burn_block(
            self.burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        )
    }

    pub fn can_transfer(&mut self, amount: u128) -> bool {
        self.get_available_balance() >= amount
    }

    pub fn debit(&mut self, amount: u128) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-debit");
        }

        self.balance.debit_unlocked_amount(amount)
    }

    pub fn credit(&mut self, amount: u128) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-credit");
        }

        self.balance
            .checked_add_unlocked_amount(amount)
            .expect("STX balance overflow");
    }

    pub fn set_balance(&mut self, balance: STXBalance) {
        self.balance = balance;
    }

    pub fn lock_tokens_v1(&mut self, amount_to_lock: u128, unlock_burn_height: u64) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-token-lock");
        }

        // caller needs to have checked this
        assert!(amount_to_lock > 0, "BUG: cannot lock 0 tokens");

        if unlock_burn_height <= self.burn_block_height {
            // caller needs to have checked this
            panic!("FATAL: cannot set a lock with expired unlock burn height");
        }

        if self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account already has locked tokens");
        }

        // from `unlock_available_tokens_if_any` call above, `self.balance` should
        //  be canonicalized already

        let new_amount_unlocked = self
            .balance
            .get_total_balance()
            .checked_sub(amount_to_lock)
            .expect("STX underflow");

        self.balance = STXBalance::LockedPoxOne {
            amount_unlocked: new_amount_unlocked,
            amount_locked: amount_to_lock,
            unlock_height: unlock_burn_height,
        };
    }

    ////////////// Pox-2 /////////////////

    /// Return true iff `self` represents a snapshot that has a lock
    ///  created by PoX v2.
    pub fn is_v2_locked(&mut self) -> bool {
        match self.canonical_balance_repr() {
            STXBalance::LockedPoxTwo { .. } => true,
            _ => false,
        }
    }

    /// Increase the account's current lock to `new_total_locked`.
    /// Panics if `self` was not locked by V2 PoX.
    pub fn increase_lock_v2(&mut self, new_total_locked: u128) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after extend-token-lock");
        }

        if !self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account does not have locked tokens");
        }

        if !self.is_v2_locked() {
            // caller needs to have checked this
            panic!("FATAL: account must be locked by pox-2");
        }

        assert!(
            self.balance.amount_locked() <= new_total_locked,
            "FATAL: account must lock more after `increase_lock_v2`"
        );

        let total_amount = self
            .balance
            .amount_unlocked()
            .checked_add(self.balance.amount_locked())
            .expect("STX balance overflowed u128");
        let amount_unlocked = total_amount
            .checked_sub(new_total_locked)
            .expect("STX underflow: more is locked than total balance");

        self.balance = STXBalance::LockedPoxTwo {
            amount_unlocked,
            amount_locked: new_total_locked,
            unlock_height: self.balance.unlock_height(),
        };
    }

    /// Extend this account's current lock to `unlock_burn_height`.
    /// After calling, this method will set the balance to a "LockedPoxTwo" balance,
    ///  because this method is only invoked as a result of PoX2 interactions
    pub fn extend_lock_v2(&mut self, unlock_burn_height: u64) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after extend-token-lock");
        }

        if !self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account does not have locked tokens");
        }

        if unlock_burn_height <= self.burn_block_height {
            // caller needs to have checked this
            panic!("FATAL: cannot set a lock with expired unlock burn height");
        }

        self.balance = STXBalance::LockedPoxTwo {
            amount_unlocked: self.balance.amount_unlocked(),
            amount_locked: self.balance.amount_locked(),
            unlock_height: unlock_burn_height,
        };
    }

    /// Lock `amount_to_lock` tokens on this account until `unlock_burn_height`.
    /// After calling, this method will set the balance to a "LockedPoxTwo" balance,
    ///  because this method is only invoked as a result of PoX2 interactions
    pub fn lock_tokens_v2(&mut self, amount_to_lock: u128, unlock_burn_height: u64) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-token-lock");
        }

        // caller needs to have checked this
        assert!(amount_to_lock > 0, "BUG: cannot lock 0 tokens");

        if unlock_burn_height <= self.burn_block_height {
            // caller needs to have checked this
            panic!("FATAL: cannot set a lock with expired unlock burn height");
        }

        if self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account already has locked tokens");
        }

        // from `unlock_available_tokens_if_any` call above, `self.balance` should
        //  be canonicalized already

        let new_amount_unlocked = self
            .balance
            .get_total_balance()
            .checked_sub(amount_to_lock)
            .expect("STX underflow");

        self.balance = STXBalance::LockedPoxTwo {
            amount_unlocked: new_amount_unlocked,
            amount_locked: amount_to_lock,
            unlock_height: unlock_burn_height,
        };
    }

    //////////////// Pox-3 //////////////////

    /// Lock `amount_to_lock` tokens on this account until `unlock_burn_height`.
    /// After calling, this method will set the balance to a "LockedPoxThree" balance,
    ///  because this method is only invoked as a result of PoX3 interactions
    pub fn lock_tokens_v3(&mut self, amount_to_lock: u128, unlock_burn_height: u64) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-token-lock");
        }

        // caller needs to have checked this
        assert!(amount_to_lock > 0, "BUG: cannot lock 0 tokens");

        if unlock_burn_height <= self.burn_block_height {
            // caller needs to have checked this
            panic!("FATAL: cannot set a lock with expired unlock burn height");
        }

        if self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account already has locked tokens");
        }

        // from `unlock_available_tokens_if_any` call above, `self.balance` should
        //  be canonicalized already

        let new_amount_unlocked = self
            .balance
            .get_total_balance()
            .checked_sub(amount_to_lock)
            .expect("FATAL: account locks more STX than balance possessed");

        self.balance = STXBalance::LockedPoxThree {
            amount_unlocked: new_amount_unlocked,
            amount_locked: amount_to_lock,
            unlock_height: unlock_burn_height,
        };
    }

    /// Extend this account's current lock to `unlock_burn_height`.
    /// After calling, this method will set the balance to a "LockedPoxThree" balance,
    ///  because this method is only invoked as a result of PoX3 interactions
    pub fn extend_lock_v3(&mut self, unlock_burn_height: u64) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after extend-token-lock");
        }

        if !self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account does not have locked tokens");
        }

        if unlock_burn_height <= self.burn_block_height {
            // caller needs to have checked this
            panic!("FATAL: cannot set a lock with expired unlock burn height");
        }

        self.balance = STXBalance::LockedPoxThree {
            amount_unlocked: self.balance.amount_unlocked(),
            amount_locked: self.balance.amount_locked(),
            unlock_height: unlock_burn_height,
        };
    }

    /// Increase the account's current lock to `new_total_locked`.
    /// Panics if `self` was not locked by V3 PoX.
    pub fn increase_lock_v3(&mut self, new_total_locked: u128) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after extend-token-lock");
        }

        if !self.has_locked_tokens() {
            // caller needs to have checked this
            panic!("FATAL: account does not have locked tokens");
        }

        if !self.is_v3_locked() {
            // caller needs to have checked this
            panic!("FATAL: account must be locked by pox-3");
        }

        assert!(
            self.balance.amount_locked() <= new_total_locked,
            "FATAL: account must lock more after `increase_lock_v3`"
        );

        let total_amount = self
            .balance
            .amount_unlocked()
            .checked_add(self.balance.amount_locked())
            .expect("STX balance overflowed u128");
        let amount_unlocked = total_amount
            .checked_sub(new_total_locked)
            .expect("STX underflow: more is locked than total balance");

        self.balance = STXBalance::LockedPoxThree {
            amount_unlocked,
            amount_locked: new_total_locked,
            unlock_height: self.balance.unlock_height(),
        };
    }

    /// Return true iff `self` represents a snapshot that has a lock
    ///  created by PoX v3.
    pub fn is_v3_locked(&mut self) -> bool {
        match self.canonical_balance_repr() {
            STXBalance::LockedPoxThree { .. } => true,
            _ => false,
        }
    }

    /////////////// GENERAL //////////////////////

    /// If this snapshot is locked, then alter the lock height to be
    /// the next burn block (i.e., `self.burn_block_height + 1`)
    pub fn accelerate_unlock(&mut self) {
        let unlocked = self.unlock_available_tokens_if_any();
        if unlocked > 0 {
            debug!("Consolidated after account-token-lock");
        }

        let new_unlock_height = self.burn_block_height + 1;
        self.balance = match self.balance {
            STXBalance::Unlocked { amount } => STXBalance::Unlocked { amount },
            STXBalance::LockedPoxOne { .. } => {
                unreachable!("Attempted to accelerate the unlock of a lockup created by PoX-1")
            }
            STXBalance::LockedPoxTwo {
                amount_unlocked,
                amount_locked,
                ..
            } => STXBalance::LockedPoxTwo {
                amount_unlocked,
                amount_locked,
                unlock_height: new_unlock_height,
            },
            STXBalance::LockedPoxThree {
                amount_unlocked,
                amount_locked,
                ..
            } => STXBalance::LockedPoxThree {
                amount_unlocked,
                amount_locked,
                unlock_height: new_unlock_height,
            },
        };
    }

    /// Unlock any tokens that are unlockable at the current
    ///  burn block height, and return the amount newly unlocked
    fn unlock_available_tokens_if_any(&mut self) -> u128 {
        let (new_balance, unlocked) = self.balance.canonical_repr_at_block(
            self.burn_block_height,
            self.db_ref.get_v1_unlock_height(),
            self.db_ref.get_v2_unlock_height(),
        );
        self.balance = new_balance;
        unlocked
    }
}

// NOTE: do _not_ add mutation methods to this struct. Put them in STXBalanceSnapshot!
impl STXBalance {
    pub const unlocked_and_v1_size: usize = 40;
    pub const v2_and_v3_size: usize = 41;
    pub const pox_2_version: u8 = 0;
    pub const pox_3_version: u8 = 1;

    pub fn zero() -> STXBalance {
        STXBalance::Unlocked { amount: 0 }
    }

    pub fn initial(amount: u128) -> STXBalance {
        STXBalance::Unlocked { amount }
    }

    /// This method returns the datastructure's lazy view of the unlock_height:
    ///  this *may* be updated by a canonicalized view of the account
    pub fn unlock_height(&self) -> u64 {
        match self {
            STXBalance::Unlocked { .. } => 0,
            STXBalance::LockedPoxOne { unlock_height, .. }
            | STXBalance::LockedPoxTwo { unlock_height, .. }
            | STXBalance::LockedPoxThree { unlock_height, .. } => *unlock_height,
        }
    }

    /// This method returns the datastructure's lazy view of the unlock_height
    ///  *while* factoring in the PoX 2 early unlock for PoX 1 and PoX 3 early unlock for PoX 2.
    /// This value is still lazy: this unlock height may be less than the current
    ///  burn block height, if so it will be updated in a canonicalized view.
    pub fn effective_unlock_height(&self, v1_unlock_height: u32, v2_unlock_height: u32) -> u64 {
        match self {
            STXBalance::Unlocked { .. } => 0,
            STXBalance::LockedPoxOne { unlock_height, .. } => {
                if *unlock_height >= (v1_unlock_height as u64) {
                    v1_unlock_height as u64
                } else {
                    *unlock_height
                }
            }
            STXBalance::LockedPoxTwo { unlock_height, .. } => {
                if *unlock_height >= (v2_unlock_height as u64) {
                    v2_unlock_height as u64
                } else {
                    *unlock_height
                }
            }
            STXBalance::LockedPoxThree { unlock_height, .. } => *unlock_height,
        }
    }

    /// This method returns the datastructure's lazy view of the amount locked:
    ///  this *may* be updated by a canonicalized view of the account
    pub fn amount_locked(&self) -> u128 {
        match self {
            STXBalance::Unlocked { .. } => 0,
            STXBalance::LockedPoxOne { amount_locked, .. }
            | STXBalance::LockedPoxTwo { amount_locked, .. }
            | STXBalance::LockedPoxThree { amount_locked, .. } => *amount_locked,
        }
    }

    /// This method returns the datastructure's lazy view of the amount unlocked:
    ///  this *may* be updated by a canonicalized view of the account
    pub fn amount_unlocked(&self) -> u128 {
        match self {
            STXBalance::Unlocked {
                amount: amount_unlocked,
            }
            | STXBalance::LockedPoxOne {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxTwo {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxThree {
                amount_unlocked, ..
            } => *amount_unlocked,
        }
    }

    fn debit_unlocked_amount(&mut self, delta: u128) {
        match self {
            STXBalance::Unlocked {
                amount: amount_unlocked,
            }
            | STXBalance::LockedPoxOne {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxTwo {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxThree {
                amount_unlocked, ..
            } => {
                *amount_unlocked = amount_unlocked.checked_sub(delta).expect("STX underflow");
            }
        }
    }

    fn checked_add_unlocked_amount(&mut self, delta: u128) -> Option<u128> {
        match self {
            STXBalance::Unlocked {
                amount: amount_unlocked,
            }
            | STXBalance::LockedPoxOne {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxTwo {
                amount_unlocked, ..
            }
            | STXBalance::LockedPoxThree {
                amount_unlocked, ..
            } => {
                if let Some(new_amount) = amount_unlocked.checked_add(delta) {
                    *amount_unlocked = new_amount;
                    Some(new_amount)
                } else {
                    None
                }
            }
        }
    }

    /// Returns a canonicalized STXBalance at a given burn_block_height
    /// (i.e., if burn_block_height >= unlock_height, then return struct where
    ///   amount_unlocked = 0, unlock_height = 0), and the amount of tokens which
    ///   are "unlocked" by the canonicalization
    pub fn canonical_repr_at_block(
        &self,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> (STXBalance, u128) {
        if self.has_unlockable_tokens_at_burn_block(
            burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        ) {
            (
                STXBalance::Unlocked {
                    amount: self.get_total_balance(),
                },
                self.amount_locked(),
            )
        } else {
            (self.clone(), 0)
        }
    }

    pub fn get_available_balance_at_burn_block(
        &self,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> u128 {
        if self.has_unlockable_tokens_at_burn_block(
            burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        ) {
            self.get_total_balance()
        } else {
            match self {
                STXBalance::Unlocked { amount } => *amount,
                STXBalance::LockedPoxOne {
                    amount_unlocked, ..
                } => *amount_unlocked,
                STXBalance::LockedPoxTwo {
                    amount_unlocked, ..
                } => *amount_unlocked,
                STXBalance::LockedPoxThree {
                    amount_unlocked, ..
                } => *amount_unlocked,
            }
        }
    }

    pub fn get_locked_balance_at_burn_block(
        &self,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> (u128, u64) {
        if self.has_unlockable_tokens_at_burn_block(
            burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        ) {
            (0, 0)
        } else {
            match self {
                STXBalance::Unlocked { .. } => (0, 0),
                STXBalance::LockedPoxOne {
                    amount_locked,
                    unlock_height,
                    ..
                } => (*amount_locked, *unlock_height),
                STXBalance::LockedPoxTwo {
                    amount_locked,
                    unlock_height,
                    ..
                } => (*amount_locked, *unlock_height),
                STXBalance::LockedPoxThree {
                    amount_locked,
                    unlock_height,
                    ..
                } => (*amount_locked, *unlock_height),
            }
        }
    }

    pub fn get_total_balance(&self) -> u128 {
        let (unlocked, locked) = match self {
            STXBalance::Unlocked { amount } => (*amount, 0),
            STXBalance::LockedPoxOne {
                amount_unlocked,
                amount_locked,
                ..
            } => (*amount_unlocked, *amount_locked),
            STXBalance::LockedPoxTwo {
                amount_unlocked,
                amount_locked,
                ..
            } => (*amount_unlocked, *amount_locked),
            STXBalance::LockedPoxThree {
                amount_unlocked,
                amount_locked,
                ..
            } => (*amount_unlocked, *amount_locked),
        };
        unlocked.checked_add(locked).expect("STX overflow")
    }

    pub fn was_locked_by_v1(&self) -> bool {
        if let STXBalance::LockedPoxOne { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn was_locked_by_v2(&self) -> bool {
        if let STXBalance::LockedPoxTwo { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn was_locked_by_v3(&self) -> bool {
        if let STXBalance::LockedPoxThree { .. } = self {
            true
        } else {
            false
        }
    }

    pub fn has_locked_tokens_at_burn_block(
        &self,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> bool {
        match self {
            STXBalance::Unlocked { .. } => false,
            STXBalance::LockedPoxOne {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                // if normally unlockable, return false
                if *unlock_height <= burn_block_height {
                    return false;
                }
                // if unlockable due to Stacks 2.1 early unlock
                if v1_unlock_height as u64 <= burn_block_height {
                    return false;
                }
                true
            }
            STXBalance::LockedPoxTwo {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                if *unlock_height <= burn_block_height {
                    return false;
                }
                // if unlockable due to Stacks 2.2 early unlock
                if v2_unlock_height as u64 <= burn_block_height {
                    return false;
                }
                true
            }
            STXBalance::LockedPoxThree {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                if *unlock_height <= burn_block_height {
                    return false;
                }
                true
            }
        }
    }

    pub fn has_unlockable_tokens_at_burn_block(
        &self,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> bool {
        match self {
            STXBalance::Unlocked { .. } => false,
            STXBalance::LockedPoxOne {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                // if normally unlockable, return true
                if *unlock_height <= burn_block_height {
                    return true;
                }
                // if unlockable due to Stacks 2.1 early unlock
                if v1_unlock_height as u64 <= burn_block_height {
                    return true;
                }
                false
            }
            STXBalance::LockedPoxTwo {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                // if normally unlockable, return true
                if *unlock_height <= burn_block_height {
                    return true;
                }
                // if unlockable due to Stacks 2.2 early unlock
                if v2_unlock_height as u64 <= burn_block_height {
                    return true;
                }
                false
            }
            STXBalance::LockedPoxThree {
                amount_locked,
                unlock_height,
                ..
            } => {
                if *amount_locked == 0 {
                    return false;
                }
                // if normally unlockable, return true
                if *unlock_height <= burn_block_height {
                    return true;
                }
                false
            }
        }
    }

    pub fn can_transfer_at_burn_block(
        &self,
        amount: u128,
        burn_block_height: u64,
        v1_unlock_height: u32,
        v2_unlock_height: u32,
    ) -> bool {
        self.get_available_balance_at_burn_block(
            burn_block_height,
            v1_unlock_height,
            v2_unlock_height,
        ) >= amount
    }
}