-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathtonops.cpp
2120 lines (1971 loc) · 78.5 KB
/
tonops.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 <functional>
#include "vm/tonops.h"
#include "vm/log.h"
#include "vm/opctable.h"
#include "vm/stack.hpp"
#include "vm/excno.hpp"
#include "vm/vm.h"
#include "vm/dict.h"
#include "vm/boc.h"
#include "Ed25519.h"
#include "vm/Hasher.h"
#include "block/block-auto.h"
#include "block/block-parse.h"
#include "crypto/ellcurve/secp256k1.h"
#include "crypto/ellcurve/p256.h"
#include "openssl/digest.hpp"
#include <sodium.h>
#include "bls.h"
#include "mc-config.h"
namespace vm {
namespace {
bool debug(const char* str) TD_UNUSED;
bool debug(const char* str) {
std::cerr << str;
return true;
}
bool debug(int x) TD_UNUSED;
bool debug(int x) {
if (x < 100) {
std::cerr << '[' << (char)(64 + x) << ']';
} else {
std::cerr << '[' << (char)(64 + x / 100) << x % 100 << ']';
}
return true;
}
} // namespace
#define DBG_START int dbg = 0;
#define DBG debug(++dbg)&&
#define DEB_START DBG_START
#define DEB DBG
int exec_set_gas_generic(VmState* st, long long new_gas_limit) {
if (new_gas_limit < st->gas_consumed()) {
throw VmNoGas{};
}
st->change_gas_limit(new_gas_limit);
if (st->get_stop_on_accept_message()) {
VM_LOG(st) << "External message is accepted, stopping TVM";
return st->jump(td::Ref<QuitCont>{true, 0});
}
return 0;
}
int exec_accept(VmState* st) {
VM_LOG(st) << "execute ACCEPT";
return exec_set_gas_generic(st, GasLimits::infty);
}
int exec_set_gas_limit(VmState* st) {
VM_LOG(st) << "execute SETGASLIMIT";
td::RefInt256 x = st->get_stack().pop_int_finite();
long long gas = 0;
if (x->sgn() > 0) {
gas = x->unsigned_fits_bits(63) ? x->to_long() : GasLimits::infty;
}
return exec_set_gas_generic(st, gas);
}
int exec_gas_consumed(VmState* st) {
VM_LOG(st) << "execute GASCONSUMED";
st->get_stack().push_smallint(st->gas_consumed());
return 0;
}
int exec_commit(VmState* st) {
VM_LOG(st) << "execute COMMIT";
st->force_commit();
return 0;
}
void register_basic_gas_ops(OpcodeTable& cp0) {
using namespace std::placeholders;
cp0.insert(OpcodeInstr::mksimple(0xf800, 16, "ACCEPT", exec_accept))
.insert(OpcodeInstr::mksimple(0xf801, 16, "SETGASLIMIT", exec_set_gas_limit))
.insert(OpcodeInstr::mksimple(0xf807, 16, "GASCONSUMED", exec_gas_consumed)->require_version(4))
.insert(OpcodeInstr::mksimple(0xf80f, 16, "COMMIT", exec_commit));
}
void register_ton_gas_ops(OpcodeTable& cp0) {
using namespace std::placeholders;
}
static const StackEntry& get_param(VmState* st, unsigned idx) {
auto tuple = st->get_c7();
auto t1 = tuple_index(tuple, 0).as_tuple_range(255);
if (t1.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
return tuple_index(t1, idx);
}
// ConfigParams: 18 (only one entry), 19, 20, 21, 24, 25, 43
static td::Ref<Tuple> get_unpacked_config_tuple(VmState* st) {
auto tuple = st->get_c7();
auto t1 = tuple_index(tuple, 0).as_tuple_range(255);
if (t1.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
auto t2 = tuple_index(t1, 14).as_tuple_range(255);
if (t2.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
return t2;
}
int exec_get_param(VmState* st, unsigned idx, const char* name) {
if (name) {
VM_LOG(st) << "execute " << name;
}
Stack& stack = st->get_stack();
stack.push(get_param(st, idx));
return 0;
}
int exec_get_var_param(VmState* st, unsigned idx) {
idx &= 15;
VM_LOG(st) << "execute GETPARAM " << idx;
return exec_get_param(st, idx, nullptr);
}
int exec_get_config_dict(VmState* st) {
exec_get_param(st, 9, "CONFIGDICT");
st->get_stack().push_smallint(32);
return 0;
}
int exec_get_config_param(VmState* st, bool opt) {
VM_LOG(st) << "execute CONFIG" << (opt ? "OPTPARAM" : "PARAM");
Stack& stack = st->get_stack();
auto idx = stack.pop_int();
exec_get_param(st, 9, nullptr);
Dictionary dict{stack.pop_maybe_cell(), 32};
td::BitArray<32> key;
Ref<vm::Cell> value;
if (idx->export_bits(key.bits(), key.size(), true)) {
value = dict.lookup_ref(key);
}
if (opt) {
stack.push_maybe_cell(std::move(value));
} else if (value.not_null()) {
stack.push_cell(std::move(value));
stack.push_bool(true);
} else {
stack.push_bool(false);
}
return 0;
}
int exec_get_global_common(VmState* st, unsigned n) {
st->get_stack().push(tuple_extend_index(st->get_c7(), n));
return 0;
}
int exec_get_global(VmState* st, unsigned args) {
args &= 31;
VM_LOG(st) << "execute GETGLOB " << args;
return exec_get_global_common(st, args);
}
int exec_get_global_var(VmState* st) {
VM_LOG(st) << "execute GETGLOBVAR";
st->check_underflow(1);
unsigned args = st->get_stack().pop_smallint_range(254);
return exec_get_global_common(st, args);
}
int exec_set_global_common(VmState* st, unsigned idx) {
Stack& stack = st->get_stack();
auto x = stack.pop();
auto tuple = st->get_c7();
if (idx >= 255) {
throw VmError{Excno::range_chk, "tuple index out of range"};
}
static auto empty_tuple = Ref<Tuple>{true};
st->set_c7(empty_tuple); // optimization; use only if no exception can be thrown until true set_c7()
auto tpay = tuple_extend_set_index(tuple, idx, std::move(x));
if (tpay > 0) {
st->consume_tuple_gas(tpay);
}
st->set_c7(std::move(tuple));
return 0;
}
int exec_set_global(VmState* st, unsigned args) {
args &= 31;
VM_LOG(st) << "execute SETGLOB " << args;
st->check_underflow(1);
return exec_set_global_common(st, args);
}
int exec_set_global_var(VmState* st) {
VM_LOG(st) << "execute SETGLOBVAR";
st->check_underflow(2);
unsigned args = st->get_stack().pop_smallint_range(254);
return exec_set_global_common(st, args);
}
int exec_get_prev_blocks_info(VmState* st, unsigned idx, const char* name) {
idx &= 3;
VM_LOG(st) << "execute " << name;
Stack& stack = st->get_stack();
auto tuple = st->get_c7();
auto t1 = tuple_index(tuple, 0).as_tuple_range(255);
if (t1.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
auto t2 = tuple_index(t1, 13).as_tuple_range(255);
if (t2.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
stack.push(tuple_index(t2, idx));
return 0;
}
int exec_get_global_id(VmState* st) {
VM_LOG(st) << "execute GLOBALID";
if (st->get_global_version() >= 6) {
Ref<CellSlice> cs = tuple_index(get_unpacked_config_tuple(st), 1).as_slice();
if (cs.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a slice"};
}
if (cs->size() < 32) {
throw VmError{Excno::cell_und, "invalid global-id config"};
}
st->get_stack().push_smallint(cs->prefetch_long(32));
} else {
Ref<Cell> config = get_param(st, 19).as_cell();
if (config.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a cell"};
}
Dictionary config_dict{std::move(config), 32};
Ref<Cell> cell = config_dict.lookup_ref(td::BitArray<32>{19});
if (cell.is_null()) {
throw VmError{Excno::unknown, "invalid global-id config"};
}
CellSlice cs = load_cell_slice(cell);
if (cs.size() < 32) {
throw VmError{Excno::unknown, "invalid global-id config"};
}
st->get_stack().push_smallint(cs.fetch_long(32));
}
return 0;
}
int exec_get_gas_fee(VmState* st) {
VM_LOG(st) << "execute GETGASFEE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::uint64 gas = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
block::GasLimitsPrices prices = util::get_gas_prices(get_unpacked_config_tuple(st), is_masterchain);
stack.push_int(prices.compute_gas_price(gas));
return 0;
}
int exec_get_storage_fee(VmState* st) {
VM_LOG(st) << "execute GETSTORAGEFEE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::int64 delta = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
td::uint64 bits = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
td::uint64 cells = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
td::optional<block::StoragePrices> maybe_prices =
util::get_storage_prices(get_unpacked_config_tuple(st));
stack.push_int(util::calculate_storage_fee(maybe_prices, is_masterchain, delta, bits, cells));
return 0;
}
int exec_get_forward_fee(VmState* st) {
VM_LOG(st) << "execute GETFORWARDFEE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::uint64 bits = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
td::uint64 cells = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
block::MsgPrices prices = util::get_msg_prices(get_unpacked_config_tuple(st), is_masterchain);
stack.push_int(prices.compute_fwd_fees256(cells, bits));
return 0;
}
int exec_get_precompiled_gas(VmState* st) {
VM_LOG(st) << "execute GETPRECOMPILEDGAS";
Stack& stack = st->get_stack();
stack.push(get_param(st, 16));
return 0;
}
int exec_get_original_fwd_fee(VmState* st) {
VM_LOG(st) << "execute GETORIGINALFWDFEE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::RefInt256 fwd_fee = stack.pop_int_finite();
if (fwd_fee->sgn() < 0) {
throw VmError{Excno::range_chk, "fwd_fee is negative"};
}
block::MsgPrices prices = util::get_msg_prices(get_unpacked_config_tuple(st), is_masterchain);
stack.push_int(td::muldiv(fwd_fee, td::make_refint(1 << 16), td::make_refint((1 << 16) - prices.first_frac)));
return 0;
}
int exec_get_gas_fee_simple(VmState* st) {
VM_LOG(st) << "execute GETGASFEESIMPLE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::uint64 gas = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
block::GasLimitsPrices prices = util::get_gas_prices(get_unpacked_config_tuple(st), is_masterchain);
stack.push_int(td::rshift(td::make_refint(prices.gas_price) * gas, 16, 1));
return 0;
}
int exec_get_forward_fee_simple(VmState* st) {
VM_LOG(st) << "execute GETFORWARDFEESIMPLE";
Stack& stack = st->get_stack();
bool is_masterchain = stack.pop_bool();
td::uint64 bits = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
td::uint64 cells = stack.pop_long_range(std::numeric_limits<td::int64>::max(), 0);
block::MsgPrices prices = util::get_msg_prices(get_unpacked_config_tuple(st), is_masterchain);
stack.push_int(td::rshift(td::make_refint(prices.bit_price) * bits + td::make_refint(prices.cell_price) * cells, 16,
1)); // divide by 2^16 with ceil rounding
return 0;
}
void register_ton_config_ops(OpcodeTable& cp0) {
using namespace std::placeholders;
cp0.insert(OpcodeInstr::mkfixedrange(0xf820, 0xf823, 16, 4, instr::dump_1c("GETPARAM "), exec_get_var_param))
.insert(OpcodeInstr::mksimple(0xf823, 16, "NOW", std::bind(exec_get_param, _1, 3, "NOW")))
.insert(OpcodeInstr::mksimple(0xf824, 16, "BLOCKLT", std::bind(exec_get_param, _1, 4, "BLOCKLT")))
.insert(OpcodeInstr::mksimple(0xf825, 16, "LTIME", std::bind(exec_get_param, _1, 5, "LTIME")))
.insert(OpcodeInstr::mksimple(0xf826, 16, "RANDSEED", std::bind(exec_get_param, _1, 6, "RANDSEED")))
.insert(OpcodeInstr::mksimple(0xf827, 16, "BALANCE", std::bind(exec_get_param, _1, 7, "BALANCE")))
.insert(OpcodeInstr::mksimple(0xf828, 16, "MYADDR", std::bind(exec_get_param, _1, 8, "MYADDR")))
.insert(OpcodeInstr::mksimple(0xf829, 16, "CONFIGROOT", std::bind(exec_get_param, _1, 9, "CONFIGROOT")))
.insert(OpcodeInstr::mksimple(0xf82a, 16, "MYCODE", std::bind(exec_get_param, _1, 10, "MYCODE")))
.insert(OpcodeInstr::mksimple(0xf82b, 16, "INCOMINGVALUE", std::bind(exec_get_param, _1, 11, "INCOMINGVALUE")))
.insert(OpcodeInstr::mksimple(0xf82c, 16, "STORAGEFEES", std::bind(exec_get_param, _1, 12, "STORAGEFEES")))
.insert(OpcodeInstr::mksimple(0xf82d, 16, "PREVBLOCKSINFOTUPLE", std::bind(exec_get_param, _1, 13, "PREVBLOCKSINFOTUPLE")))
.insert(OpcodeInstr::mksimple(0xf82e, 16, "UNPACKEDCONFIGTUPLE", std::bind(exec_get_param, _1, 14, "UNPACKEDCONFIGTUPLE")))
.insert(OpcodeInstr::mksimple(0xf82f, 16, "DUEPAYMENT", std::bind(exec_get_param, _1, 15, "DUEPAYMENT")))
.insert(OpcodeInstr::mksimple(0xf830, 16, "CONFIGDICT", exec_get_config_dict))
.insert(OpcodeInstr::mksimple(0xf832, 16, "CONFIGPARAM", std::bind(exec_get_config_param, _1, false)))
.insert(OpcodeInstr::mksimple(0xf833, 16, "CONFIGOPTPARAM", std::bind(exec_get_config_param, _1, true)))
.insert(OpcodeInstr::mksimple(0xf83400, 24, "PREVMCBLOCKS", std::bind(exec_get_prev_blocks_info, _1, 0, "PREVMCBLOCKS"))->require_version(4))
.insert(OpcodeInstr::mksimple(0xf83401, 24, "PREVKEYBLOCK", std::bind(exec_get_prev_blocks_info, _1, 1, "PREVKEYBLOCK"))->require_version(4))
.insert(OpcodeInstr::mksimple(0xf835, 16, "GLOBALID", exec_get_global_id)->require_version(4))
.insert(OpcodeInstr::mksimple(0xf836, 16, "GETGASFEE", exec_get_gas_fee)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf837, 16, "GETSTORAGEFEE", exec_get_storage_fee)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf838, 16, "GETFORWARDFEE", exec_get_forward_fee)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf839, 16, "GETPRECOMPILEDGAS", exec_get_precompiled_gas)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf83a, 16, "GETORIGINALFWDFEE", exec_get_original_fwd_fee)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf83b, 16, "GETGASFEESIMPLE", exec_get_gas_fee_simple)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf83c, 16, "GETFORWARDFEESIMPLE", exec_get_forward_fee_simple)->require_version(6))
.insert(OpcodeInstr::mksimple(0xf840, 16, "GETGLOBVAR", exec_get_global_var))
.insert(OpcodeInstr::mkfixedrange(0xf841, 0xf860, 16, 5, instr::dump_1c_and(31, "GETGLOB "), exec_get_global))
.insert(OpcodeInstr::mksimple(0xf860, 16, "SETGLOBVAR", exec_set_global_var))
.insert(OpcodeInstr::mkfixedrange(0xf861, 0xf880, 16, 5, instr::dump_1c_and(31, "SETGLOB "), exec_set_global));
}
static constexpr int randseed_idx = 6;
td::RefInt256 generate_randu256(VmState* st) {
auto tuple = st->get_c7();
auto t1 = tuple_index(tuple, 0).as_tuple_range(255);
if (t1.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
auto seedv = tuple_index(t1, randseed_idx).as_int();
if (seedv.is_null()) {
throw VmError{Excno::type_chk, "random seed is not an integer"};
}
unsigned char seed[32];
if (!seedv->export_bytes(seed, 32, false)) {
throw VmError{Excno::range_chk, "random seed out of range"};
}
unsigned char hash[64];
digest::hash_str<digest::SHA512>(hash, seed, 32);
if (!seedv.write().import_bytes(hash, 32, false)) {
throw VmError{Excno::range_chk, "cannot store new random seed"};
}
td::RefInt256 res{true};
if (!res.write().import_bytes(hash + 32, 32, false)) {
throw VmError{Excno::range_chk, "cannot store new random number"};
}
static auto empty_tuple = Ref<Tuple>{true};
st->set_c7(empty_tuple); // optimization; use only if no exception can be thrown until true set_c7()
tuple.write()[0].clear();
t1.write().at(randseed_idx) = std::move(seedv);
st->consume_tuple_gas(t1);
tuple.write().at(0) = std::move(t1);
st->consume_tuple_gas(tuple);
st->set_c7(std::move(tuple));
return res;
}
int exec_randu256(VmState* st) {
VM_LOG(st) << "execute RANDU256";
st->get_stack().push_int(generate_randu256(st));
return 0;
}
int exec_rand_int(VmState* st) {
VM_LOG(st) << "execute RAND";
auto& stack = st->get_stack();
stack.check_underflow(1);
auto x = stack.pop_int_finite();
auto y = generate_randu256(st);
typename td::BigInt256::DoubleInt tmp{0};
tmp.add_mul(*x, *y);
tmp.rshift(256, -1).normalize();
stack.push_int(td::make_refint(tmp));
return 0;
}
int exec_set_rand(VmState* st, bool mix) {
VM_LOG(st) << "execute " << (mix ? "ADDRAND" : "SETRAND");
auto& stack = st->get_stack();
stack.check_underflow(1);
auto x = stack.pop_int_finite();
if (!x->unsigned_fits_bits(256)) {
throw VmError{Excno::range_chk, "new random seed out of range"};
}
auto tuple = st->get_c7();
auto t1 = tuple_index(tuple, 0).as_tuple_range(255);
if (t1.is_null()) {
throw VmError{Excno::type_chk, "intermediate value is not a tuple"};
}
if (mix) {
auto seedv = tuple_index(t1, randseed_idx).as_int();
if (seedv.is_null()) {
throw VmError{Excno::type_chk, "random seed is not an integer"};
}
unsigned char buffer[64], hash[32];
if (!std::move(seedv)->export_bytes(buffer, 32, false)) {
throw VmError{Excno::range_chk, "random seed out of range"};
}
if (!x->export_bytes(buffer + 32, 32, false)) {
throw VmError{Excno::range_chk, "mixed seed value out of range"};
}
digest::hash_str<digest::SHA256>(hash, buffer, 64);
if (!x.write().import_bytes(hash, 32, false)) {
throw VmError{Excno::range_chk, "new random seed value out of range"};
}
}
static auto empty_tuple = Ref<Tuple>{true};
st->set_c7(empty_tuple); // optimization; use only if no exception can be thrown until true set_c7()
tuple.write()[0].clear();
auto tpay = tuple_extend_set_index(t1, randseed_idx, std::move(x));
if (tpay > 0) {
st->consume_tuple_gas(tpay);
}
tuple.unique_write()[0] = std::move(t1);
st->consume_tuple_gas(tuple);
st->set_c7(std::move(tuple));
return 0;
}
void register_prng_ops(OpcodeTable& cp0) {
using namespace std::placeholders;
cp0.insert(OpcodeInstr::mksimple(0xf810, 16, "RANDU256", exec_randu256))
.insert(OpcodeInstr::mksimple(0xf811, 16, "RAND", exec_rand_int))
.insert(OpcodeInstr::mksimple(0xf814, 16, "SETRAND", std::bind(exec_set_rand, _1, false)))
.insert(OpcodeInstr::mksimple(0xf815, 16, "ADDRAND", std::bind(exec_set_rand, _1, true)));
}
int exec_compute_hash(VmState* st, int mode) {
VM_LOG(st) << "execute HASH" << (mode & 1 ? 'S' : 'C') << 'U';
Stack& stack = st->get_stack();
std::array<unsigned char, 32> hash;
if (!(mode & 1)) {
auto cell = stack.pop_cell();
hash = cell->get_hash().as_array();
} else {
auto cs = stack.pop_cellslice();
vm::CellBuilder cb;
CHECK(cb.append_cellslice_bool(std::move(cs)));
// TODO: use cb.get_hash() instead
hash = cb.finalize()->get_hash().as_array();
}
td::RefInt256 res{true};
CHECK(res.write().import_bytes(hash.data(), hash.size(), false));
stack.push_int(std::move(res));
return 0;
}
int exec_compute_sha256(VmState* st) {
VM_LOG(st) << "execute SHA256U";
Stack& stack = st->get_stack();
auto cs = stack.pop_cellslice();
if (cs->size() & 7) {
throw VmError{Excno::cell_und, "Slice does not consist of an integer number of bytes"};
}
auto len = (cs->size() >> 3);
unsigned char data[128], hash[32];
CHECK(len <= sizeof(data));
CHECK(cs->prefetch_bytes(data, len));
digest::hash_str<digest::SHA256>(hash, data, len);
td::RefInt256 res{true};
CHECK(res.write().import_bytes(hash, 32, false));
stack.push_int(std::move(res));
return 0;
}
int exec_hash_ext(VmState* st, unsigned args) {
bool rev = (args >> 8) & 1;
bool append = (args >> 9) & 1;
int hash_id = args & 255;
VM_LOG(st) << "execute HASHEXT" << (append ? "A" : "") << (rev ? "R" : "") << " " << (hash_id == 255 ? -1 : hash_id);
Stack& stack = st->get_stack();
if (hash_id == 255) {
hash_id = stack.pop_smallint_range(254);
}
int cnt = stack.pop_smallint_range(stack.depth() - 1);
Hasher hasher{hash_id};
size_t total_bits = 0;
long long gas_consumed = 0;
for (int i = 0; i < cnt; ++i) {
td::ConstBitPtr data{nullptr};
unsigned size;
int idx = rev ? i : cnt - 1 - i;
auto slice = stack[idx].as_slice();
if (slice.not_null()) {
data = slice->data_bits();
size = slice->size();
} else {
auto builder = stack[idx].as_builder();
if (builder.not_null()) {
data = builder->data_bits();
size = builder->size();
} else {
stack.pop_many(cnt);
throw VmError{Excno::type_chk, "expected slice or builder"};
}
}
total_bits += size;
long long gas_total = (i + 1) * VmState::hash_ext_entry_gas_price + total_bits / 8 / hasher.bytes_per_gas_unit();
st->consume_gas(gas_total - gas_consumed);
gas_consumed = gas_total;
hasher.append(data, size);
}
stack.pop_many(cnt);
td::BufferSlice hash = hasher.finish();
if (append) {
Ref<CellBuilder> builder = stack.pop_builder();
if (!builder->can_extend_by(hash.size() * 8)) {
throw VmError{Excno::cell_ov};
}
builder.write().store_bytes(hash.as_slice());
stack.push_builder(std::move(builder));
} else {
if (hash.size() <= 32) {
td::RefInt256 res{true};
CHECK(res.write().import_bytes((unsigned char*)hash.data(), hash.size(), false));
stack.push_int(std::move(res));
} else {
std::vector<StackEntry> res;
for (size_t i = 0; i < hash.size(); i += 32) {
td::RefInt256 x{true};
CHECK(x.write().import_bytes((unsigned char*)hash.data() + i, std::min<size_t>(hash.size() - i, 32), false));
res.push_back(std::move(x));
}
stack.push_tuple(std::move(res));
}
}
return 0;
}
std::string dump_hash_ext(CellSlice& cs, unsigned args) {
bool rev = (args >> 8) & 1;
bool append = (args >> 9) & 1;
int hash_id = args & 255;
return PSTRING() << "HASHEXT" << (append ? "A" : "") << (rev ? "R" : "") << " " << (hash_id == 255 ? -1 : hash_id);
}
int exec_ed25519_check_signature(VmState* st, bool from_slice) {
VM_LOG(st) << "execute CHKSIGN" << (from_slice ? 'S' : 'U');
Stack& stack = st->get_stack();
stack.check_underflow(3);
auto key_int = stack.pop_int();
auto signature_cs = stack.pop_cellslice();
unsigned char data[128], key[32], signature[64];
unsigned data_len;
if (from_slice) {
auto cs = stack.pop_cellslice();
if (cs->size() & 7) {
throw VmError{Excno::cell_und, "Slice does not consist of an integer number of bytes"};
}
data_len = (cs->size() >> 3);
CHECK(data_len <= sizeof(data));
CHECK(cs->prefetch_bytes(data, data_len));
} else {
auto hash_int = stack.pop_int();
data_len = 32;
if (!hash_int->export_bytes(data, data_len, false)) {
throw VmError{Excno::range_chk, "data hash must fit in an unsigned 256-bit integer"};
}
}
if (!signature_cs->prefetch_bytes(signature, 64)) {
throw VmError{Excno::cell_und, "Ed25519 signature must contain at least 512 data bits"};
}
if (!key_int->export_bytes(key, 32, false)) {
throw VmError{Excno::range_chk, "Ed25519 public key must fit in an unsigned 256-bit integer"};
}
st->register_chksgn_call();
td::Ed25519::PublicKey pub_key{td::SecureString(td::Slice{key, 32})};
auto res = pub_key.verify_signature(td::Slice{data, data_len}, td::Slice{signature, 64});
stack.push_bool(res.is_ok() || st->get_chksig_always_succeed());
return 0;
}
int exec_ecrecover(VmState* st) {
VM_LOG(st) << "execute ECRECOVER";
Stack& stack = st->get_stack();
stack.check_underflow(4);
auto s = stack.pop_int();
auto r = stack.pop_int();
auto v = (td::uint8)stack.pop_smallint_range(255);
auto hash = stack.pop_int();
unsigned char signature[65];
if (!r->export_bytes(signature, 32, false)) {
throw VmError{Excno::range_chk, "r must fit in an unsigned 256-bit integer"};
}
if (!s->export_bytes(signature + 32, 32, false)) {
throw VmError{Excno::range_chk, "s must fit in an unsigned 256-bit integer"};
}
signature[64] = v;
unsigned char hash_bytes[32];
if (!hash->export_bytes(hash_bytes, 32, false)) {
throw VmError{Excno::range_chk, "data hash must fit in an unsigned 256-bit integer"};
}
st->consume_gas(VmState::ecrecover_gas_price);
unsigned char public_key[65];
if (td::ecrecover(hash_bytes, signature, public_key)) {
td::uint8 h = public_key[0];
td::RefInt256 x1{true}, x2{true};
CHECK(x1.write().import_bytes(public_key + 1, 32, false));
CHECK(x2.write().import_bytes(public_key + 33, 32, false));
stack.push_smallint(h);
stack.push_int(std::move(x1));
stack.push_int(std::move(x2));
stack.push_bool(true);
} else {
stack.push_bool(false);
}
return 0;
}
int exec_p256_chksign(VmState* st, bool from_slice) {
VM_LOG(st) << "execute P256_CHKSIGN" << (from_slice ? 'S' : 'U');
Stack& stack = st->get_stack();
stack.check_underflow(3);
auto key_cs = stack.pop_cellslice();
auto signature_cs = stack.pop_cellslice();
unsigned char data[128], key[33], signature[64];
unsigned data_len;
if (from_slice) {
auto cs = stack.pop_cellslice();
if (cs->size() & 7) {
throw VmError{Excno::cell_und, "Slice does not consist of an integer number of bytes"};
}
data_len = (cs->size() >> 3);
CHECK(data_len <= sizeof(data));
CHECK(cs->prefetch_bytes(data, data_len));
} else {
auto hash_int = stack.pop_int();
data_len = 32;
if (!hash_int->export_bytes(data, data_len, false)) {
throw VmError{Excno::range_chk, "data hash must fit in an unsigned 256-bit integer"};
}
}
if (!signature_cs->prefetch_bytes(signature, 64)) {
throw VmError{Excno::cell_und, "P256 signature must contain at least 512 data bits"};
}
if (!key_cs->prefetch_bytes(key, 33)) {
throw VmError{Excno::cell_und, "P256 public key must contain at least 33 data bytes"};
}
st->consume_gas(VmState::p256_chksgn_gas_price);
auto res = td::p256_check_signature(td::Slice{data, data_len}, td::Slice{key, 33}, td::Slice{signature, 64});
if (res.is_error()) {
VM_LOG(st) << "P256_CHKSIGN: " << res.error().message();
}
stack.push_bool(res.is_ok() || st->get_chksig_always_succeed());
return 0;
}
static_assert(crypto_scalarmult_ristretto255_BYTES == 32, "Unexpected value of ristretto255 constant");
static_assert(crypto_scalarmult_ristretto255_SCALARBYTES == 32, "Unexpected value of ristretto255 constant");
static_assert(crypto_core_ristretto255_BYTES == 32, "Unexpected value of ristretto255 constant");
static_assert(crypto_core_ristretto255_HASHBYTES == 64, "Unexpected value of ristretto255 constant");
static_assert(crypto_core_ristretto255_SCALARBYTES == 32, "Unexpected value of ristretto255 constant");
static_assert(crypto_core_ristretto255_NONREDUCEDSCALARBYTES == 64, "Unexpected value of ristretto255 constant");
int exec_ristretto255_from_hash(VmState* st) {
VM_LOG(st) << "execute RIST255_FROMHASH";
Stack& stack = st->get_stack();
stack.check_underflow(2);
auto x2 = stack.pop_int();
auto x1 = stack.pop_int();
st->consume_gas(VmState::rist255_fromhash_gas_price);
unsigned char xb[64], rb[32];
if (!x1->export_bytes(xb, 32, false)) {
throw VmError{Excno::range_chk, "x1 must fit in an unsigned 256-bit integer"};
}
if (!x2->export_bytes(xb + 32, 32, false)) {
throw VmError{Excno::range_chk, "x2 must fit in an unsigned 256-bit integer"};
}
crypto_core_ristretto255_from_hash(rb, xb);
td::RefInt256 r{true};
CHECK(r.write().import_bytes(rb, 32, false));
stack.push_int(std::move(r));
return 0;
}
int exec_ristretto255_validate(VmState* st, bool quiet) {
VM_LOG(st) << "execute RIST255_VALIDATE";
Stack& stack = st->get_stack();
auto x = stack.pop_int();
st->consume_gas(VmState::rist255_validate_gas_price);
unsigned char xb[32];
if (!x->export_bytes(xb, 32, false) || !crypto_core_ristretto255_is_valid_point(xb)) {
if (quiet) {
stack.push_bool(false);
return 0;
}
throw VmError{Excno::range_chk, "x is not a valid encoded element"};
}
if (quiet) {
stack.push_bool(true);
}
return 0;
}
int exec_ristretto255_add(VmState* st, bool quiet) {
VM_LOG(st) << "execute RIST255_ADD";
Stack& stack = st->get_stack();
stack.check_underflow(2);
auto y = stack.pop_int();
auto x = stack.pop_int();
st->consume_gas(VmState::rist255_add_gas_price);
unsigned char xb[32], yb[32], rb[32];
if (!x->export_bytes(xb, 32, false) || !y->export_bytes(yb, 32, false) || crypto_core_ristretto255_add(rb, xb, yb)) {
if (quiet) {
stack.push_bool(false);
return 0;
}
throw VmError{Excno::range_chk, "x and/or y are not valid encoded elements"};
}
td::RefInt256 r{true};
CHECK(r.write().import_bytes(rb, 32, false));
stack.push_int(std::move(r));
if (quiet) {
stack.push_bool(true);
}
return 0;
}
int exec_ristretto255_sub(VmState* st, bool quiet) {
VM_LOG(st) << "execute RIST255_SUB";
Stack& stack = st->get_stack();
stack.check_underflow(2);
auto y = stack.pop_int();
auto x = stack.pop_int();
st->consume_gas(VmState::rist255_add_gas_price);
unsigned char xb[32], yb[32], rb[32];
if (!x->export_bytes(xb, 32, false) || !y->export_bytes(yb, 32, false) || crypto_core_ristretto255_sub(rb, xb, yb)) {
if (quiet) {
stack.push_bool(false);
return 0;
}
throw VmError{Excno::range_chk, "x and/or y are not valid encoded elements"};
}
td::RefInt256 r{true};
CHECK(r.write().import_bytes(rb, 32, false));
stack.push_int(std::move(r));
if (quiet) {
stack.push_bool(true);
}
return 0;
}
static bool export_bytes_little(const td::RefInt256& n, unsigned char* nb) {
if (!n->export_bytes(nb, 32, false)) {
return false;
}
std::reverse(nb, nb + 32);
return true;
}
static td::RefInt256 get_ristretto256_l() {
static td::RefInt256 l =
(td::make_refint(1) << 252) + td::dec_string_to_int256(td::Slice("27742317777372353535851937790883648493"));
return l;
}
int exec_ristretto255_mul(VmState* st, bool quiet) {
VM_LOG(st) << "execute RIST255_MUL";
Stack& stack = st->get_stack();
stack.check_underflow(2);
auto n = stack.pop_int() % get_ristretto256_l();
auto x = stack.pop_int();
st->consume_gas(VmState::rist255_mul_gas_price);
if (n->sgn() == 0) {
stack.push_smallint(0);
if (quiet) {
stack.push_bool(true);
}
return 0;
}
unsigned char xb[32], nb[32], rb[32];
if (!x->export_bytes(xb, 32, false) || !export_bytes_little(n, nb) || crypto_scalarmult_ristretto255(rb, nb, xb)) {
if (quiet) {
stack.push_bool(false);
return 0;
}
throw VmError{Excno::range_chk, "invalid x or n"};
}
td::RefInt256 r{true};
CHECK(r.write().import_bytes(rb, 32, false));
stack.push_int(std::move(r));
if (quiet) {
stack.push_bool(true);
}
return 0;
}
int exec_ristretto255_mul_base(VmState* st, bool quiet) {
VM_LOG(st) << "execute RIST255_MULBASE";
Stack& stack = st->get_stack();
auto n = stack.pop_int() % get_ristretto256_l();
st->consume_gas(VmState::rist255_mulbase_gas_price);
unsigned char nb[32], rb[32];
memset(rb, 255, sizeof(rb));
if (!export_bytes_little(n, nb) || crypto_scalarmult_ristretto255_base(rb, nb)) {
if (std::all_of(rb, rb + 32, [](unsigned char c) { return c == 255; })) {
if (quiet) {
stack.push_bool(false);
return 0;
}
throw VmError{Excno::range_chk, "invalid n"};
}
}
td::RefInt256 r{true};
CHECK(r.write().import_bytes(rb, 32, false));
stack.push_int(std::move(r));
if (quiet) {
stack.push_bool(true);
}
return 0;
}
int exec_ristretto255_push_l(VmState* st) {
VM_LOG(st) << "execute RIST255_PUSHL";
Stack& stack = st->get_stack();
stack.push_int(get_ristretto256_l());
return 0;
}
static bls::P1 slice_to_bls_p1(const CellSlice& cs) {
bls::P1 p1;
if (!cs.prefetch_bytes(p1.as_slice())) {
throw VmError{Excno::cell_und, PSTRING() << "slice must contain at least " << bls::P1_SIZE << " bytes"};
}
return p1;
}
static bls::P2 slice_to_bls_p2(const CellSlice& cs) {
bls::P2 p2;
if (!cs.prefetch_bytes(p2.as_slice())) {
throw VmError{Excno::cell_und, PSTRING() << "slice must contain at least " << bls::P2_SIZE << " bytes"};
}
return p2;
}
static bls::FP slice_to_bls_fp(const CellSlice& cs) {
bls::FP fp;
if (!cs.prefetch_bytes(fp.as_slice())) {
throw VmError{Excno::cell_und, PSTRING() << "slice must contain at least " << bls::FP_SIZE << " bytes"};
}
return fp;
}
static bls::FP2 slice_to_bls_fp2(const CellSlice& cs) {
bls::FP2 fp2;
if (!cs.prefetch_bytes(fp2.as_slice())) {
throw VmError{Excno::cell_und, PSTRING() << "slice must contain at least " << bls::FP_SIZE * 2 << " bytes"};
}
return fp2;
}
static td::BufferSlice slice_to_bls_msg(const CellSlice& cs) {
if (cs.size() % 8 != 0) {
throw VmError{Excno::cell_und, "message does not consist of an integer number of bytes"};
}
size_t msg_size = cs.size() / 8;
td::BufferSlice s(msg_size);
cs.prefetch_bytes((td::uint8*)s.data(), (int)msg_size);
return s;
}
static Ref<CellSlice> bls_to_slice(td::Slice s) {
VmStateInterface::Guard guard{nullptr}; // Don't consume gas for finalize and load_cell_slice
CellBuilder cb;
return load_cell_slice_ref(cb.store_bytes(s).finalize());
}
static long long bls_calculate_multiexp_gas(int n, long long base, long long coef1, long long coef2) {
int l = 4;
while ((1LL << (l + 1)) <= n) {
++l;
}
return base + n * coef1 + n * coef2 / l;
}
int exec_bls_verify(VmState* st) {
VM_LOG(st) << "execute BLS_VERIFY";
Stack& stack = st->get_stack();
stack.check_underflow(3);
st->consume_gas(VmState::bls_verify_gas_price);
bls::P2 sig = slice_to_bls_p2(*stack.pop_cellslice());
td::BufferSlice msg = slice_to_bls_msg(*stack.pop_cellslice());
bls::P1 pub = slice_to_bls_p1(*stack.pop_cellslice());
stack.push_bool(bls::verify(pub, msg, sig));
return 0;
}
int exec_bls_aggregate(VmState* st) {
VM_LOG(st) << "execute BLS_AGGREGATE";
Stack& stack = st->get_stack();
int n = stack.pop_smallint_range(stack.depth() - 1, 1);
st->consume_gas(VmState::bls_aggregate_base_gas_price + (long long)n * VmState::bls_aggregate_element_gas_price);
std::vector<bls::P2> sigs(n);
for (int i = n - 1; i >= 0; --i) {
sigs[i] = slice_to_bls_p2(*stack.pop_cellslice());
}
bls::P2 aggregated = bls::aggregate(sigs);
stack.push_cellslice(bls_to_slice(aggregated.as_slice()));
return 0;
}
int exec_bls_fast_aggregate_verify(VmState* st) {
VM_LOG(st) << "execute BLS_FASTAGGREGATEVERIFY";
Stack& stack = st->get_stack();
stack.check_underflow(3);
Ref<CellSlice> sig = stack.pop_cellslice();
Ref<CellSlice> msg = stack.pop_cellslice();
int n = stack.pop_smallint_range(stack.depth() - 1);
st->consume_gas(VmState::bls_fast_aggregate_verify_base_gas_price +
(long long)n * VmState::bls_fast_aggregate_verify_element_gas_price);
std::vector<bls::P1> pubs(n);
for (int i = n - 1; i >= 0; --i) {
pubs[i] = slice_to_bls_p1(*stack.pop_cellslice());
}
stack.push_bool(bls::fast_aggregate_verify(pubs, slice_to_bls_msg(*msg), slice_to_bls_p2(*sig)));
return 0;
}
int exec_bls_aggregate_verify(VmState* st) {
VM_LOG(st) << "execute BLS_AGGREGATEVERIFY";
Stack& stack = st->get_stack();
stack.check_underflow(2);
Ref<CellSlice> sig = stack.pop_cellslice();
int n = stack.pop_smallint_range((stack.depth() - 1) / 2);
st->consume_gas(VmState::bls_aggregate_verify_base_gas_price +
(long long)n * VmState::bls_aggregate_verify_element_gas_price);
std::vector<std::pair<bls::P1, td::BufferSlice>> vec(n);
for (int i = n - 1; i >= 0; --i) {
vec[i].second = slice_to_bls_msg(*stack.pop_cellslice());
vec[i].first = slice_to_bls_p1(*stack.pop_cellslice());
}