Repository navigation
Expand file tree
/
Copy pathtransaction.cpp
More file actions
4092 lines (3944 loc) · 159 KB
/
Copy pathtransaction.cpp
File metadata and controls
4092 lines (3944 loc) · 159 KB
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
/*
This file is part of TON Blockchain Library.
TON Blockchain Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
TON Blockchain Library 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2017-2020 Telegram Systems LLP
*/
#include "block/transaction.h"
#include "block/block.h"
#include "block/block-parse.h"
#include "block/block-auto.h"
#include "crypto/openssl/rand.hpp"
#include "td/utils/bits.h"
#include "td/utils/uint128.h"
#include "ton/ton-shard.h"
#include "vm/vm.h"
#include "td/utils/Timer.h"
namespace {
/**
* Logger that stores the tail of log messages.
*
* @param max_size The size of the buffer. Default is 256.
*/
class StringLoggerTail : public td::LogInterface {
public:
explicit StringLoggerTail(size_t max_size = 256) : buf(max_size, '\0') {}
/**
* Appends a slice of data to the buffer.
*
* @param slice The slice of data to be appended.
*/
void append(td::CSlice slice) override {
if (slice.size() > buf.size()) {
slice.remove_prefix(slice.size() - buf.size());
}
while (!slice.empty()) {
size_t s = std::min(buf.size() - pos, slice.size());
std::copy(slice.begin(), slice.begin() + s, buf.begin() + pos);
pos += s;
if (pos == buf.size()) {
pos = 0;
truncated = true;
}
slice.remove_prefix(s);
}
}
/**
* Retrieves the tail of the log.
*
* @returns The log as std::string.
*/
std::string get_log() const {
if (truncated) {
std::string res = buf;
std::rotate(res.begin(), res.begin() + pos, res.end());
return res;
} else {
return buf.substr(0, pos);
}
}
private:
std::string buf;
size_t pos = 0;
bool truncated = false;
};
}
namespace block {
using td::Ref;
/**
* Looks up a library among public libraries.
*
* @param key A constant bit pointer representing the key of the library to lookup.
*
* @returns A reference to the library cell if found, null otherwise.
*/
Ref<vm::Cell> ComputePhaseConfig::lookup_library(td::ConstBitPtr key) const {
return libraries ? vm::lookup_library_in(key, libraries->get_root_cell()) : Ref<vm::Cell>{};
}
/*
*
* ACCOUNTS
*
*/
/**
* Sets the address of the account.
*
* @param wc The workchain ID of the account.
* @param new_addr The new address of the account.
*
* @returns True if the address was successfully set, false otherwise.
*/
bool Account::set_address(ton::WorkchainId wc, td::ConstBitPtr new_addr) {
workchain = wc;
addr = new_addr;
return true;
}
/**
* Sets the length of anycast prefix length in the account address.
*
* @param new_length The new rewrite lingth.
*
* @returns True if the length was successfully set, False otherwise.
*/
bool Account::set_addr_rewrite_length(int new_length) {
if (new_length < 0 || new_length > 30) {
return false; // invalid value
}
if (addr_rewrite_length_set) {
return addr_rewrite_length == new_length;
} else {
addr_rewrite_length = (unsigned char)new_length;
addr_rewrite_length_set = true;
return true;
}
}
/**
* Checks if the given addr rewrite length is valid for the Account.
*
* @param length The addr rewrite length to be checked.
*
* @returns True if the addr rewrite length is valid, False otherwise.
*/
bool Account::check_addr_rewrite_length(int length) const {
return addr_rewrite_length_set ? (length == addr_rewrite_length) : (length >= 0 && length <= 30);
}
/**
* Parses anycast data of the account address.
*
* Initializes addr_rewrite.
*
* @param cs The cell slice containing partially-parsed account address.
*
* @returns True if parsing was successful, false otherwise.
*/
bool Account::parse_maybe_anycast(vm::CellSlice& cs) {
int t = (int)cs.fetch_ulong(1);
if (t < 0) {
return false;
} else if (!t) {
return set_addr_rewrite_length(0);
}
int depth;
return cs.fetch_uint_leq(30, depth) // anycast_info$_ depth:(#<= 30)
&& depth // { depth >= 1 }
&& cs.fetch_bits_to(addr_rewrite.bits(), depth) // rewrite_pfx:(bits depth)
&& set_addr_rewrite_length(depth);
}
/**
* Stores the anycast information to a serialized account address.
*
* @param cb The vm::CellBuilder object to store the information in.
*
* @returns True if the anycast information was successfully stored, false otherwise.
*/
bool Account::store_maybe_anycast(vm::CellBuilder& cb) const {
if (!addr_rewrite_length_set || !addr_rewrite_length) {
return cb.store_bool_bool(false);
}
return cb.store_bool_bool(true) // just$1
&& cb.store_uint_leq(30, addr_rewrite_length) // depth:(#<= 30)
&& cb.store_bits_bool(addr_rewrite.cbits(), addr_rewrite_length); // rewrite_pfx:(bits depth)
}
/**
* Unpacks the address from a given CellSlice.
*
* @param addr_cs The CellSlice containing the address.
*
* @returns True if the address was successfully unpacked, False otherwise.
*/
bool Account::unpack_address(vm::CellSlice& addr_cs) {
int addr_tag = block::gen::t_MsgAddressInt.get_tag(addr_cs);
int new_wc = ton::workchainInvalid;
switch (addr_tag) {
case block::gen::MsgAddressInt::addr_std:
if (!(addr_cs.advance(2) && parse_maybe_anycast(addr_cs) && addr_cs.fetch_int_to(8, new_wc) &&
addr_cs.fetch_bits_to(addr_orig.bits(), 256) && addr_cs.empty_ext())) {
return false;
}
break;
case block::gen::MsgAddressInt::addr_var:
// cannot appear in masterchain / basechain
return false;
default:
return false;
}
addr_cs.clear();
if (new_wc == ton::workchainInvalid) {
return false;
}
if (workchain == ton::workchainInvalid) {
workchain = new_wc;
addr = addr_orig;
addr.bits().copy_from(addr_rewrite.cbits(), addr_rewrite_length);
} else if (addr_rewrite_length) {
ton::StdSmcAddress new_addr = addr_orig;
new_addr.bits().copy_from(addr_rewrite.cbits(), addr_rewrite_length);
if (new_addr != addr) {
LOG(ERROR) << "error unpacking account " << workchain << ":" << addr.to_hex()
<< " : account header contains different address " << new_addr.to_hex() << " (with splitting depth "
<< (int)addr_rewrite_length << ")";
return false;
}
} else if (addr != addr_orig) {
LOG(ERROR) << "error unpacking account " << workchain << ":" << addr.to_hex()
<< " : account header contains different address " << addr_orig.to_hex();
return false;
}
if (workchain != new_wc) {
LOG(ERROR) << "error unpacking account " << workchain << ":" << addr.to_hex()
<< " : account header contains different workchain " << new_wc;
return false;
}
addr_rewrite = addr.bits(); // initialize all 32 bits of addr_rewrite
if (!addr_rewrite_length) {
my_addr_exact = my_addr;
}
return true;
}
/**
* Unpacks storage information from a CellSlice.
*
* Storage information is serialized using StorageInfo TLB-scheme.
*
* @param cs The CellSlice containing the storage information.
*
* @returns True if the unpacking is successful, false otherwise.
*/
bool Account::unpack_storage_info(vm::CellSlice& cs) {
block::gen::StorageInfo::Record info;
block::gen::StorageUsed::Record used;
if (!tlb::unpack_exact(cs, info) || !tlb::csr_unpack(info.used, used)) {
return false;
}
last_paid = info.last_paid;
if (info.storage_extra.write().fetch_long(3) == 1) {
info.storage_extra->prefetch_bits_to(storage_dict_hash.value_force());
} else {
storage_dict_hash = {};
}
if (info.due_payment->prefetch_ulong(1) == 1) {
vm::CellSlice& cs2 = info.due_payment.write();
cs2.advance(1);
due_payment = block::tlb::t_Grams.as_integer_skip(cs2);
if (due_payment.is_null() || !cs2.empty_ext()) {
return false;
}
} else {
due_payment = td::zero_refint();
}
unsigned long long u = 0;
u |= storage_used.cells = block::tlb::t_VarUInteger_7.as_uint(*used.cells);
u |= storage_used.bits = block::tlb::t_VarUInteger_7.as_uint(*used.bits);
LOG(DEBUG) << "last_paid=" << last_paid << "; cells=" << storage_used.cells << " bits=" << storage_used.bits;
return (u != std::numeric_limits<td::uint64>::max());
}
/**
* Unpacks the state of an Account from a CellSlice.
*
* State is serialized using StateInit TLB-scheme.
* Initializes fixed_prefix_length (from account state - StateInit)
*
* @param cs The CellSlice containing the serialized state.
*
* @returns True if the state was successfully unpacked, False otherwise.
*/
bool Account::unpack_state(vm::CellSlice& cs) {
block::gen::StateInit::Record state;
if (!tlb::unpack_exact(cs, state)) {
return false;
}
fixed_prefix_length = 0;
if (state.fixed_prefix_length->size() == 6) {
fixed_prefix_length = (int)state.fixed_prefix_length->prefetch_ulong(6) - 32;
}
if (state.special->size() > 1) {
int z = (int)state.special->prefetch_ulong(3);
if (z < 0) {
return false;
}
tick = z & 2;
tock = z & 1;
LOG(DEBUG) << "tick=" << tick << ", tock=" << tock;
}
code = state.code->prefetch_ref();
data = state.data->prefetch_ref();
library = orig_library = state.library->prefetch_ref();
return true;
}
/**
* Computes the address of the account.
*
* @param force If set to true, the address will be recomputed even if it already exists.
*
* @returns True if the address was successfully computed, false otherwise.
*/
bool Account::compute_my_addr(bool force) {
if (!force && my_addr.not_null() && my_addr_exact.not_null()) {
return true;
}
if (workchain == ton::workchainInvalid) {
my_addr.clear();
return false;
}
vm::CellBuilder cb;
Ref<vm::Cell> cell, cell2;
if (workchain >= -128 && workchain < 127) {
if (!(cb.store_long_bool(2, 2) // addr_std$10
&& store_maybe_anycast(cb) // anycast:(Maybe Anycast)
&& cb.store_long_rchk_bool(workchain, 8) // workchain_id:int8
&& cb.store_bits_bool(addr_orig) // addr:bits256
&& cb.finalize_to(cell) && cb.store_long_bool(4, 3) // addr_std$10 anycast:(Maybe Anycast)
&& cb.store_long_rchk_bool(workchain, 8) // workchain_id:int8
&& cb.store_bits_bool(addr) // addr:bits256
&& cb.finalize_to(cell2))) {
return false;
}
} else {
if (!(cb.store_long_bool(3, 2) // addr_var$11
&& store_maybe_anycast(cb) // anycast:(Maybe Anycast)
&& cb.store_long_bool(256, 9) // addr_len:(## 9)
&& cb.store_long_rchk_bool(workchain, 32) // workchain_id:int32
&& cb.store_bits_bool(addr_orig) // addr:(bits addr_len)
&& cb.finalize_to(cell) && cb.store_long_bool(6, 3) // addr_var$11 anycast:(Maybe Anycast)
&& cb.store_long_bool(256, 9) // addr_len:(## 9)
&& cb.store_long_rchk_bool(workchain, 32) // workchain_id:int32
&& cb.store_bits_bool(addr) // addr:(bits addr_len)
&& cb.finalize_to(cell2))) {
return false;
}
}
my_addr = load_cell_slice_ref(std::move(cell));
my_addr_exact = load_cell_slice_ref(std::move(cell2));
return true;
}
/**
* Computes the address of the Account.
*
* Legacy (used only if global_version < 10).
*
* @param tmp_addr A reference to the CellSlice for the result.
* @param fixed_prefix_length The fixed prefix length for the address.
* @param orig_addr_rewrite Address prefix of length fixed_prefix_length.
*
* @returns True if the address was successfully computed, false otherwise.
*/
bool Account::recompute_tmp_addr(Ref<vm::CellSlice>& tmp_addr, int fixed_prefix_length,
td::ConstBitPtr orig_addr_rewrite) const {
if (!fixed_prefix_length && my_addr_exact.not_null()) {
tmp_addr = my_addr_exact;
return true;
}
if (fixed_prefix_length == addr_rewrite_length && my_addr.not_null()) {
tmp_addr = my_addr;
return true;
}
if (fixed_prefix_length < 0 || fixed_prefix_length > 30) {
return false;
}
vm::CellBuilder cb;
bool std = (workchain >= -128 && workchain < 128);
if (!cb.store_long_bool(std ? 2 : 3, 2)) { // addr_std$10 or addr_var$11
return false;
}
if (!fixed_prefix_length) {
if (!cb.store_bool_bool(false)) { // anycast:(Maybe Anycast)
return false;
}
} else if (!(cb.store_bool_bool(true) // just$1
&& cb.store_long_bool(fixed_prefix_length, 5) // depth:(#<= 30)
&& cb.store_bits_bool(addr.bits(), fixed_prefix_length))) { // rewrite_pfx:(bits depth)
return false;
}
if (std) {
if (!cb.store_long_rchk_bool(workchain, 8)) { // workchain:int8
return false;
}
} else if (!(cb.store_long_bool(256, 9) // addr_len:(## 9)
&& cb.store_long_bool(workchain, 32))) { // workchain:int32
return false;
}
Ref<vm::Cell> cell;
return cb.store_bits_bool(orig_addr_rewrite, fixed_prefix_length) // address:(bits addr_len) or bits256
&& cb.store_bits_bool(addr.bits() + fixed_prefix_length, 256 - fixed_prefix_length) && cb.finalize_to(cell) &&
(tmp_addr = vm::load_cell_slice_ref(std::move(cell))).not_null();
}
/**
* Sets address rewriting info for a newly-activated account.
*
* @param rewrite_length The fixed prefix length for the account address.
* @param orig_addr_rewrite Address prefix of length fixed_prefix_length.
*
* @returns True if the rewriting info was successfully set, false otherwise.
*/
bool Account::init_rewrite_addr(int rewrite_length, td::ConstBitPtr orig_addr_rewrite) {
if (addr_rewrite_length_set || !set_addr_rewrite_length(rewrite_length)) {
return false;
}
addr_orig = addr;
addr_rewrite = addr.bits();
addr_orig.bits().copy_from(orig_addr_rewrite, rewrite_length);
return compute_my_addr(true);
}
/**
* Unpacks the account information from the provided CellSlice.
*
* Used to unpack previously existing accounts.
*
* @param shard_account The ShardAccount to unpack.
* @param now The current Unix time.
* @param special Flag indicating if the account is special.
*
* @returns True if the unpacking is successful, false otherwise.
*/
bool Account::unpack(Ref<vm::CellSlice> shard_account, ton::UnixTime now, bool special) {
LOG(DEBUG) << "unpacking " << (special ? "special " : "") << "account " << addr.to_hex();
if (shard_account.is_null()) {
LOG(ERROR) << "account " << addr.to_hex() << " does not have a valid ShardAccount to unpack";
return false;
}
if (verbosity > 2) {
FLOG(INFO) {
shard_account->print_rec(sb, 2);
block::gen::t_ShardAccount.print(sb, shard_account);
};
}
block::gen::ShardAccount::Record acc_info;
if (!(block::tlb::t_ShardAccount.validate_csr(shard_account) && tlb::unpack_exact(shard_account.write(), acc_info))) {
LOG(ERROR) << "account " << addr.to_hex() << " state is invalid";
return false;
}
last_trans_lt_ = acc_info.last_trans_lt;
last_trans_hash_ = acc_info.last_trans_hash;
now_ = now;
auto account = std::move(acc_info.account);
total_state = orig_total_state = account;
auto acc_cs = load_cell_slice(std::move(account));
if (block::gen::t_Account.get_tag(acc_cs) == block::gen::Account::account_none) {
is_special = special;
return acc_cs.size_ext() == 1 && init_new(now);
}
block::gen::Account::Record_account acc;
block::gen::AccountStorage::Record storage;
if (!(tlb::unpack_exact(acc_cs, acc) && (my_addr = acc.addr).not_null() && unpack_address(acc.addr.write()) &&
compute_my_addr() && unpack_storage_info(acc.storage_stat.write()) &&
tlb::csr_unpack(this->storage = std::move(acc.storage), storage) &&
std::max(storage.last_trans_lt, 1ULL) > acc_info.last_trans_lt && balance.unpack(std::move(storage.balance)))) {
return false;
}
is_special = special;
last_trans_end_lt_ = storage.last_trans_lt;
switch (block::gen::t_AccountState.get_tag(*storage.state)) {
case block::gen::AccountState::account_uninit:
status = orig_status = acc_uninit;
state_hash = addr;
forget_addr_rewrite_length();
break;
case block::gen::AccountState::account_frozen:
status = orig_status = acc_frozen;
if (!storage.state->have(2 + 256)) {
return false;
}
state_hash = storage.state->data_bits() + 2;
break;
case block::gen::AccountState::account_active:
status = orig_status = acc_active;
if (storage.state.write().fetch_ulong(1) != 1) {
return false;
}
inner_state = storage.state;
if (!unpack_state(storage.state.write())) {
return false;
}
state_hash.clear();
break;
default:
return false;
}
LOG(DEBUG) << "end of Account.unpack() for " << workchain << ":" << addr.to_hex()
<< " (balance = " << balance.to_str() << " ; last_trans_lt = " << last_trans_lt_ << ".."
<< last_trans_end_lt_ << ")";
return true;
}
/**
* Initializes a new Account object.
*
* @param now The current Unix time.
*
* @returns True if the initialization is successful, false otherwise.
*/
bool Account::init_new(ton::UnixTime now) {
// only workchain and addr are initialized at this point
if (workchain == ton::workchainInvalid) {
return false;
}
addr_orig = addr;
addr_rewrite = addr.cbits();
last_trans_lt_ = last_trans_end_lt_ = 0;
last_trans_hash_.set_zero();
now_ = now;
last_paid = 0;
storage_used = {};
storage_dict_hash = {};
due_payment = td::zero_refint();
balance.set_zero();
if (my_addr_exact.is_null()) {
vm::CellBuilder cb;
if (workchain >= -128 && workchain < 128) {
CHECK(cb.store_long_bool(4, 3) // addr_std$10 anycast:(Maybe Anycast)
&& cb.store_long_rchk_bool(workchain, 8) // workchain:int8
&& cb.store_bits_bool(addr)); // address:bits256
} else {
CHECK(cb.store_long_bool(0xd00, 12) // addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9)
&& cb.store_long_rchk_bool(workchain, 32) // workchain:int32
&& cb.store_bits_bool(addr)); // address:(bits addr_len)
}
my_addr_exact = load_cell_slice_ref(cb.finalize());
}
if (my_addr.is_null()) {
my_addr = my_addr_exact;
}
if (total_state.is_null()) {
vm::CellBuilder cb;
CHECK(cb.store_long_bool(0, 1) // account_none$0 = Account
&& cb.finalize_to(total_state));
orig_total_state = total_state;
}
state_hash = addr_orig;
status = orig_status = acc_nonexist;
addr_rewrite_length_set = false;
return true;
}
/**
* Resets the fixed prefix length of the account.
*
* @returns True if the fixed prefix length was successfully reset, false otherwise.
*/
bool Account::forget_addr_rewrite_length() {
addr_rewrite_length_set = false;
addr_rewrite_length = 0;
addr_orig = addr;
my_addr = my_addr_exact;
addr_rewrite = addr.bits();
return true;
}
/**
* Deactivates the account.
*
* @returns True if the account was successfully deactivated, false otherwise.
*/
bool Account::deactivate() {
if (status == acc_active) {
return false;
}
// forget special (tick/tock) info
tick = tock = false;
fixed_prefix_length = 0;
if (status == acc_nonexist || status == acc_uninit) {
// forget fixed prefix length and address rewriting info
forget_addr_rewrite_length();
// forget specific state hash for deleted or uninitialized accounts (revert to addr)
state_hash = addr;
}
// forget code and data (only active accounts remember these)
code.clear();
data.clear();
library.clear();
// if deleted, balance must be zero
if (status == acc_nonexist && !balance.is_zero()) {
return false;
}
return true;
}
/**
* Checks if the account belongs to a specific shard.
*
* @param shard The shard to check against.
*
* @returns True if the account belongs to the shard, False otherwise.
*/
bool Account::belongs_to_shard(ton::ShardIdFull shard) const {
return workchain == shard.workchain && ton::shard_is_ancestor(shard.shard, addr);
}
/**
* Adds the partial storage payment to the total sum.
*
* @param payment The total sum to be updated.
* @param delta The time delta for which the payment is calculated.
* @param prices The storage prices.
* @param storage_used Account storage statistics.
* @param is_mc A flag indicating whether the account is in the masterchain.
*/
void add_partial_storage_payment(td::BigInt256& payment, ton::UnixTime delta, const block::StoragePrices& prices,
const StorageUsed& storage_used, bool is_mc) {
td::BigInt256 c{(long long)storage_used.cells}, b{(long long)storage_used.bits};
if (is_mc) {
// storage.cells * prices.mc_cell_price + storage.bits * prices.mc_bit_price;
c.mul_short(prices.mc_cell_price);
b.mul_short(prices.mc_bit_price);
} else {
// storage.cells * prices.cell_price + storage.bits * prices.bit_price;
c.mul_short(prices.cell_price);
b.mul_short(prices.bit_price);
}
b += c;
b.mul_short(delta).normalize();
CHECK(b.sgn() >= 0);
payment += b;
}
/**
* Computes the storage fees based on the given parameters.
*
* @param now The current Unix time.
* @param pricing The vector of storage prices.
* @param storage_used Account storage statistics.
* @param last_paid The Unix time when the last payment was made.
* @param is_special A flag indicating if the account is special.
* @param is_masterchain A flag indicating if the account is in the masterchain.
*
* @returns The computed storage fees as RefInt256.
*/
td::RefInt256 StoragePrices::compute_storage_fees(ton::UnixTime now, const std::vector<block::StoragePrices>& pricing,
const StorageUsed& storage_used, ton::UnixTime last_paid,
bool is_special, bool is_masterchain) {
if (now <= last_paid || !last_paid || is_special || pricing.empty() || now <= pricing[0].valid_since) {
return td::zero_refint();
}
std::size_t n = pricing.size(), i = n;
while (i && pricing[i - 1].valid_since > last_paid) {
--i;
}
if (i) {
--i;
}
ton::UnixTime upto = std::max(last_paid, pricing[0].valid_since);
td::RefInt256 total{true, 0};
for (; i < n && upto < now; i++) {
ton::UnixTime valid_until = (i < n - 1 ? std::min(now, pricing[i + 1].valid_since) : now);
if (upto < valid_until) {
assert(upto >= pricing[i].valid_since);
add_partial_storage_payment(total.unique_write(), valid_until - upto, pricing[i], storage_used, is_masterchain);
}
upto = valid_until;
}
return td::rshift(total, 16, 1); // divide by 2^16 with ceil rounding to obtain nanograms
}
/**
* Computes the storage fees for the account.
*
* @param now The current Unix time.
* @param pricing The vector of storage prices.
*
* @returns The computed storage fees as RefInt256.
*/
td::RefInt256 Account::compute_storage_fees(ton::UnixTime now, const std::vector<block::StoragePrices>& pricing) const {
return StoragePrices::compute_storage_fees(now, pricing, storage_used, last_paid, is_special, is_masterchain());
}
namespace transaction {
/**
* Constructs a new Transaction object.
*
* @param _account The Account object.
* @param ttype The type of the transaction (see transaction.cpp#309).
* @param req_start_lt The minimal logical time of the transaction.
* @param _now The current Unix time.
* @param _inmsg The input message that caused the transaction.
*
* @returns None
*/
Transaction::Transaction(const Account& _account, int ttype, ton::LogicalTime req_start_lt, ton::UnixTime _now,
Ref<vm::Cell> _inmsg)
: trans_type(ttype)
, is_first(_account.transactions.empty())
, new_tick(_account.tick)
, new_tock(_account.tock)
, new_fixed_prefix_length(_account.fixed_prefix_length)
, now(_now)
, account(_account)
, my_addr(_account.my_addr)
, my_addr_exact(_account.my_addr_exact)
, balance(_account.balance)
, original_balance(_account.balance)
, due_payment(_account.due_payment)
, last_paid(_account.last_paid)
, new_code(_account.code)
, new_data(_account.data)
, new_library(_account.library)
, in_msg(std::move(_inmsg)) {
start_lt = std::max(req_start_lt, account.last_trans_end_lt_);
end_lt = start_lt + 1;
acc_status = (account.status == Account::acc_nonexist ? Account::acc_uninit : account.status);
if (acc_status == Account::acc_frozen) {
frozen_hash = account.state_hash;
}
}
/**
* Unpacks the input message of a transaction.
*
* @param ihr_delivered A boolean indicating whether the message was delivered using IHR (Instant Hypercube Routing).
* @param cfg Action phase configuration.
*
* @returns A boolean indicating whether the unpacking was successful.
*/
bool Transaction::unpack_input_msg(bool ihr_delivered, const ActionPhaseConfig* cfg) {
if (in_msg.is_null() || in_msg_type) {
return false;
}
if (verbosity > 2) {
FLOG(INFO) {
sb << "unpacking inbound message for a new transaction: ";
block::gen::t_Message_Any.print_ref(sb, in_msg);
load_cell_slice(in_msg).print_rec(sb);
};
}
auto cs = vm::load_cell_slice(in_msg);
int tag = gen::t_CommonMsgInfo.get_tag(cs);
switch (tag) {
case gen::CommonMsgInfo::int_msg_info: {
if (!(tlb::unpack(cs, in_msg_info) && msg_balance_remaining.unpack(in_msg_info.value))) {
return false;
}
if (in_msg_info.ihr_disabled && ihr_delivered) {
return false;
}
bounce_enabled = in_msg_info.bounce;
in_msg_type = 1;
td::RefInt256 ihr_fee = block::tlb::t_Grams.as_integer(in_msg_info.ihr_fee);
if (ihr_delivered) {
in_fwd_fee = std::move(ihr_fee);
} else {
in_fwd_fee = td::zero_refint();
msg_balance_remaining += std::move(ihr_fee);
}
if (in_msg_info.created_lt >= start_lt) {
start_lt = in_msg_info.created_lt + 1;
end_lt = start_lt + 1;
}
// ...
break;
}
case gen::CommonMsgInfo::ext_in_msg_info: {
gen::CommonMsgInfo::Record_ext_in_msg_info info;
if (!tlb::unpack(cs, info)) {
return false;
}
in_msg_info.ihr_disabled = in_msg_info.bounce = in_msg_info.bounced = false;
in_msg_info.src = info.src;
in_msg_info.dest = info.dest;
in_msg_info.created_at = in_msg_info.created_lt = 0;
if (cfg->disable_anycast) {
// Check that dest is addr_std without anycast
gen::MsgAddressInt::Record_addr_std rec;
if (!gen::csr_unpack(info.dest, rec)) {
LOG(DEBUG) << "destination address of the external message is not a valid addr_std";
return false;
}
if (rec.anycast->size() > 1) {
LOG(DEBUG) << "destination address of the external message is an anycast address";
return false;
}
}
in_msg_type = 2;
in_msg_extern = true;
// compute forwarding fees for this external message
vm::CellStorageStat sstat; // for message size
auto cell_info = sstat.compute_used_storage(cs).move_as_ok(); // message body
sstat.bits -= cs.size(); // bits in the root cells are free
sstat.cells--; // the root cell itself is not counted as a cell
LOG(DEBUG) << "storage paid for a message: " << sstat.cells << " cells, " << sstat.bits << " bits";
if (sstat.bits > cfg->size_limits.max_msg_bits || sstat.cells > cfg->size_limits.max_msg_cells) {
LOG(DEBUG) << "inbound external message too large, invalid";
return false;
}
if (cell_info.max_merkle_depth > max_allowed_merkle_depth) {
LOG(DEBUG) << "inbound external message has too big merkle depth, invalid";
return false;
}
// fetch message pricing info
CHECK(cfg);
const MsgPrices& msg_prices = cfg->fetch_msg_prices(account.is_masterchain());
// compute forwarding fees
auto fees_c = msg_prices.compute_fwd_ihr_fees(sstat.cells, sstat.bits, true);
LOG(DEBUG) << "computed fwd fees = " << fees_c.first << " + " << fees_c.second;
if (account.is_special) {
LOG(DEBUG) << "computed fwd fees set to zero for special account";
fees_c.first = fees_c.second = 0;
}
in_fwd_fee = td::make_refint(fees_c.first);
if (balance.grams < in_fwd_fee) {
LOG(DEBUG) << "cannot pay for importing this external message";
return false;
}
// (tentatively) debit account for importing this external message
balance -= in_fwd_fee;
msg_balance_remaining.set_zero(); // external messages cannot carry value
// ...
break;
}
default:
return false;
}
// init:(Maybe (Either StateInit ^StateInit))
switch ((int)cs.prefetch_ulong(2)) {
case 2: { // (just$1 (left$0 _:StateInit ))
Ref<vm::CellSlice> state_init;
vm::CellBuilder cb;
if (!(cs.advance(2) && block::gen::t_StateInit.fetch_to(cs, state_init) &&
cb.append_cellslice_bool(std::move(state_init)) && cb.finalize_to(in_msg_state) &&
block::gen::t_StateInitWithLibs.validate_ref(in_msg_state))) {
LOG(DEBUG) << "cannot parse StateInit in inbound message";
return false;
}
break;
}
case 3: { // (just$1 (right$1 _:^StateInit ))
if (!(cs.advance(2) && cs.fetch_ref_to(in_msg_state) &&
block::gen::t_StateInitWithLibs.validate_ref(in_msg_state))) {
LOG(DEBUG) << "cannot parse ^StateInit in inbound message";
return false;
}
break;
}
default: // nothing$0
if (!cs.advance(1)) {
LOG(DEBUG) << "invalid init field in an inbound message";
return false;
}
}
// body:(Either X ^X)
switch ((int)cs.fetch_ulong(1)) {
case 0: // left$0 _:X
in_msg_body = Ref<vm::CellSlice>{true, cs};
break;
case 1: // right$1 _:^X
if (cs.size_ext() != 0x10000) {
LOG(DEBUG) << "body of an inbound message is not represented by exactly one reference";
return false;
}
in_msg_body = load_cell_slice_ref(cs.prefetch_ref());
break;
default:
LOG(DEBUG) << "invalid body field in an inbound message";
return false;
}
total_fees += in_fwd_fee;
if (account.workchain == ton::masterchainId && cfg->mc_blackhole_addr &&
cfg->mc_blackhole_addr.value() == account.addr) {
blackhole_burned.grams = msg_balance_remaining.grams;
msg_balance_remaining.grams = td::zero_refint();
LOG(DEBUG) << "Burning " << blackhole_burned.grams << " nanoton (blackhole address)";
}
return true;
}
/**
* Prepares the storage phase of a transaction.
*
* @param cfg The configuration for the storage phase.
* @param force_collect Flag indicating whether to collect fees for frozen accounts.
* @param adjust_msg_value Flag indicating whether to adjust the message value if the account balance becomes less than the message balance.
*
* @returns True if the storage phase was successfully prepared, false otherwise.
*/
bool Transaction::prepare_storage_phase(const StoragePhaseConfig& cfg, bool force_collect, bool adjust_msg_value) {
if (now < account.last_paid) {
return false;
}
auto to_pay = account.compute_storage_fees(now, *(cfg.pricing)) + due_payment;
if (to_pay.not_null() && sgn(to_pay) < 0) {
return false;
}
auto res = std::make_unique<StoragePhase>();
res->is_special = account.is_special;
last_paid = res->last_paid_updated = (res->is_special ? 0 : now);
if (to_pay.is_null() || sgn(to_pay) == 0) {
res->fees_collected = res->fees_due = td::zero_refint();
} else if (to_pay <= balance.grams) {
res->fees_collected = to_pay;
res->fees_due = td::zero_refint();
balance -= std::move(to_pay);
if (cfg.global_version >= 7) {
due_payment = td::zero_refint();
}
} else if (acc_status == Account::acc_frozen && !force_collect && to_pay < cfg.delete_due_limit) {
// do not collect fee
res->last_paid_updated = (res->is_special ? 0 : account.last_paid);
res->fees_collected = res->fees_due = td::zero_refint();
} else {
res->fees_collected = balance.grams;
res->fees_due = std::move(to_pay) - std::move(balance.grams);
balance.grams = td::zero_refint();
if (!res->is_special) {
auto total_due = res->fees_due;
switch (acc_status) {
case Account::acc_uninit:
case Account::acc_frozen:
if (total_due > cfg.delete_due_limit && balance.extra.is_null()) {
// Keeping accounts with non-null extras is a temporary measure before implementing proper collection of
// extracurrencies from deleted accounts
res->deleted = true;
acc_status = Account::acc_deleted;
if (balance.extra.not_null()) {
// collect extra currencies as a fee
total_fees += block::CurrencyCollection{0, std::move(balance.extra)};
balance.extra.clear();
}
}
break;
case Account::acc_active:
if (total_due > cfg.freeze_due_limit) {
res->frozen = true;
was_frozen = true;
acc_status = Account::acc_frozen;
}
break;
}
if (cfg.enable_due_payment) {
due_payment = total_due;
}
}
}
if (adjust_msg_value && msg_balance_remaining.grams > balance.grams) {
msg_balance_remaining.grams = balance.grams;
}
total_fees += res->fees_collected;
storage_phase = std::move(res);
return true;
}
/**
* Prepares the credit phase of a transaction.
*
* This function creates a CreditPhase object and performs the necessary calculations
* to determine the amount to be credited in the credit phase. It updates the due payment,
* credit, balance, and total fees accordingly.
*
* @returns True if the credit phase is prepared successfully, false otherwise.
*/
bool Transaction::prepare_credit_phase() {
credit_phase = std::make_unique<CreditPhase>();
// Due payment is only collected in storage phase.
// For messages with bounce flag, contract always receives the amount specified in message
// auto collected = std::min(msg_balance_remaining.grams, due_payment);
// credit_phase->due_fees_collected = collected;
// due_payment -= collected;
// credit_phase->credit = msg_balance_remaining -= collected;
credit_phase->due_fees_collected = td::zero_refint();
credit_phase->credit = msg_balance_remaining;
if (!msg_balance_remaining.is_valid()) {
LOG(ERROR) << "cannot compute the amount to be credited in the credit phase of transaction";
return false;
}
// NB: msg_balance_remaining may be deducted from balance later during bounce phase
balance += msg_balance_remaining;
if (!balance.is_valid()) {
LOG(ERROR) << "cannot credit currency collection to account";
return false;
}
// total_fees += std::move(collected);
return true;
}