-
Notifications
You must be signed in to change notification settings - Fork 6k
/
Copy pathprotoToAbiV2.cpp
1407 lines (1273 loc) · 41.1 KB
/
protoToAbiV2.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
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <boost/preprocessor.hpp>
#include <regex>
/// Convenience macros
/// Returns a valid Solidity integer width w such that 8 <= w <= 256.
#define INTWIDTH(z, n, _ununsed) BOOST_PP_MUL(BOOST_PP_ADD(n, 1), 8)
/// Using declaration that aliases long boost multiprecision types with
/// s(u)<width> where <width> is a valid Solidity integer width and "s"
/// stands for "signed" and "u" for "unsigned".
#define USINGDECL(z, n, sign) \
using BOOST_PP_CAT(BOOST_PP_IF(sign, s, u), INTWIDTH(z, n,)) = \
boost::multiprecision::number< \
boost::multiprecision::cpp_int_backend< \
INTWIDTH(z, n,), \
INTWIDTH(z, n,), \
BOOST_PP_IF( \
sign, \
boost::multiprecision::signed_magnitude, \
boost::multiprecision::unsigned_magnitude \
), \
boost::multiprecision::unchecked, \
void \
> \
>;
/// Instantiate the using declarations for signed and unsigned integer types.
BOOST_PP_REPEAT(32, USINGDECL, 1)
BOOST_PP_REPEAT(32, USINGDECL, 0)
/// Case implementation that returns an integer value of the specified type.
/// For signed integers, we divide by two because the range for boost multiprecision
/// types is double that of Solidity integer types. Example, 8-bit signed boost
/// number range is [-255, 255] but Solidity `int8` range is [-128, 127]
#define CASEIMPL(z, n, sign) \
case INTWIDTH(z, n,): \
stream << BOOST_PP_IF( \
sign, \
integerValue< \
BOOST_PP_CAT( \
BOOST_PP_IF(sign, s, u), \
INTWIDTH(z, n,) \
)>(_counter) / 2, \
integerValue< \
BOOST_PP_CAT( \
BOOST_PP_IF(sign, s, u), \
INTWIDTH(z, n,) \
)>(_counter) \
); \
break;
/// Switch implementation that instantiates case statements for (un)signed
/// Solidity integer types.
#define SWITCHIMPL(sign) \
std::ostringstream stream; \
switch (_intWidth) \
{ \
BOOST_PP_REPEAT(32, CASEIMPL, sign) \
} \
return stream.str();
using namespace solidity::util;
using namespace solidity::test::abiv2fuzzer;
namespace
{
template <typename V>
static V integerValue(unsigned _counter)
{
V value = V(
u256(solidity::util::keccak256(solidity::util::h256(_counter))) % u256(boost::math::tools::max_value<V>())
);
if (boost::multiprecision::is_signed_number<V>::value && value % 2 == 0)
return value * (-1);
else
return value;
}
static std::string signedIntegerValue(unsigned _counter, unsigned _intWidth)
{
SWITCHIMPL(1)
}
static std::string unsignedIntegerValue(unsigned _counter, unsigned _intWidth)
{
SWITCHIMPL(0)
}
static std::string integerValue(unsigned _counter, unsigned _intWidth, bool _signed)
{
if (_signed)
return signedIntegerValue(_counter, _intWidth);
else
return unsignedIntegerValue(_counter, _intWidth);
}
}
std::string ProtoConverter::getVarDecl(
std::string const& _type,
std::string const& _varName,
std::string const& _qualifier
)
{
// One level of indentation for state variable declarations
// Two levels of indentation for local variable declarations
return Whiskers(R"(
<?isLocalVar> </isLocalVar><type><?qual> <qualifier></qual> <varName>;)"
)
("isLocalVar", !m_isStateVar)
("type", _type)
("qual", !_qualifier.empty())
("qualifier", _qualifier)
("varName", _varName)
.render() +
"\n";
}
std::pair<std::string, std::string> ProtoConverter::visit(Type const& _type)
{
switch (_type.type_oneof_case())
{
case Type::kVtype:
return visit(_type.vtype());
case Type::kNvtype:
return visit(_type.nvtype());
case Type::TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(ValueType const& _type)
{
switch (_type.value_type_oneof_case())
{
case ValueType::kBoolty:
return visit(_type.boolty());
case ValueType::kInty:
return visit(_type.inty());
case ValueType::kByty:
return visit(_type.byty());
case ValueType::kAdty:
return visit(_type.adty());
case ValueType::VALUE_TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(NonValueType const& _type)
{
switch (_type.nonvalue_type_oneof_case())
{
case NonValueType::kDynbytearray:
return visit(_type.dynbytearray());
case NonValueType::kArrtype:
if (ValidityVisitor().visit(_type.arrtype()))
return visit(_type.arrtype());
else
return std::make_pair("", "");
case NonValueType::kStype:
if (ValidityVisitor().visit(_type.stype()))
return visit(_type.stype());
else
return std::make_pair("", "");
case NonValueType::NONVALUE_TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(BoolType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(IntegerType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(FixedByteType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(AddressType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(DynamicByteArrayType const& _type)
{
return processType(_type, false);
}
std::pair<std::string, std::string> ProtoConverter::visit(ArrayType const& _type)
{
return processType(_type, false);
}
std::pair<std::string, std::string> ProtoConverter::visit(StructType const& _type)
{
return processType(_type, false);
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::processType(T const& _type, bool _isValueType)
{
std::ostringstream local, global;
auto [varName, paramName] = newVarNames(getNextVarCounter(), m_isStateVar);
// Add variable name to the argument list of coder function call
if (m_argsCoder.str().empty())
m_argsCoder << varName;
else
m_argsCoder << ", " << varName;
std::string location{};
if (!m_isStateVar && !_isValueType)
location = "memory";
auto varDeclBuffers = varDecl(
varName,
paramName,
_type,
_isValueType,
location
);
global << varDeclBuffers.first;
local << varDeclBuffers.second;
auto assignCheckBuffers = assignChecker(varName, paramName, _type);
global << assignCheckBuffers.first;
local << assignCheckBuffers.second;
m_structCounter += m_numStructsAdded;
return std::make_pair(global.str(), local.str());
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::varDecl(
std::string const& _varName,
std::string const& _paramName,
T _type,
bool _isValueType,
std::string const& _location
)
{
std::ostringstream local, global;
TypeVisitor tVisitor(m_structCounter);
std::string typeStr = tVisitor.visit(_type);
if (typeStr.empty())
return std::make_pair("", "");
// Append struct defs
global << tVisitor.structDef();
m_numStructsAdded = tVisitor.numStructs();
// variable declaration
if (m_isStateVar)
global << getVarDecl(typeStr, _varName, _location);
else
local << getVarDecl(typeStr, _varName, _location);
// Add typed params for calling public and external functions with said type
appendTypedParams(
CalleeType::PUBLIC,
_isValueType,
typeStr,
_paramName,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypedParams(
CalleeType::EXTERNAL,
_isValueType,
typeStr,
_paramName,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypes(
_isValueType,
typeStr,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypedReturn(
_isValueType,
typeStr,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendToIsabelleTypeString(
tVisitor.isabelleTypeString(),
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
// Update dyn param only if necessary
if (tVisitor.isLastDynParamRightPadded())
m_isLastDynParamRightPadded = true;
return std::make_pair(global.str(), local.str());
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::assignChecker(
std::string const& _varName,
std::string const& _paramName,
T _type
)
{
std::ostringstream local;
AssignCheckVisitor acVisitor(
_varName,
_paramName,
m_returnValue,
m_isStateVar,
m_counter,
m_structCounter
);
std::pair<std::string, std::string> assignCheckStrPair = acVisitor.visit(_type);
m_returnValue += acVisitor.errorStmts();
m_counter += acVisitor.counted();
m_checks << assignCheckStrPair.second;
appendToIsabelleValueString(
acVisitor.isabelleValueString(),
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
// State variables cannot be assigned in contract-scope
// Therefore, we buffer their assignments and
// render them in function scope later.
local << assignCheckStrPair.first;
return std::make_pair("", local.str());
}
std::pair<std::string, std::string> ProtoConverter::visit(VarDecl const& _x)
{
return visit(_x.type());
}
std::string ProtoConverter::equalityChecksAsString()
{
return m_checks.str();
}
std::string ProtoConverter::delimiterToString(Delimiter _delimiter, bool _space)
{
switch (_delimiter)
{
case Delimiter::ADD:
return _space ? ", " : ",";
case Delimiter::SKIP:
return "";
}
}
/* When a new variable is declared, we can invoke this function
* to prepare the typed param list to be passed to callee functions.
* We independently prepare this list for "public" and "external"
* callee functions.
*/
void ProtoConverter::appendTypedParams(
CalleeType _calleeType,
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
switch (_calleeType)
{
case CalleeType::PUBLIC:
appendTypedParamsPublic(_isValueType, _typeString, _varName, _delimiter);
break;
case CalleeType::EXTERNAL:
appendTypedParamsExternal(_isValueType, _typeString, _varName, _delimiter);
break;
}
}
void ProtoConverter::appendTypes(
bool _isValueType,
std::string const& _typeString,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_types << Whiskers(R"(<delimiter><type>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
.render();
}
void ProtoConverter::appendTypedReturn(
bool _isValueType,
std::string const& _typeString,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_typedReturn << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
("varName", "lv_" + std::to_string(m_varCounter - 1))
.render();
}
// Adds the qualifier "calldata" to non-value parameter of an external function.
void ProtoConverter::appendTypedParamsExternal(
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
m_externalParamsRep.push_back({_delimiter, _isValueType, _typeString, _varName});
m_untypedParamsExternal << Whiskers(R"(<delimiter><varName>)")
("delimiter", delimiterToString(_delimiter))
("varName", _varName)
.render();
}
// Adds the qualifier "memory" to non-value parameter of an external function.
void ProtoConverter::appendTypedParamsPublic(
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_typedParamsPublic << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
("varName", _varName)
.render();
}
void ProtoConverter::appendToIsabelleTypeString(
std::string const& _typeString,
Delimiter _delimiter
)
{
m_isabelleTypeString << delimiterToString(_delimiter, false) << _typeString;
}
void ProtoConverter::appendToIsabelleValueString(
std::string const& _valueString,
Delimiter _delimiter
)
{
m_isabelleValueString << delimiterToString(_delimiter, false) << _valueString;
}
std::string ProtoConverter::typedParametersAsString(CalleeType _calleeType)
{
switch (_calleeType)
{
case CalleeType::PUBLIC:
return m_typedParamsPublic.str();
case CalleeType::EXTERNAL:
{
std::ostringstream typedParamsExternal;
for (auto const& i: m_externalParamsRep)
{
Delimiter del = std::get<0>(i);
bool valueType = std::get<1>(i);
std::string typeString = std::get<2>(i);
std::string varName = std::get<3>(i);
bool isCalldata = randomBool(/*probability=*/0.5);
std::string location = (isCalldata ? "calldata" : "memory");
std::string qualifiedTypeString = (valueType ? typeString : typeString + " " + location);
typedParamsExternal << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(del))
("type", qualifiedTypeString)
("varName", varName)
.render();
}
return typedParamsExternal.str();
}
}
}
std::string ProtoConverter::visit(TestFunction const& _x, std::string const& _storageVarDefs)
{
// TODO: Support more than one but less than N local variables
auto localVarBuffers = visit(_x.local_vars());
std::string structTypeDecl = localVarBuffers.first;
std::string localVarDefs = localVarBuffers.second;
std::ostringstream testBuffer;
std::string testFunction = Whiskers(R"(
function test() public returns (uint) {
<?calldata>return test_calldata_coding();</calldata>
<?returndata>return test_returndata_coding();</returndata>
})")
("calldata", m_test == Contract_Test::Contract_Test_CALLDATA_CODER)
("returndata", m_test == Contract_Test::Contract_Test_RETURNDATA_CODER)
.render();
std::string functionDeclCalldata = "function test_calldata_coding() internal returns (uint)";
std::string functionDeclReturndata = "function test_returndata_coding() internal returns (uint)";
testBuffer << Whiskers(R"(<structTypeDecl>
<testFunction>
<?calldata>
<functionDeclCalldata> {
<storageVarDefs>
<localVarDefs>
<calldataTestCode>
}
<calldataHelperFuncs>
</calldata>
<?returndata>
<functionDeclReturndata> {
<returndataTestCode>
}
<?varsPresent>
function coder_returndata_external() external returns (<return_types>) {
<storageVarDefs>
<localVarDefs>
return (<return_values>);
}
</varsPresent>
</returndata>)")
("testFunction", testFunction)
("calldata", m_test == Contract_Test::Contract_Test_CALLDATA_CODER)
("returndata", m_test == Contract_Test::Contract_Test_RETURNDATA_CODER)
("calldataHelperFuncs", calldataHelperFunctions())
("varsPresent", !m_types.str().empty())
("structTypeDecl", structTypeDecl)
("functionDeclCalldata", functionDeclCalldata)
("functionDeclReturndata", functionDeclReturndata)
("storageVarDefs", _storageVarDefs)
("localVarDefs", localVarDefs)
("calldataTestCode", testCallDataFunction(static_cast<unsigned>(_x.invalid_encoding_length())))
("returndataTestCode", testReturnDataFunction())
("return_types", m_types.str())
("return_values", m_argsCoder.str())
.render();
return testBuffer.str();
}
std::string ProtoConverter::testCallDataFunction(unsigned _invalidLength)
{
return Whiskers(R"(
uint returnVal = this.coder_calldata_public(<argumentNames>);
if (returnVal != 0)
return returnVal;
returnVal = this.coder_calldata_external(<argumentNames>);
if (returnVal != 0)
return uint(200000) + returnVal;
<?atLeastOneVar>
bytes memory argumentEncoding = abi.encode(<argumentNames>);
returnVal = checkEncodedCall(
this.coder_calldata_public.selector,
argumentEncoding,
<invalidLengthFuzz>,
<isRightPadded>
);
if (returnVal != 0)
return returnVal;
returnVal = checkEncodedCall(
this.coder_calldata_external.selector,
argumentEncoding,
<invalidLengthFuzz>,
<isRightPadded>
);
if (returnVal != 0)
return uint(200000) + returnVal;
</atLeastOneVar>
return 0;
)")
("argumentNames", m_argsCoder.str())
("invalidLengthFuzz", std::to_string(_invalidLength))
("isRightPadded", isLastDynParamRightPadded() ? "true" : "false")
("atLeastOneVar", m_varCounter > 0)
.render();
}
std::string ProtoConverter::testReturnDataFunction()
{
return Whiskers(R"(
<?varsPresent>
(<varDecl>) = this.coder_returndata_external();
<equality_checks>
</varsPresent>
return 0;
)")
("varsPresent", !m_typedReturn.str().empty())
("varDecl", m_typedReturn.str())
("equality_checks", m_checks.str())
.render();
}
std::string ProtoConverter::calldataHelperFunctions()
{
std::stringstream calldataHelperFuncs;
calldataHelperFuncs << R"(
/// Accepts function selector, correct argument encoding, and length of
/// invalid encoding and returns the correct and incorrect abi encoding
/// for calling the function specified by the function selector.
function createEncoding(
bytes4 funcSelector,
bytes memory argumentEncoding,
uint invalidLengthFuzz,
bool isRightPadded
) internal pure returns (bytes memory, bytes memory)
{
bytes memory validEncoding = new bytes(4 + argumentEncoding.length);
// Ensure that invalidEncoding crops at least 32 bytes (padding length
// is at most 31 bytes) if `isRightPadded` is true.
// This is because shorter bytes/string values (whose encoding is right
// padded) can lead to successful decoding when fewer than 32 bytes have
// been cropped in the worst case. In other words, if `isRightPadded` is
// true, then
// 0 <= invalidLength <= argumentEncoding.length - 32
// otherwise
// 0 <= invalidLength <= argumentEncoding.length - 1
uint invalidLength;
if (isRightPadded)
invalidLength = invalidLengthFuzz % (argumentEncoding.length - 31);
else
invalidLength = invalidLengthFuzz % argumentEncoding.length;
bytes memory invalidEncoding = new bytes(4 + invalidLength);
for (uint i = 0; i < 4; i++)
validEncoding[i] = invalidEncoding[i] = funcSelector[i];
for (uint i = 0; i < argumentEncoding.length; i++)
validEncoding[i+4] = argumentEncoding[i];
for (uint i = 0; i < invalidLength; i++)
invalidEncoding[i+4] = argumentEncoding[i];
return (validEncoding, invalidEncoding);
}
/// Accepts function selector, correct argument encoding, and an invalid
/// encoding length as input. Returns a non-zero value if either call with
/// correct encoding fails or call with incorrect encoding succeeds.
/// Returns zero if both calls meet expectation.
function checkEncodedCall(
bytes4 funcSelector,
bytes memory argumentEncoding,
uint invalidLengthFuzz,
bool isRightPadded
) public returns (uint)
{
(bytes memory validEncoding, bytes memory invalidEncoding) = createEncoding(
funcSelector,
argumentEncoding,
invalidLengthFuzz,
isRightPadded
);
(bool success, bytes memory returnVal) = address(this).call(validEncoding);
uint returnCode = abi.decode(returnVal, (uint));
// Return non-zero value if call fails for correct encoding
if (success == false || returnCode != 0)
return 400000;
(success, ) = address(this).call(invalidEncoding);
// Return non-zero value if call succeeds for incorrect encoding
if (success == true)
return 400001;
return 0;
})";
/// These are indirections to test memory-calldata codings more robustly.
std::stringstream indirections;
unsigned numIndirections = randomNumberOneToN(s_maxIndirections);
for (unsigned i = 1; i <= numIndirections; i++)
{
bool finalIndirection = i == numIndirections;
std::string mutability = (finalIndirection ? "pure" : "view");
indirections << Whiskers(R"(
function coder_calldata_external_i<N>(<parameters>) external <mutability> returns (uint) {
<?finalIndirection>
<equality_checks>
return 0;
<!finalIndirection>
return this.coder_calldata_external_i<NPlusOne>(<untyped_parameters>);
</finalIndirection>
}
)")
("N", std::to_string(i))
("parameters", typedParametersAsString(CalleeType::EXTERNAL))
("mutability", mutability)
("finalIndirection", finalIndirection)
("equality_checks", equalityChecksAsString())
("NPlusOne", std::to_string(i + 1))
("untyped_parameters", m_untypedParamsExternal.str())
.render();
}
// These are callee functions that encode from storage, decode to
// memory/calldata and check if decoded value matches storage value
// return true on successful match, false otherwise
calldataHelperFuncs << Whiskers(R"(
function coder_calldata_public(<parameters_memory>) public pure returns (uint) {
<equality_checks>
return 0;
}
function coder_calldata_external(<parameters_calldata>) external view returns (uint) {
return this.coder_calldata_external_i1(<untyped_parameters>);
}
<indirections>
)")
("parameters_memory", typedParametersAsString(CalleeType::PUBLIC))
("equality_checks", equalityChecksAsString())
("parameters_calldata", typedParametersAsString(CalleeType::EXTERNAL))
("untyped_parameters", m_untypedParamsExternal.str())
("indirections", indirections.str())
.render();
return calldataHelperFuncs.str();
}
std::string ProtoConverter::commonHelperFunctions()
{
std::stringstream helperFuncs;
helperFuncs << R"(
/// Compares bytes, returning true if they are equal and false otherwise.
function bytesCompare(bytes memory a, bytes memory b) internal pure returns (bool) {
if(a.length != b.length)
return false;
for (uint i = 0; i < a.length; i++)
if (a[i] != b[i])
return false;
return true;
}
)";
return helperFuncs.str();
}
void ProtoConverter::visit(Contract const& _x)
{
std::string pragmas = R"(pragma solidity >=0.0;
pragma experimental ABIEncoderV2;)";
// Record test spec
m_test = _x.test();
// TODO: Support more than one but less than N state variables
auto storageBuffers = visit(_x.state_vars());
std::string storageVarDecls = storageBuffers.first;
std::string storageVarDefs = storageBuffers.second;
m_isStateVar = false;
std::string testFunction = visit(_x.testfunction(), storageVarDefs);
/* Structure of contract body
* - Storage variable declarations
* - Struct definitions
* - Test function
* - Storage variable assignments
* - Local variable definitions and assignments
* - Test code proper (calls public and external functions)
* - Helper functions
*/
std::ostringstream contractBody;
contractBody << storageVarDecls
<< testFunction
<< commonHelperFunctions();
m_output << Whiskers(R"(<pragmas>
<contractStart>
<contractBody>
<contractEnd>)")
("pragmas", pragmas)
("contractStart", "contract C {")
("contractBody", contractBody.str())
("contractEnd", "}")
.render();
}
std::string ProtoConverter::isabelleTypeString() const
{
std::string typeString = m_isabelleTypeString.str();
if (!typeString.empty())
return "(" + typeString + ")";
else
return typeString;
}
std::string ProtoConverter::isabelleValueString() const
{
std::string valueString = m_isabelleValueString.str();
if (!valueString.empty())
return "(" + valueString + ")";
else
return valueString;
}
std::string ProtoConverter::contractToString(Contract const& _input)
{
visit(_input);
return m_output.str();
}
/// Type visitor
void TypeVisitor::StructTupleString::addTypeStringToTuple(std::string& _typeString)
{
index++;
if (index > 1)
stream << ",";
stream << _typeString;
}
void TypeVisitor::StructTupleString::addArrayBracketToType(std::string& _arrayBracket)
{
stream << _arrayBracket;
}
std::string TypeVisitor::visit(BoolType const&)
{
m_baseType = "bool";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(IntegerType const& _type)
{
m_baseType = getIntTypeAsString(_type);
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(FixedByteType const& _type)
{
m_baseType = getFixedByteTypeAsString(_type);
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(AddressType const&)
{
m_baseType = "address";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(ArrayType const& _type)
{
if (!ValidityVisitor().visit(_type))
return "";
std::string baseType = visit(_type.t());
solAssert(!baseType.empty(), "");
std::string arrayBracket = _type.is_static() ?
std::string("[") +
std::to_string(getStaticArrayLengthFromFuzz(_type.length())) +
std::string("]") :
std::string("[]");
m_baseType += arrayBracket;
m_structTupleString.addArrayBracketToType(arrayBracket);
// If we don't know yet if the array will be dynamically encoded,
// check again. If we already know that it will be, there's no
// need to do anything.
if (!m_isLastDynParamRightPadded)
m_isLastDynParamRightPadded = DynParamVisitor().visit(_type);
return baseType + arrayBracket;
}
std::string TypeVisitor::visit(DynamicByteArrayType const&)
{
m_isLastDynParamRightPadded = true;
m_baseType = "bytes";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
void TypeVisitor::structDefinition(StructType const& _type)
{
// Return an empty string if struct is empty
solAssert(ValidityVisitor().visit(_type), "");
// Reset field counter and indentation
unsigned wasFieldCounter = m_structFieldCounter;
unsigned wasIndentation = m_indentation;
m_indentation = 1;
m_structFieldCounter = 0;
// Commence struct declaration
std::string structDef = lineString(
"struct " +
std::string(s_structNamePrefix) +
std::to_string(m_structCounter) +
" {"
);
// Start tuple of types with parenthesis
m_structTupleString.start();
// Increase indentation for struct fields
m_indentation++;
for (auto const& t: _type.t())
{
std::string type{};
if (!ValidityVisitor().visit(t))
continue;
TypeVisitor tVisitor(m_structCounter + 1);
type = tVisitor.visit(t);
m_structCounter += tVisitor.numStructs();
m_structDef << tVisitor.structDef();
solAssert(!type.empty(), "");
structDef += lineString(
Whiskers(R"(<type> <member>;)")
("type", type)
("member", "m" + std::to_string(m_structFieldCounter++))
.render()
);
std::string isabelleTypeStr = tVisitor.isabelleTypeString();
m_structTupleString.addTypeStringToTuple(isabelleTypeStr);
}
m_indentation--;
structDef += lineString("}");
// End tuple of types with parenthesis
m_structTupleString.end();
m_structCounter++;
m_structDef << structDef;
m_indentation = wasIndentation;
m_structFieldCounter = wasFieldCounter;
}
std::string TypeVisitor::visit(StructType const& _type)
{
if (ValidityVisitor().visit(_type))
{
// Add struct definition
structDefinition(_type);
// Set last dyn param if struct contains a dyn param e.g., bytes, array etc.
m_isLastDynParamRightPadded = DynParamVisitor().visit(_type);
// If top-level struct is a non-empty struct, assign the name S<suffix>
m_baseType = s_structTypeName + std::to_string(m_structStartCounter);
}
else
m_baseType = {};
return m_baseType;
}
/// AssignCheckVisitor implementation
void AssignCheckVisitor::ValueStream::appendValue(std::string& _value)
{
solAssert(!_value.empty(), "Abiv2 fuzzer: Empty value");
index++;
if (index > 1)
stream << ",";
stream << _value;
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(BoolType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
m_valueStream.appendValue(value);
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(IntegerType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
m_valueStream.appendValue(value);
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(FixedByteType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
{
std::string isabelleValue = ValueGetterVisitor{}.isabelleBytesValueAsString(value);
m_valueStream.appendValue(isabelleValue);
}
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(AddressType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
{
std::string isabelleValue = ValueGetterVisitor{}.isabelleAddressValueAsString(value);
m_valueStream.appendValue(isabelleValue);
}
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);