-
Notifications
You must be signed in to change notification settings - Fork 672
/
transaction.cpp
2634 lines (2509 loc) · 103 KB
/
transaction.cpp
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 {
class StringLoggerTail : public td::LogInterface {
public:
explicit StringLoggerTail(size_t max_size = 256) : buf(max_size, '\0') {}
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);
}
}
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;
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
*
*/
bool Account::set_address(ton::WorkchainId wc, td::ConstBitPtr new_addr) {
workchain = wc;
addr = new_addr;
return true;
}
bool Account::set_split_depth(int new_split_depth) {
if (new_split_depth < 0 || new_split_depth > 30) {
return false; // invalid value for split_depth
}
if (split_depth_set_) {
return split_depth_ == new_split_depth;
} else {
split_depth_ = (unsigned char)new_split_depth;
split_depth_set_ = true;
return true;
}
}
bool Account::check_split_depth(int split_depth) const {
return split_depth_set_ ? (split_depth == split_depth_) : (split_depth >= 0 && split_depth <= 30);
}
// initializes split_depth and addr_rewrite
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_split_depth(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_split_depth(depth);
}
bool Account::store_maybe_anycast(vm::CellBuilder& cb) const {
if (!split_depth_set_ || !split_depth_) {
return cb.store_bool_bool(false);
}
return cb.store_bool_bool(true) // just$1
&& cb.store_uint_leq(30, split_depth_) // depth:(#<= 30)
&& cb.store_bits_bool(addr_rewrite.cbits(), split_depth_); // rewrite_pfx:(bits depth)
}
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(), split_depth_);
} else if (split_depth_) {
ton::StdSmcAddress new_addr = addr_orig;
new_addr.bits().copy_from(addr_rewrite.cbits(), split_depth_);
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)split_depth_ << ")";
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 (!split_depth_) {
my_addr_exact = my_addr;
}
return true;
}
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.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_stat.cells = block::tlb::t_VarUInteger_7.as_uint(*used.cells);
u |= storage_stat.bits = block::tlb::t_VarUInteger_7.as_uint(*used.bits);
u |= storage_stat.public_cells = block::tlb::t_VarUInteger_7.as_uint(*used.public_cells);
LOG(DEBUG) << "last_paid=" << last_paid << "; cells=" << storage_stat.cells << " bits=" << storage_stat.bits
<< " public_cells=" << storage_stat.public_cells;
return (u != std::numeric_limits<td::uint64>::max());
}
// initializes split_depth (from account state - StateInit)
bool Account::unpack_state(vm::CellSlice& cs) {
block::gen::StateInit::Record state;
if (!tlb::unpack_exact(cs, state)) {
return false;
}
int sd = 0;
if (state.split_depth->size() == 6) {
sd = (int)state.split_depth->prefetch_ulong(6) - 32;
}
if (!set_split_depth(sd)) {
return false;
}
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;
}
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;
}
bool Account::recompute_tmp_addr(Ref<vm::CellSlice>& tmp_addr, int split_depth,
td::ConstBitPtr orig_addr_rewrite) const {
if (!split_depth && my_addr_exact.not_null()) {
tmp_addr = my_addr_exact;
return true;
}
if (split_depth == split_depth_ && my_addr.not_null()) {
tmp_addr = my_addr;
return true;
}
if (split_depth < 0 || split_depth > 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 (!split_depth) {
if (!cb.store_bool_bool(false)) { // anycast:(Maybe Anycast)
return false;
}
} else if (!(cb.store_bool_bool(true) // just$1
&& cb.store_long_bool(split_depth, 5) // depth:(#<= 30)
&& cb.store_bits_bool(addr.bits(), split_depth))) { // 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, split_depth) // address:(bits addr_len) or bits256
&& cb.store_bits_bool(addr.bits() + split_depth, 256 - split_depth) && cb.finalize_to(cell) &&
(tmp_addr = vm::load_cell_slice_ref(std::move(cell))).not_null();
}
bool Account::init_rewrite_addr(int split_depth, td::ConstBitPtr orig_addr_rewrite) {
if (split_depth_set_ || !set_split_depth(split_depth)) {
return false;
}
addr_orig = addr;
addr_rewrite = addr.bits();
addr_orig.bits().copy_from(orig_addr_rewrite, split_depth);
return compute_my_addr(true);
}
// used to unpack previously existing accounts
bool Account::unpack(Ref<vm::CellSlice> shard_account, Ref<vm::CellSlice> extra, 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) {
shard_account->print_rec(std::cerr, 2);
block::gen::t_ShardAccount.print(std::cerr, *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_split_depth();
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;
}
// used to initialize new accounts
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_stat.clear();
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;
split_depth_set_ = false;
return true;
}
bool Account::forget_split_depth() {
split_depth_set_ = false;
split_depth_ = 0;
addr_orig = addr;
my_addr = my_addr_exact;
addr_rewrite = addr.bits();
return true;
}
bool Account::deactivate() {
if (status == acc_active) {
return false;
}
// forget special (tick/tock) info
tick = tock = false;
if (status == acc_nonexist || status == acc_uninit) {
// forget split depth and address rewriting info
forget_split_depth();
// 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;
}
bool Account::belongs_to_shard(ton::ShardIdFull shard) const {
return workchain == shard.workchain && ton::shard_is_ancestor(shard.shard, addr);
}
void add_partial_storage_payment(td::BigInt256& payment, ton::UnixTime delta, const block::StoragePrices& prices,
const vm::CellStorageStat& storage, bool is_mc) {
td::BigInt256 c{(long long)storage.cells}, b{(long long)storage.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);
CHECK(b.sgn() >= 0);
payment += b;
}
td::RefInt256 StoragePrices::compute_storage_fees(ton::UnixTime now, const std::vector<block::StoragePrices>& pricing,
const vm::CellStorageStat& storage_stat, 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 {};
}
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_stat, is_masterchain);
}
upto = valid_until;
}
total.unique_write().rshift(16, 1); // divide by 2^16 with ceil rounding to obtain nanograms
return total;
}
td::RefInt256 Account::compute_storage_fees(ton::UnixTime now, const std::vector<block::StoragePrices>& pricing) const {
return StoragePrices::compute_storage_fees(now, pricing, storage_stat, last_paid, is_special, is_masterchain());
}
namespace transaction {
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)
, 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;
}
}
bool Transaction::unpack_input_msg(bool ihr_delivered, const ActionPhaseConfig* cfg) {
if (in_msg.is_null() || in_msg_type) {
return false;
}
if (verbosity > 2) {
fprintf(stderr, "unpacking inbound message for a new transaction: ");
block::gen::t_Message_Any.print_ref(std::cerr, in_msg);
load_cell_slice(in_msg).print_rec(std::cerr);
}
auto cs = vm::load_cell_slice(in_msg);
int tag = block::gen::t_CommonMsgInfo.get_tag(cs);
Ref<vm::CellSlice> src_addr, dest_addr;
switch (tag) {
case block::gen::CommonMsgInfo::int_msg_info: {
block::gen::CommonMsgInfo::Record_int_msg_info info;
if (!(tlb::unpack(cs, info) && msg_balance_remaining.unpack(std::move(info.value)))) {
return false;
}
if (info.ihr_disabled && ihr_delivered) {
return false;
}
bounce_enabled = info.bounce;
src_addr = std::move(info.src);
dest_addr = std::move(info.dest);
in_msg_type = 1;
td::RefInt256 ihr_fee = block::tlb::t_Grams.as_integer(std::move(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 (info.created_lt >= start_lt) {
start_lt = info.created_lt + 1;
end_lt = start_lt + 1;
}
// ...
break;
}
case block::gen::CommonMsgInfo::ext_in_msg_info: {
block::gen::CommonMsgInfo::Record_ext_in_msg_info info;
if (!tlb::unpack(cs, info)) {
return false;
}
src_addr = std::move(info.src);
dest_addr = std::move(info.dest);
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_StateInit.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_StateInit.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;
return true;
}
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));
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);
} else if (acc_status == Account::acc_frozen && !force_collect && to_pay + due_payment < 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 + due_payment;
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 (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;
}
bool Transaction::prepare_credit_phase() {
credit_phase = std::make_unique<CreditPhase>();
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;
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;
}
} // namespace transaction
bool ComputePhaseConfig::parse_GasLimitsPrices(Ref<vm::Cell> cell, td::RefInt256& freeze_due_limit,
td::RefInt256& delete_due_limit) {
return cell.not_null() &&
parse_GasLimitsPrices(vm::load_cell_slice_ref(std::move(cell)), freeze_due_limit, delete_due_limit);
}
bool ComputePhaseConfig::parse_GasLimitsPrices(Ref<vm::CellSlice> cs, td::RefInt256& freeze_due_limit,
td::RefInt256& delete_due_limit) {
if (cs.is_null()) {
return false;
}
block::gen::GasLimitsPrices::Record_gas_flat_pfx flat;
if (tlb::csr_unpack(cs, flat)) {
return parse_GasLimitsPrices_internal(std::move(flat.other), freeze_due_limit, delete_due_limit,
flat.flat_gas_limit, flat.flat_gas_price);
} else {
return parse_GasLimitsPrices_internal(std::move(cs), freeze_due_limit, delete_due_limit);
}
}
bool ComputePhaseConfig::parse_GasLimitsPrices_internal(Ref<vm::CellSlice> cs, td::RefInt256& freeze_due_limit,
td::RefInt256& delete_due_limit, td::uint64 _flat_gas_limit,
td::uint64 _flat_gas_price) {
auto f = [&](const auto& r, td::uint64 spec_limit) {
gas_limit = r.gas_limit;
special_gas_limit = spec_limit;
gas_credit = r.gas_credit;
gas_price = r.gas_price;
freeze_due_limit = td::make_refint(r.freeze_due_limit);
delete_due_limit = td::make_refint(r.delete_due_limit);
};
block::gen::GasLimitsPrices::Record_gas_prices_ext rec;
if (tlb::csr_unpack(cs, rec)) {
f(rec, rec.special_gas_limit);
} else {
block::gen::GasLimitsPrices::Record_gas_prices rec0;
if (tlb::csr_unpack(std::move(cs), rec0)) {
f(rec0, rec0.gas_limit);
} else {
return false;
}
}
flat_gas_limit = _flat_gas_limit;
flat_gas_price = _flat_gas_price;
compute_threshold();
return true;
}
bool ComputePhaseConfig::is_address_suspended(ton::WorkchainId wc, td::Bits256 addr) const {
if (!suspended_addresses) {
return false;
}
try {
vm::CellBuilder key;
key.store_long_bool(wc, 32);
key.store_bits_bool(addr);
return !suspended_addresses->lookup(key.data_bits(), 288).is_null();
} catch (vm::VmError) {
return false;
}
}
void ComputePhaseConfig::compute_threshold() {
gas_price256 = td::make_refint(gas_price);
if (gas_limit > flat_gas_limit) {
max_gas_threshold =
td::rshift(gas_price256 * (gas_limit - flat_gas_limit), 16, 1) + td::make_bigint(flat_gas_price);
} else {
max_gas_threshold = td::make_refint(flat_gas_price);
}
}
td::uint64 ComputePhaseConfig::gas_bought_for(td::RefInt256 nanograms) const {
if (nanograms.is_null() || sgn(nanograms) < 0) {
return 0;
}
if (nanograms >= max_gas_threshold) {
return gas_limit;
}
if (nanograms < flat_gas_price) {
return 0;
}
auto res = td::div((std::move(nanograms) - flat_gas_price) << 16, gas_price256);
return res->to_long() + flat_gas_limit;
}
td::RefInt256 ComputePhaseConfig::compute_gas_price(td::uint64 gas_used) const {
return gas_used <= flat_gas_limit ? td::make_refint(flat_gas_price)
: td::rshift(gas_price256 * (gas_used - flat_gas_limit), 16, 1) + flat_gas_price;
}
namespace transaction {
bool Transaction::compute_gas_limits(ComputePhase& cp, const ComputePhaseConfig& cfg) {
// Compute gas limits
if (account.is_special) {
cp.gas_max = cfg.special_gas_limit;
} else {
cp.gas_max = cfg.gas_bought_for(balance.grams);
}
cp.gas_credit = 0;
if (trans_type != tr_ord) {
// may use all gas that can be bought using remaining balance
cp.gas_limit = cp.gas_max;
} else {
// originally use only gas bought using remaining message balance
// if the message is "accepted" by the smart contract, the gas limit will be set to gas_max
cp.gas_limit = std::min(cfg.gas_bought_for(msg_balance_remaining.grams), cp.gas_max);
if (!block::tlb::t_Message.is_internal(in_msg)) {
// external messages carry no balance, give them some credit to check whether they are accepted
cp.gas_credit = std::min(cfg.gas_credit, cp.gas_max);
}
}
LOG(DEBUG) << "gas limits: max=" << cp.gas_max << ", limit=" << cp.gas_limit << ", credit=" << cp.gas_credit;
return true;
}
Ref<vm::Stack> Transaction::prepare_vm_stack(ComputePhase& cp) {
Ref<vm::Stack> stack_ref{true};
td::RefInt256 acc_addr{true};
CHECK(acc_addr.write().import_bits(account.addr.cbits(), 256));
vm::Stack& stack = stack_ref.write();
switch (trans_type) {
case tr_tick:
case tr_tock:
stack.push_int(balance.grams);
stack.push_int(std::move(acc_addr));
stack.push_bool(trans_type == tr_tock);
stack.push_smallint(-2);
return stack_ref;
case tr_ord:
stack.push_int(balance.grams);
stack.push_int(msg_balance_remaining.grams);
stack.push_cell(in_msg);
stack.push_cellslice(in_msg_body);
stack.push_bool(in_msg_extern);
return stack_ref;
default:
LOG(ERROR) << "cannot initialize stack for a transaction of type " << trans_type;
return {};
}
}
bool Transaction::prepare_rand_seed(td::BitArray<256>& rand_seed, const ComputePhaseConfig& cfg) const {
// we might use SHA256(block_rand_seed . addr . trans_lt)
// instead, we use SHA256(block_rand_seed . addr)
// if the smart contract wants to randomize further, it can use RANDOMIZE instruction
td::BitArray<256 + 256> data;
data.bits().copy_from(cfg.block_rand_seed.cbits(), 256);
(data.bits() + 256).copy_from(account.addr_rewrite.cbits(), 256);
rand_seed.clear();
data.compute_sha256(rand_seed);
return true;
}
Ref<vm::Tuple> Transaction::prepare_vm_c7(const ComputePhaseConfig& cfg) const {
td::BitArray<256> rand_seed;
td::RefInt256 rand_seed_int{true};
if (!(prepare_rand_seed(rand_seed, cfg) && rand_seed_int.unique_write().import_bits(rand_seed.cbits(), 256, false))) {
LOG(ERROR) << "cannot compute rand_seed for transaction";
throw CollatorError{"cannot generate valid SmartContractInfo"};
return {};
}
auto tuple = vm::make_tuple_ref(
td::make_refint(0x076ef1ea), // [ magic:0x076ef1ea
td::zero_refint(), // actions:Integer
td::zero_refint(), // msgs_sent:Integer
td::make_refint(now), // unixtime:Integer
td::make_refint(account.block_lt), // block_lt:Integer
td::make_refint(start_lt), // trans_lt:Integer
std::move(rand_seed_int), // rand_seed:Integer
balance.as_vm_tuple(), // balance_remaining:[Integer (Maybe Cell)]
my_addr, // myself:MsgAddressInt
vm::StackEntry::maybe(cfg.global_config)); // global_config:(Maybe Cell) ] = SmartContractInfo;
LOG(DEBUG) << "SmartContractInfo initialized with " << vm::StackEntry(tuple).to_string();
return vm::make_tuple_ref(std::move(tuple));
}
int output_actions_count(Ref<vm::Cell> list) {
int i = -1;
do {
++i;
list = load_cell_slice(std::move(list)).prefetch_ref();
} while (list.not_null());
return i;
}
bool Transaction::unpack_msg_state(bool lib_only) {
block::gen::StateInit::Record state;
if (in_msg_state.is_null() || !tlb::unpack_cell(in_msg_state, state)) {
LOG(ERROR) << "cannot unpack StateInit from an inbound message";
return false;
}
if (lib_only) {
in_msg_library = state.library->prefetch_ref();
return true;
}
if (state.split_depth->size() == 6) {
new_split_depth = (signed char)(state.split_depth->prefetch_ulong(6) - 32);
} else {
new_split_depth = 0;
}
if (state.special->size() > 1) {
int z = (int)state.special->prefetch_ulong(3);
if (z < 0) {
return false;
}
new_tick = z & 2;
new_tock = z & 1;
LOG(DEBUG) << "tick=" << new_tick << ", tock=" << new_tock;
}
new_code = state.code->prefetch_ref();
new_data = state.data->prefetch_ref();
new_library = state.library->prefetch_ref();
return true;
}
std::vector<Ref<vm::Cell>> Transaction::compute_vm_libraries(const ComputePhaseConfig& cfg) {
std::vector<Ref<vm::Cell>> lib_set;
if (in_msg_library.not_null()) {
lib_set.push_back(in_msg_library);
}
if (new_library.not_null()) {
lib_set.push_back(new_library);
}
auto global_libs = cfg.get_lib_root();
if (global_libs.not_null()) {
lib_set.push_back(std::move(global_libs));
}
return lib_set;
}
bool Transaction::check_in_msg_state_hash() {
CHECK(in_msg_state.not_null());
CHECK(new_split_depth >= 0 && new_split_depth < 32);
td::Bits256 in_state_hash = in_msg_state->get_hash().bits();
int d = new_split_depth;
if ((in_state_hash.bits() + d).compare(account.addr.bits() + d, 256 - d)) {
return false;
}
orig_addr_rewrite = in_state_hash.bits();
orig_addr_rewrite_set = true;
return account.recompute_tmp_addr(my_addr, d, orig_addr_rewrite.bits());
}