forked from newton-blockchain/ton
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest-smartcont.cpp
1652 lines (1484 loc) · 61.9 KB
/
test-smartcont.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 "vm/dict.h"
#include "common/bigint.hpp"
#include "Ed25519.h"
#include "block/block-auto.h"
#include "block/block.h"
#include "block/block-parse.h"
#include "fift/Fift.h"
#include "fift/words.h"
#include "fift/utils.h"
#include "smc-envelope/GenericAccount.h"
#include "smc-envelope/ManualDns.h"
#include "smc-envelope/MultisigWallet.h"
#include "smc-envelope/SmartContract.h"
#include "smc-envelope/SmartContractCode.h"
#include "smc-envelope/WalletV3.h"
#include "smc-envelope/HighloadWallet.h"
#include "smc-envelope/HighloadWalletV2.h"
#include "smc-envelope/PaymentChannel.h"
#include "td/utils/base64.h"
#include "td/utils/crypto.h"
#include "td/utils/Random.h"
#include "td/utils/tests.h"
#include "td/utils/ScopeGuard.h"
#include "td/utils/StringBuilder.h"
#include "td/utils/Timer.h"
#include "td/utils/PathView.h"
#include "td/utils/filesystem.h"
#include "td/utils/port/path.h"
#include "td/utils/Variant.h"
#include <bitset>
#include <set>
#include <tuple>
std::string current_dir() {
return td::PathView(td::realpath(__FILE__).move_as_ok()).parent_dir().str();
}
std::string load_source(std::string name) {
return td::read_file_str(current_dir() + "../../crypto/" + name).move_as_ok();
}
td::Ref<vm::Cell> get_wallet_v3_source() {
std::string code = R"ABCD(
SETCP0 DUP IFNOTRET // return if recv_internal
DUP 85143 INT EQUAL OVER 78748 INT EQUAL OR IFJMP:<{ // "seqno" and "get_public_key" get-methods
1 INT AND c4 PUSHCTR CTOS 32 LDU 32 LDU NIP 256 PLDU CONDSEL // cnt or pubk
}>
INC 32 THROWIF // fail unless recv_external
9 PUSHPOW2 LDSLICEX DUP 32 LDU 32 LDU 32 LDU // signature in_msg subwallet_id valid_until msg_seqno cs
NOW s1 s3 XCHG LEQ 35 THROWIF // signature in_msg subwallet_id cs msg_seqno
c4 PUSH CTOS 32 LDU 32 LDU 256 LDU ENDS // signature in_msg subwallet_id cs msg_seqno stored_seqno stored_subwallet public_key
s3 s2 XCPU EQUAL 33 THROWIFNOT // signature in_msg subwallet_id cs public_key stored_seqno stored_subwallet
s4 s4 XCPU EQUAL 34 THROWIFNOT // signature in_msg stored_subwallet cs public_key stored_seqno
s0 s4 XCHG HASHSU // signature stored_seqno stored_subwallet cs public_key msg_hash
s0 s5 s5 XC2PU // public_key stored_seqno stored_subwallet cs msg_hash signature public_key
CHKSIGNU 35 THROWIFNOT // public_key stored_seqno stored_subwallet cs
ACCEPT
WHILE:<{
DUP SREFS // public_key stored_seqno stored_subwallet cs _51
}>DO<{ // public_key stored_seqno stored_subwallet cs
8 LDU LDREF s0 s2 XCHG // public_key stored_seqno stored_subwallet cs _56 mode
SENDRAWMSG
}> // public_key stored_seqno stored_subwallet cs
ENDS SWAP INC // public_key stored_subwallet seqno'
NEWC 32 STU 32 STU 256 STU ENDC c4 POP
)ABCD";
return fift::compile_asm(code).move_as_ok();
}
TEST(Tonlib, WalletV3) {
LOG(ERROR) << td::base64_encode(std_boc_serialize(get_wallet_v3_source()).move_as_ok());
CHECK(get_wallet_v3_source()->get_hash() == ton::WalletV3::get_init_code(2)->get_hash());
auto fift_output = fift::mem_run_fift(load_source("smartcont/new-wallet-v3.fif"), {"aba", "0", "239"}).move_as_ok();
auto new_wallet_pk = fift_output.source_lookup.read_file("new-wallet.pk").move_as_ok().data;
auto new_wallet_query = fift_output.source_lookup.read_file("new-wallet-query.boc").move_as_ok().data;
auto new_wallet_addr = fift_output.source_lookup.read_file("new-wallet.addr").move_as_ok().data;
td::Ed25519::PrivateKey priv_key{td::SecureString{new_wallet_pk}};
auto pub_key = priv_key.get_public_key().move_as_ok();
ton::WalletV3::InitData init_data;
init_data.public_key = pub_key.as_octet_string();
init_data.wallet_id = 239;
auto wallet = ton::WalletV3::create(init_data, 2);
ASSERT_EQ(239u, wallet->get_wallet_id().ok());
ASSERT_EQ(0u, wallet->get_seqno().ok());
auto address = wallet->get_address();
CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32));
auto init_message = wallet->get_init_message(priv_key).move_as_ok();
td::Ref<vm::Cell> ext_init_message = ton::GenericAccount::create_ext_message(
address, ton::GenericAccount::get_init_state(wallet->get_state()), init_message);
LOG(ERROR) << "-------";
vm::load_cell_slice(ext_init_message).print_rec(std::cerr);
LOG(ERROR) << "-------";
vm::load_cell_slice(vm::std_boc_deserialize(new_wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(new_wallet_query).move_as_ok()->get_hash() == ext_init_message->get_hash());
CHECK(wallet.write().send_external_message(init_message).success);
fift_output.source_lookup.write_file("/main.fif", load_source("smartcont/wallet-v3.fif")).ensure();
class ZeroOsTime : public fift::OsTime {
public:
td::uint32 now() override {
return 0;
}
};
fift_output.source_lookup.set_os_time(std::make_unique<ZeroOsTime>());
auto dest = block::StdAddress::parse("Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX").move_as_ok();
fift_output = fift::mem_run_fift(std::move(fift_output.source_lookup),
{"aba", "new-wallet", "-C", "TESTv3",
"Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX", "239", "1", "321"})
.move_as_ok();
auto wallet_query = fift_output.source_lookup.read_file("wallet-query.boc").move_as_ok().data;
ton::WalletV3::Gift gift;
gift.destination = dest;
gift.message = "TESTv3";
gift.gramms = 321000000000ll;
ASSERT_EQ(239u, wallet->get_wallet_id().ok());
ASSERT_EQ(1u, wallet->get_seqno().ok());
CHECK(priv_key.get_public_key().ok().as_octet_string() == wallet->get_public_key().ok().as_octet_string());
CHECK(priv_key.get_public_key().ok().as_octet_string() ==
ton::GenericAccount::get_public_key(*wallet).ok().as_octet_string());
auto gift_message = ton::GenericAccount::create_ext_message(
address, {}, wallet->make_a_gift_message(priv_key, 60, {gift}).move_as_ok());
LOG(ERROR) << "-------";
vm::load_cell_slice(gift_message).print_rec(std::cerr);
LOG(ERROR) << "-------";
vm::load_cell_slice(vm::std_boc_deserialize(wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == gift_message->get_hash());
}
TEST(Tonlib, HighloadWallet) {
auto source_lookup = fift::create_mem_source_lookup(load_source("smartcont/new-highload-wallet.fif")).move_as_ok();
source_lookup.write_file("/auto/highload-wallet-code.fif", load_source("smartcont/auto/highload-wallet-code.fif"))
.ensure();
auto fift_output = fift::mem_run_fift(std::move(source_lookup), {"aba", "0", "239"}).move_as_ok();
LOG(ERROR) << fift_output.output;
auto new_wallet_pk = fift_output.source_lookup.read_file("new-wallet.pk").move_as_ok().data;
auto new_wallet_query = fift_output.source_lookup.read_file("new-wallet239-query.boc").move_as_ok().data;
auto new_wallet_addr = fift_output.source_lookup.read_file("new-wallet239.addr").move_as_ok().data;
td::Ed25519::PrivateKey priv_key{td::SecureString{new_wallet_pk}};
auto pub_key = priv_key.get_public_key().move_as_ok();
ton::HighloadWallet::InitData init_data(pub_key.as_octet_string(), 239);
auto wallet = ton::HighloadWallet::create(init_data, -1);
auto address = wallet->get_address();
CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32));
ASSERT_EQ(239u, wallet->get_wallet_id().ok());
ASSERT_EQ(0u, wallet->get_seqno().ok());
CHECK(pub_key.as_octet_string() == wallet->get_public_key().ok().as_octet_string());
CHECK(pub_key.as_octet_string() == ton::GenericAccount::get_public_key(*wallet).ok().as_octet_string());
CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32));
auto init_message = wallet->get_init_message(priv_key).move_as_ok();
td::Ref<vm::Cell> res = ton::GenericAccount::create_ext_message(
address, ton::GenericAccount::get_init_state(wallet->get_state()), init_message);
LOG(ERROR) << "---smc-envelope----";
vm::load_cell_slice(res).print_rec(std::cerr);
LOG(ERROR) << "---fift scripts----";
vm::load_cell_slice(vm::std_boc_deserialize(new_wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(new_wallet_query).move_as_ok()->get_hash() == res->get_hash());
fift_output.source_lookup.write_file("/main.fif", load_source("smartcont/highload-wallet.fif")).ensure();
std::string order;
std::vector<ton::HighloadWallet::Gift> gifts;
auto add_order = [&](td::Slice dest_str, td::int64 gramms) {
auto g = td::to_string(gramms);
if (g.size() < 10) {
g = std::string(10 - g.size(), '0') + g;
}
order += PSTRING() << "SEND " << dest_str << " " << g.substr(0, g.size() - 9) << "." << g.substr(g.size() - 9)
<< "\n";
ton::HighloadWallet::Gift gift;
gift.destination = block::StdAddress::parse(dest_str).move_as_ok();
gift.gramms = gramms;
gifts.push_back(gift);
};
std::string dest_str = "Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX";
add_order(dest_str, 0);
add_order(dest_str, 321000000000ll);
add_order(dest_str, 321ll);
fift_output.source_lookup.write_file("/order", order).ensure();
class ZeroOsTime : public fift::OsTime {
public:
td::uint32 now() override {
return 0;
}
};
init_data.seqno = 123;
wallet = ton::HighloadWallet::create(init_data, -1);
fift_output.source_lookup.set_os_time(std::make_unique<ZeroOsTime>());
fift_output = fift::mem_run_fift(std::move(fift_output.source_lookup), {"aba", "new-wallet", "239", "123", "order"})
.move_as_ok();
auto wallet_query = fift_output.source_lookup.read_file("wallet-query.boc").move_as_ok().data;
auto gift_message = ton::GenericAccount::create_ext_message(
address, {}, wallet->make_a_gift_message(priv_key, 60, gifts).move_as_ok());
LOG(ERROR) << "---smc-envelope----";
vm::load_cell_slice(gift_message).print_rec(std::cerr);
LOG(ERROR) << "---fift scripts----";
vm::load_cell_slice(vm::std_boc_deserialize(wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == gift_message->get_hash());
}
TEST(Tonlib, HighloadWalletV2) {
auto source_lookup = fift::create_mem_source_lookup(load_source("smartcont/new-highload-wallet-v2.fif")).move_as_ok();
source_lookup
.write_file("/auto/highload-wallet-v2-code.fif", load_source("smartcont/auto/highload-wallet-v2-code.fif"))
.ensure();
class ZeroOsTime : public fift::OsTime {
public:
td::uint32 now() override {
return 0;
}
};
source_lookup.set_os_time(std::make_unique<ZeroOsTime>());
auto fift_output = fift::mem_run_fift(std::move(source_lookup), {"aba", "0", "239"}).move_as_ok();
LOG(ERROR) << fift_output.output;
auto new_wallet_pk = fift_output.source_lookup.read_file("new-wallet.pk").move_as_ok().data;
auto new_wallet_query = fift_output.source_lookup.read_file("new-wallet239-query.boc").move_as_ok().data;
auto new_wallet_addr = fift_output.source_lookup.read_file("new-wallet239.addr").move_as_ok().data;
td::Ed25519::PrivateKey priv_key{td::SecureString{new_wallet_pk}};
auto pub_key = priv_key.get_public_key().move_as_ok();
ton::HighloadWalletV2::InitData init_data(pub_key.as_octet_string(), 239);
auto wallet = ton::HighloadWalletV2::create(init_data, -1);
auto address = wallet->get_address();
ASSERT_EQ(239u, wallet->get_wallet_id().ok());
wallet->get_seqno().ensure_error();
CHECK(pub_key.as_octet_string() == wallet->get_public_key().ok().as_octet_string());
CHECK(pub_key.as_octet_string() == ton::GenericAccount::get_public_key(*wallet).ok().as_octet_string());
CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32));
auto init_message = wallet->get_init_message(priv_key, 65535).move_as_ok();
td::Ref<vm::Cell> res = ton::GenericAccount::create_ext_message(
address, ton::GenericAccount::get_init_state(wallet->get_state()), init_message);
LOG(ERROR) << "---smc-envelope----";
vm::load_cell_slice(res).print_rec(std::cerr);
LOG(ERROR) << "---fift scripts----";
vm::load_cell_slice(vm::std_boc_deserialize(new_wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(new_wallet_query).move_as_ok()->get_hash() == res->get_hash());
fift_output.source_lookup.write_file("/main.fif", load_source("smartcont/highload-wallet-v2.fif")).ensure();
std::string order;
std::vector<ton::HighloadWalletV2::Gift> gifts;
auto add_order = [&](td::Slice dest_str, td::int64 gramms) {
auto g = td::to_string(gramms);
if (g.size() < 10) {
g = std::string(10 - g.size(), '0') + g;
}
order += PSTRING() << "SEND " << dest_str << " " << g.substr(0, g.size() - 9) << "." << g.substr(g.size() - 9)
<< "\n";
ton::HighloadWalletV2::Gift gift;
gift.destination = block::StdAddress::parse(dest_str).move_as_ok();
gift.gramms = gramms;
gifts.push_back(gift);
};
std::string dest_str = "Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX";
add_order(dest_str, 0);
add_order(dest_str, 321000000000ll);
add_order(dest_str, 321ll);
fift_output.source_lookup.write_file("/order", order).ensure();
fift_output.source_lookup.set_os_time(std::make_unique<ZeroOsTime>());
fift_output =
fift::mem_run_fift(std::move(fift_output.source_lookup), {"aba", "new-wallet", "239", "order"}).move_as_ok();
auto wallet_query = fift_output.source_lookup.read_file("wallet-query.boc").move_as_ok().data;
auto gift_message = ton::GenericAccount::create_ext_message(
address, {}, wallet->make_a_gift_message(priv_key, 60, gifts).move_as_ok());
LOG(ERROR) << "---smc-envelope----";
vm::load_cell_slice(gift_message).print_rec(std::cerr);
LOG(ERROR) << "---fift scripts----";
vm::load_cell_slice(vm::std_boc_deserialize(wallet_query).move_as_ok()).print_rec(std::cerr);
CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == gift_message->get_hash());
}
TEST(Tonlib, RestrictedWallet) {
//auto source_lookup = fift::create_mem_source_lookup(load_source("smartcont/new-restricted-wallet2.fif")).move_as_ok();
//source_lookup
//.write_file("/auto/restricted-wallet2-code.fif", load_source("smartcont/auto/restricted-wallet2-code.fif"))
//.ensure();
//class ZeroOsTime : public fift::OsTime {
//public:
//td::uint32 now() override {
//return 0;
//}
//};
//source_lookup.set_os_time(std::make_unique<ZeroOsTime>());
//auto priv_key = td::Ed25519::generate_private_key().move_as_ok();
//auto pub_key = priv_key.get_public_key().move_as_ok();
//auto pub_key_serialized = block::PublicKey::from_bytes(pub_key.as_octet_string()).move_as_ok().serialize(true);
//std::vector<std::string> args = {"path", pub_key_serialized, std::string("100")};
//auto fift_output = fift::mem_run_fift(std::move(source_lookup), args).move_as_ok();
//ton::RestrictedWallet::InitData init_data;
//td::uint64 x = 100 * 1000000000ull;
//init_data.key = &pub_key;
//init_data.start_at = 0;
//init_data.limits = {{-32768, x}, {92, x * 3 / 4}, {183, x * 1 / 2}, {366, x * 1 / 4}, {548, 0}};
//auto wallet = ton::RestrictedWallet::create(init_data, -1);
//ASSERT_EQ(0u, wallet->get_seqno().move_as_ok());
//CHECK(pub_key.as_octet_string() == wallet->get_public_key().move_as_ok().as_octet_string());
////LOG(ERROR) << wallet->get_balance(x, 60 * 60 * 24 * 400).move_as_ok();
//auto new_wallet_query = fift_output.source_lookup.read_file("rwallet-query.boc").move_as_ok().data;
//auto new_wallet_addr = fift_output.source_lookup.read_file("rwallet.addr").move_as_ok().data;
//auto address = wallet->get_address(-1);
////CHECK(address.addr.as_slice() == td::Slice(new_wallet_addr).substr(0, 32));
//address.bounceable = false;
//auto res = ton::GenericAccount::create_ext_message(address, wallet->get_init_state(),
//wallet->get_init_message(priv_key).move_as_ok());
//LOG(ERROR) << "-------";
//vm::load_cell_slice(res).print_rec(std::cerr);
//LOG(ERROR) << "-------";
//vm::load_cell_slice(vm::std_boc_deserialize(new_wallet_query).move_as_ok()).print_rec(std::cerr);
//CHECK(vm::std_boc_deserialize(new_wallet_query).move_as_ok()->get_hash() == res->get_hash());
//auto dest = block::StdAddress::parse("Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX").move_as_ok();
//fift_output.source_lookup.write_file("/main.fif", load_source("smartcont/wallet-v2.fif")).ensure();
//fift_output.source_lookup.write_file("rwallet.pk", priv_key.as_octet_string().as_slice()).ensure();
//fift_output = fift::mem_run_fift(
//std::move(fift_output.source_lookup),
//{"aba", "rwallet", "-C", "TESTv2", "Ef9Tj6fMJP+OqhAdhKXxq36DL+HYSzCc3+9O6UNzqsgPfYFX", "0", "321"})
//.move_as_ok();
//auto wallet_query = fift_output.source_lookup.read_file("wallet-query.boc").move_as_ok().data;
//ton::TestWallet::Gift gift;
//gift.destination = dest;
//gift.message = "TESTv2";
//gift.gramms = 321000000000ll;
////CHECK(priv_key.get_public_key().ok().as_octet_string() == wallet->get_public_key().ok().as_octet_string());
//auto gift_message = ton::GenericAccount::create_ext_message(
//address, {}, wallet->make_a_gift_message(priv_key, 60, {gift}).move_as_ok());
//LOG(ERROR) << "-------";
//vm::load_cell_slice(gift_message).print_rec(std::cerr);
//LOG(ERROR) << "-------";
//vm::load_cell_slice(vm::std_boc_deserialize(wallet_query).move_as_ok()).print_rec(std::cerr);
//CHECK(vm::std_boc_deserialize(wallet_query).move_as_ok()->get_hash() == gift_message->get_hash());
}
TEST(Tonlib, RestrictedWallet3) {
auto init_priv_key = td::Ed25519::generate_private_key().move_as_ok();
auto init_pub_key = init_priv_key.get_public_key().move_as_ok();
auto priv_key = td::Ed25519::generate_private_key().move_as_ok();
auto pub_key = priv_key.get_public_key().move_as_ok();
ton::RestrictedWallet::InitData init_data;
init_data.init_key = init_pub_key.as_octet_string();
init_data.main_key = pub_key.as_octet_string();
init_data.wallet_id = 123;
auto wallet = ton::RestrictedWallet::create(init_data, 1);
auto address = wallet->get_address();
td::uint64 x = 100 * 1000000000ull;
ton::RestrictedWallet::Config config;
config.start_at = 1;
config.limits = {{-32768, x}, {92, x * 3 / 4}, {183, x * 1 / 2}, {366, x * 1 / 4}, {548, 0}};
CHECK(wallet.write().send_external_message(wallet->get_init_message(init_priv_key, 10, config).move_as_ok()).success);
CHECK(wallet->get_seqno().move_as_ok() == 1);
ton::WalletInterface::Gift gift;
gift.destination = address;
gift.message = "hello";
CHECK(wallet.write().send_external_message(wallet->make_a_gift_message(priv_key, 10, {gift}).move_as_ok()).success);
CHECK(wallet->get_seqno().move_as_ok() == 2);
}
template <class T>
void check_wallet_seqno(td::Ref<T> wallet, td::uint32 seqno) {
ASSERT_EQ(seqno, wallet->get_seqno().ok());
}
void check_wallet_seqno(td::Ref<ton::HighloadWalletV2> wallet, td::uint32 seqno) {
}
void check_wallet_seqno(td::Ref<ton::WalletInterface> wallet, td::uint32 seqno) {
}
template <class T>
void check_wallet_state(td::Ref<T> wallet, td::uint32 seqno, td::uint32 wallet_id, td::Slice public_key) {
ASSERT_EQ(wallet_id, wallet->get_wallet_id().ok());
ASSERT_EQ(public_key, wallet->get_public_key().ok().as_octet_string().as_slice());
check_wallet_seqno(wallet, seqno);
}
struct CreatedWallet {
td::optional<td::Ed25519::PrivateKey> priv_key;
block::StdAddress address;
td::Ref<ton::WalletInterface> wallet;
};
template <class T>
class InitWallet {
public:
CreatedWallet operator()(int revision) const {
ton::WalletInterface::DefaultInitData init_data;
auto priv_key = td::Ed25519::generate_private_key().move_as_ok();
auto pub_key = priv_key.get_public_key().move_as_ok();
init_data.seqno = 0;
init_data.wallet_id = 123;
init_data.public_key = pub_key.as_octet_string();
auto wallet = T::create(init_data, revision);
auto address = wallet->get_address();
check_wallet_state(wallet, 0, 123, init_data.public_key);
CHECK(wallet.write().send_external_message(wallet->get_init_message(priv_key).move_as_ok()).success);
CreatedWallet res;
res.wallet = std::move(wallet);
res.address = std::move(address);
res.priv_key = std::move(priv_key);
return res;
}
};
template <>
CreatedWallet InitWallet<ton::RestrictedWallet>::operator()(int revision) const {
auto init_priv_key = td::Ed25519::generate_private_key().move_as_ok();
auto init_pub_key = init_priv_key.get_public_key().move_as_ok();
auto priv_key = td::Ed25519::generate_private_key().move_as_ok();
auto pub_key = priv_key.get_public_key().move_as_ok();
ton::RestrictedWallet::InitData init_data;
init_data.init_key = init_pub_key.as_octet_string();
init_data.main_key = pub_key.as_octet_string();
init_data.wallet_id = 123;
auto wallet = ton::RestrictedWallet::create(init_data, 1);
check_wallet_state(wallet, 0, 123, init_data.init_key);
auto address = wallet->get_address();
td::uint64 x = 100 * 1000000000ull;
ton::RestrictedWallet::Config config;
config.start_at = 1;
config.limits = {{-32768, x}, {92, x * 3 / 4}, {183, x * 1 / 2}, {366, x * 1 / 4}, {548, 0}};
CHECK(wallet.write().send_external_message(wallet->get_init_message(init_priv_key, 10, config).move_as_ok()).success);
CHECK(wallet->get_seqno().move_as_ok() == 1);
CreatedWallet res;
res.wallet = std::move(wallet);
res.address = std::move(address);
res.priv_key = std::move(priv_key);
return res;
}
template <class T>
void do_test_wallet(int revision) {
auto res = InitWallet<T>()(revision);
auto priv_key = res.priv_key.unwrap();
auto address = std::move(res.address);
auto iwallet = std::move(res.wallet);
auto public_key = priv_key.get_public_key().move_as_ok().as_octet_string();
;
check_wallet_state(iwallet, 1, 123, public_key);
// lets send a lot of messages
std::vector<ton::WalletInterface::Gift> gifts;
for (size_t i = 0; i < iwallet->get_max_gifts_size(); i++) {
ton::WalletInterface::Gift gift;
gift.gramms = 1;
gift.destination = address;
gift.message = std::string(iwallet->get_max_message_size(), 'z');
gifts.push_back(gift);
}
td::uint32 valid_until = 10000;
auto send_gifts = iwallet->make_a_gift_message(priv_key, valid_until, gifts).move_as_ok();
{
auto cwallet = iwallet;
CHECK(!cwallet.write()
.send_external_message(send_gifts, ton::SmartContract::Args().set_now(valid_until + 1))
.success);
}
//TODO: make wallet work (or not) with now == valid_until
auto ans = iwallet.write().send_external_message(send_gifts, ton::SmartContract::Args().set_now(valid_until - 1));
CHECK(ans.success);
CHECK((int)gifts.size() <= ans.output_actions_count(ans.actions));
check_wallet_state(iwallet, 2, 123, public_key);
}
template <class T>
void do_test_wallet() {
for (auto revision : T::get_revisions()) {
do_test_wallet<T>(revision);
}
}
TEST(Tonlib, Wallet) {
do_test_wallet<ton::WalletV3>();
do_test_wallet<ton::HighloadWallet>();
do_test_wallet<ton::HighloadWalletV2>();
do_test_wallet<ton::RestrictedWallet>();
}
namespace std { // ouch
bool operator<(const ton::MultisigWallet::Mask& a, const ton::MultisigWallet::Mask& b) {
for (size_t i = 0; i < a.size(); i++) {
if (a[i] != b[i]) {
return a[i] < b[i];
}
}
return false;
}
} // namespace std
TEST(Smartcon, Multisig) {
auto ms_lib = ton::MultisigWallet::create();
int n = 100;
int k = 99;
td::uint32 wallet_id = std::numeric_limits<td::uint32>::max() - 3;
std::vector<td::Ed25519::PrivateKey> keys;
for (int i = 0; i < n; i++) {
keys.push_back(td::Ed25519::generate_private_key().move_as_ok());
}
auto init_state = ms_lib->create_init_data(
wallet_id, td::transform(keys, [](auto& key) { return key.get_public_key().ok().as_octet_string(); }), k);
auto ms = ton::MultisigWallet::create(init_state);
td::uint32 now = 0;
auto args = [&now]() -> ton::SmartContract::Args { return ton::SmartContract::Args().set_now(now); };
// first empty query (init)
CHECK(ms.write().send_external_message(vm::CellBuilder().finalize(), args()).code == 0);
// first empty query
CHECK(ms.write().send_external_message(vm::CellBuilder().finalize(), args()).code > 0);
{
td::uint64 query_id = 123 | ((now + 10 * 60ull) << 32);
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
auto query = qb.create(0, keys[0]);
auto res = ms.write().send_external_message(query, args());
CHECK(!res.accepted);
CHECK(res.code == 41);
}
{
for (int i = 1; i <= 11; i++) {
td::uint64 query_id = i | ((now + 100 * 60ull) << 32);
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
auto query = qb.create(5, keys[5]);
auto res = ms.write().send_external_message(query, args());
if (i <= 10) {
CHECK(res.accepted);
} else {
CHECK(!res.accepted);
}
}
now += 100 * 60 + 100;
{
td::uint64 query_id = 200 | ((now + 100 * 60ull) << 32);
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
auto query = qb.create(6, keys[6]);
auto res = ms.write().send_external_message(query, args());
CHECK(res.accepted);
}
{
td::uint64 query_id = 300 | ((now + 100 * 60ull) << 32);
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
auto query = qb.create(5, keys[5]);
auto res = ms.write().send_external_message(query, args());
CHECK(res.accepted);
}
}
td::uint64 query_id = 123 | ((now + 100 * 60ull) << 32);
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
for (int i = 0; i < 10; i++) {
auto query = qb.create(i, keys[i]);
auto ans = ms.write().send_external_message(query, args());
LOG(INFO) << "CODE: " << ans.code;
LOG(INFO) << "GAS: " << ans.gas_used;
}
for (int i = 0; i + 1 < 50; i++) {
qb.sign(i, keys[i]);
}
auto query = qb.create(49, keys[49]);
CHECK(ms->get_n_k() == std::make_pair(n, k));
auto ans = ms.write().send_external_message(query, args());
LOG(INFO) << "CODE: " << ans.code;
LOG(INFO) << "GAS: " << ans.gas_used;
CHECK(ans.success);
ASSERT_EQ(0, ms->processed(query_id));
CHECK(ms.write().send_external_message(query, args()).code > 0);
ASSERT_EQ(0, ms->processed(query_id));
{
ton::MultisigWallet::QueryBuilder qb(wallet_id, query_id, vm::CellBuilder().finalize());
for (int i = 50; i + 1 < 100; i++) {
qb.sign(i, keys[i]);
}
query = qb.create(99, keys[99]);
}
ans = ms.write().send_external_message(query, args());
LOG(INFO) << "CODE: " << ans.code;
LOG(INFO) << "GAS: " << ans.gas_used;
ASSERT_EQ(-1, ms->processed(query_id));
}
TEST(Smartcont, MultisigStress) {
int n = 10;
int k = 5;
td::uint32 wallet_id = std::numeric_limits<td::uint32>::max() - 3;
std::vector<td::Ed25519::PrivateKey> keys;
for (int i = 0; i < n; i++) {
keys.push_back(td::Ed25519::generate_private_key().move_as_ok());
}
auto public_keys = td::transform(keys, [](auto& key) { return key.get_public_key().ok().as_octet_string(); });
auto ms_lib = ton::MultisigWallet::create();
auto init_state_old =
ms_lib->create_init_data_fast(wallet_id, td::transform(public_keys, [](auto& key) { return key.copy(); }), k);
auto init_state =
ms_lib->create_init_data(wallet_id, td::transform(public_keys, [](auto& key) { return key.copy(); }), k);
CHECK(init_state_old->get_hash() == init_state->get_hash());
auto ms = ton::MultisigWallet::create(init_state);
CHECK(ms->get_public_keys() == public_keys);
td::int32 now = 100 * 60;
td::int32 qid = 1;
using Mask = std::bitset<128>;
struct Query {
td::int64 id;
td::Ref<vm::Cell> message;
Mask signed_mask;
};
std::vector<Query> queries;
int max_queries = 300;
td::Random::Xorshift128plus rnd(123);
auto new_query = [&] {
if (qid > max_queries) {
return;
}
Query query;
query.id = (static_cast<td::int64>(now) << 32) | qid++;
query.message = vm::CellBuilder().store_bytes(td::rand_string('a', 'z', rnd.fast(0, 100))).finalize();
queries.push_back(std::move(query));
};
auto verify = [&] {
auto messages = ms->get_unsigned_messaged();
std::set<std::tuple<td::uint64, ton::MultisigWallet::Mask, std::string>> s;
std::set<std::tuple<td::uint64, ton::MultisigWallet::Mask, std::string>> t;
for (auto& m : messages) {
auto x = std::make_tuple(m.query_id, m.signed_by, m.message->get_hash().as_slice().str());
s.insert(std::move(x));
}
for (auto& q : queries) {
if (q.signed_mask.none()) {
continue;
}
t.insert(std::make_tuple(q.id, q.signed_mask, q.message->get_hash().as_slice().str()));
}
ASSERT_EQ(t.size(), s.size());
CHECK(s == t);
};
auto sign_query = [&](Query& query, Mask mask) {
auto qb = ton::MultisigWallet::QueryBuilder(wallet_id, query.id, query.message);
int first_i = -1;
for (int i = 0; i < (int)mask.size(); i++) {
if (mask.test(i)) {
if (first_i == -1) {
first_i = i;
} else {
qb.sign(i, keys[i]);
}
}
}
return qb.create(first_i, keys[first_i]);
};
auto send_signature = [&](td::Ref<vm::Cell> query) {
auto ans = ms.write().send_external_message(query);
LOG(ERROR) << "GAS: " << ans.gas_used;
return ans.code == 0;
};
auto is_ready = [&](Query& query) { return ms->processed(query.id) == -1; };
auto gen_query = [&](Query& query) {
auto x = rnd.fast(1, n);
Mask mask;
for (int t = 0; t < x; t++) {
mask.set(rnd() % n);
}
auto signature = sign_query(query, mask);
return std::make_pair(signature, mask);
};
auto rand_sign = [&] {
if (queries.empty()) {
return;
}
size_t query_i = rnd() % queries.size();
auto& query = queries[query_i];
Mask mask;
td::Ref<vm::Cell> signature;
std::tie(signature, mask) = gen_query(query);
if (false && rnd() % 6 == 0) {
Mask mask2;
td::Ref<vm::Cell> signature2;
std::tie(signature2, mask2) = gen_query(query);
for (int i = 0; i < (int)keys.size(); i++) {
if (mask[i]) {
signature = ms->merge_queries(std::move(signature), std::move(signature2));
break;
}
if (mask2[i]) {
signature = ms->merge_queries(std::move(signature2), std::move(signature));
break;
}
}
//signature = ms->merge_queries(std::move(signature), std::move(signature2));
mask |= mask2;
}
int got_cnt;
Mask got_cnt_bits;
std::tie(got_cnt, got_cnt_bits) = ms->check_query_signatures(signature);
CHECK(mask == got_cnt_bits);
bool expect_ok = true;
{
auto new_mask = mask & ~query.signed_mask;
expect_ok &= new_mask.any();
for (size_t i = 0; i < mask.size(); i++) {
if (mask[i]) {
expect_ok &= new_mask[i];
break;
}
}
}
ASSERT_EQ(expect_ok, send_signature(std::move(signature)));
if (expect_ok) {
query.signed_mask |= mask;
}
auto expect_is_ready = query.signed_mask.count() >= (size_t)k;
auto state = ms->get_query_state(query.id);
ASSERT_EQ(expect_is_ready, (state.state == ton::MultisigWallet::QueryState::Sent));
CHECK(expect_is_ready || state.mask == query.signed_mask);
ASSERT_EQ(expect_is_ready, is_ready(query));
if (expect_is_ready) {
queries.erase(queries.begin() + query_i);
}
verify();
};
td::RandomSteps steps({{rand_sign, 2}, {new_query, 1}});
while (!queries.empty() || qid <= max_queries) {
steps.step(rnd);
//LOG(ERROR) << ms->data_size();
}
LOG(INFO) << "Final code size: " << ms->code_size();
LOG(INFO) << "Final data size: " << ms->data_size();
}
class MapDns {
public:
using ManualDns = ton::ManualDns;
struct Entry {
std::string name;
td::int16 category{0};
std::string text;
auto key() const {
return std::tie(name, category);
}
bool operator<(const Entry& other) const {
return key() < other.key();
}
bool operator==(const ton::DnsInterface::Entry& other) const {
return key() == other.key() && other.data.type == ManualDns::EntryData::Type::Text &&
other.data.data.get<ManualDns::EntryDataText>().text == text;
}
bool operator==(const Entry& other) const {
return key() == other.key() && text == other.text;
}
friend td::StringBuilder& operator<<(td::StringBuilder& sb, const Entry& entry) {
return sb << "[" << entry.name << ":" << entry.category << ":" << entry.text << "]";
}
};
struct Action {
std::string name;
td::int16 category{0};
td::optional<std::string> text;
bool does_create_category() const {
CHECK(!name.empty());
CHECK(category != 0);
return static_cast<bool>(text);
}
bool does_change_empty() const {
CHECK(!name.empty());
CHECK(category != 0);
return static_cast<bool>(text) && !text.value().empty();
}
void make_non_empty() {
CHECK(!name.empty());
CHECK(category != 0);
if (!text) {
text = "";
}
}
friend td::StringBuilder& operator<<(td::StringBuilder& sb, const Action& entry) {
return sb << "[" << entry.name << ":" << entry.category << ":" << (entry.text ? entry.text.value() : "<empty>")
<< "]";
}
};
void update(td::Span<Action> actions) {
for (auto& action : actions) {
do_update(action);
}
}
using CombinedActions = ton::ManualDns::CombinedActions<Action>;
void update_combined(td::Span<Action> actions) {
LOG(ERROR) << "BEGIN";
LOG(ERROR) << td::format::as_array(actions);
auto combined_actions = ton::ManualDns::combine_actions(actions);
for (auto& c : combined_actions) {
LOG(ERROR) << c.name << ":" << c.category;
if (c.actions) {
LOG(ERROR) << td::format::as_array(c.actions.value());
}
}
LOG(ERROR) << "END";
for (auto& combined_action : combined_actions) {
do_update(combined_action);
}
}
std::vector<Entry> resolve(td::Slice name, td::int16 category) {
std::vector<Entry> res;
if (name.empty()) {
for (auto& a : entries_) {
for (auto& b : a.second) {
res.push_back({a.first, b.first, b.second});
}
}
} else {
auto it = entries_.find(name);
while (it == entries_.end()) {
auto sz = name.find('.');
category = -1;
if (sz != td::Slice::npos) {
name = name.substr(sz + 1);
} else {
break;
}
it = entries_.find(name);
}
if (it != entries_.end()) {
for (auto& b : it->second) {
if (category == 0 || category == b.first) {
res.push_back({name.str(), b.first, b.second});
}
}
}
}
std::sort(res.begin(), res.end());
return res;
}
private:
std::map<std::string, std::map<td::int16, std::string>, std::less<>> entries_;
void do_update(const Action& action) {
if (action.name.empty()) {
entries_.clear();
return;
}
if (action.category == 0) {
entries_.erase(action.name);
return;
}
if (action.text) {
if (action.text.value().empty()) {
entries_[action.name].erase(action.category);
} else {
entries_[action.name][action.category] = action.text.value();
}
} else {
auto it = entries_.find(action.name);
if (it != entries_.end()) {
it->second.erase(action.category);
}
}
}
void do_update(const CombinedActions& actions) {
if (actions.name.empty()) {
entries_.clear();
LOG(ERROR) << "CLEAR";
if (!actions.actions) {
return;
}
for (auto& action : actions.actions.value()) {
CHECK(!action.name.empty());
CHECK(action.category != 0);
CHECK(action.text);
if (action.text.value().empty()) {
entries_[action.name];
} else {
entries_[action.name][action.category] = action.text.value();
}
}
return;
}
if (actions.category == 0) {
entries_.erase(actions.name);
LOG(ERROR) << "CLEAR " << actions.name;
if (!actions.actions) {
return;
}
entries_[actions.name];
for (auto& action : actions.actions.value()) {
CHECK(action.name == actions.name);
CHECK(action.category != 0);
CHECK(action.text);
if (action.text.value().empty()) {
entries_[action.name];
} else {
entries_[action.name][action.category] = action.text.value();
}
}
return;
}
CHECK(actions.actions);
CHECK(actions.actions.value().size() == 1);
for (auto& action : actions.actions.value()) {
CHECK(action.name == actions.name);
CHECK(action.category != 0);
if (action.text) {
if (action.text.value().empty()) {
entries_[action.name].erase(action.category);
} else {
entries_[action.name][action.category] = action.text.value();
}
} else {
auto it = entries_.find(action.name);
if (it != entries_.end()) {
it->second.erase(action.category);
}
}
}
}
};
class CheckedDns {
public: