-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
Copy pathGasMeter.cpp
477 lines (426 loc) · 13.1 KB
/
GasMeter.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
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/**
* @author Christian <[email protected]>
* @date 2015
* Unit tests for the gas estimator.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/GasEstimator.h>
using namespace solidity::langutil;
using namespace solidity::evmasm;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::test;
namespace solidity::frontend::test
{
class GasMeterTestFramework: public SolidityExecutionFramework
{
public:
void compile(std::string const& _sourceCode)
{
m_compiler.reset();
m_compilerInput = CompilerInput{};
m_compilerInput.sourceCode = {{"", "pragma solidity >=0.0;\n"
"// SPDX-License-Identifier: GPL-3.0\n" + _sourceCode}};
m_compilerInput.optimise = solidity::test::CommonOptions::get().optimize;
m_compilerInput.evmVersion = std::make_optional(m_evmVersion);
m_compiler.compile(m_compilerInput);
BOOST_REQUIRE_MESSAGE(m_compiler.output().success(), "Compiling contract failed");
}
void testCreationTimeGas(std::string const& _sourceCode, u256 const& _tolerance = u256(0))
{
compileAndRun(_sourceCode);
auto state = std::make_shared<KnownState>();
auto output = m_compiler.output();
auto contract = output.contract();
soltestAssert(contract.has_value());
soltestAssert(contract.value().assemblyItems.has_value());
auto object = contract.value().object;
auto runtimeObject = contract.value().runtimeObject;
auto assemblyItems = contract.value().assemblyItems.value();
PathGasMeter meter(assemblyItems, solidity::test::CommonOptions::get().evmVersion());
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(runtimeObject.size());
// costs for deployment
gas += bytecodeSize * GasCosts::createDataGas;
// costs for transaction
gas += gasForTransaction(object, true);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK_LE(m_gasUsed, gas.value);
BOOST_CHECK_LE(gas.value - _tolerance, m_gasUsed);
}
/// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments)
/// against the actual gas usage computed by the VM on the given set of argument variants.
void testRunTimeGas(std::string const& _sig, std::vector<bytes> _argumentVariants, u256 const& _tolerance = u256(0))
{
auto output = m_compiler.output();
auto contract = output.contract();
soltestAssert(contract.has_value());
soltestAssert(contract.value().runtimeAssemblyItems.has_value());
auto runtimeAssemblyItems = contract.value().runtimeAssemblyItems.value();
u256 gasUsed = 0;
GasMeter::GasConsumption gas;
util::FixedHash<4> hash = util::selectorFromSignatureH32(_sig);
for (bytes const& arguments: _argumentVariants)
{
sendMessage(hash.asBytes(), arguments, false, 0);
BOOST_CHECK(m_transactionSuccessful);
gasUsed = std::max(gasUsed, m_gasUsed);
gas = std::max(gas, gasForTransaction(hash.asBytes() + arguments, false));
}
gas += GasEstimator(solidity::test::CommonOptions::get().evmVersion()).functionalEstimation(
runtimeAssemblyItems,
_sig
);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK_LE(m_gasUsed, gas.value);
BOOST_CHECK_LE(gas.value - _tolerance, m_gasUsed);
}
static GasMeter::GasConsumption gasForTransaction(bytes const& _data, bool _isCreation)
{
auto evmVersion = solidity::test::CommonOptions::get().evmVersion();
GasMeter::GasConsumption gas = _isCreation ? GasCosts::txCreateGas : GasCosts::txGas;
for (auto i: _data)
gas += i != 0 ? GasCosts::txDataNonZeroGas(evmVersion) : GasCosts::txDataZeroGas;
return gas;
}
};
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
BOOST_AUTO_TEST_CASE(simple_contract)
{
// Tests a simple "deploy contract" code without constructor. The actual contract is not relevant.
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function f(uint a) public {
shaValue = keccak256(abi.encodePacked(a));
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(store_keccak256)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract test {
bytes32 public shaValue;
constructor() {
shaValue = keccak256(abi.encodePacked(this));
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(updating_store)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
constructor() {
data = 1;
data = 2;
data2 = 0;
}
}
)";
testCreationTimeGas(sourceCode, m_evmVersion < langutil::EVMVersion::constantinople() ? u256(0) : u256(9600));
}
BOOST_AUTO_TEST_CASE(branches)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
data2 = 1;
else
data = 1;
}
}
)";
testCreationTimeGas(sourceCode, 1);
testRunTimeGas("f(uint256)", std::vector<bytes>{encodeArgs(2), encodeArgs(8)}, 1);
}
BOOST_AUTO_TEST_CASE(function_calls)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
{ unchecked { data2 = g(x**8) + 1; } }
else
data = 1;
}
function g(uint x) internal returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
// In f, data2 is accessed twice, so there is a reduction of 2200 to 100 in actual costs.
// However, GasMeter always assumes cold costs.
testRunTimeGas(
"f(uint256)",
std::vector<bytes>{encodeArgs(2), encodeArgs(8)},
m_evmVersion < EVMVersion::berlin() ?
u256(0) :
u256(2100)
);
}
BOOST_AUTO_TEST_CASE(multiple_external_functions)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
{ unchecked { data2 = g(x**8) + 1; } }
else
data = 1;
}
function g(uint x) public returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
// In f, data2 is accessed twice, so there is a reduction of 2200 to 100 in actual costs.
// However, GasMeter always assumes cold costs.
testRunTimeGas(
"f(uint256)",
std::vector<bytes>{encodeArgs(2), encodeArgs(8)},
m_evmVersion < EVMVersion::berlin() ?
u256(0) :
u256(2100)
);
testRunTimeGas("g(uint256)", std::vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_CASE(exponent_size)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract A {
function f(uint x) public returns (uint) {
unchecked { return x ** 0; }
}
function g(uint x) public returns (uint) {
unchecked { return x ** 0x100; }
}
function h(uint x) public returns (uint) {
unchecked { return x ** 0x10000; }
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", std::vector<bytes>{encodeArgs(2)});
testRunTimeGas("g(uint256)", std::vector<bytes>{encodeArgs(2)});
testRunTimeGas("h(uint256)", std::vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_CASE(balance_gas)
{
char const* sourceCode = R"(
contract A {
function lookup_balance(address a) public returns (uint) {
return a.balance;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("lookup_balance(address)", std::vector<bytes>{encodeArgs(2), encodeArgs(100)});
}
BOOST_AUTO_TEST_CASE(extcodesize_gas)
{
char const* sourceCode = R"(
contract A {
function f() public returns (uint _s) {
assembly {
_s := extcodesize(0x30)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f()", std::vector<bytes>{encodeArgs()});
}
BOOST_AUTO_TEST_CASE(regular_functions_exclude_fallback)
{
// A bug in the estimator caused the costs for a specific function
// to always include the costs for the fallback.
char const* sourceCode = R"(
contract A {
uint public x;
fallback() external { x = 2; }
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("x()", std::vector<bytes>{encodeArgs()});
}
BOOST_AUTO_TEST_CASE(complex_control_flow)
{
// This crashed the gas estimator previously (or took a very long time).
// Now we do not follow branches if they start out with lower gas costs than the ones
// we previously considered. This of course reduces accuracy.
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract log {
function ln(int128 x) public pure returns (int128 result) {
unchecked {
int128 t = x / 256;
int128 y = 5545177;
x = t;
t = x * 16; if (t <= 1000000) { x = t; y = y - 2772588; }
t = x * 4; if (t <= 1000000) { x = t; y = y - 1386294; }
t = x * 2; if (t <= 1000000) { x = t; y = y - 693147; }
t = x + x / 2; if (t <= 1000000) { x = t; y = y - 405465; }
t = x + x / 4; if (t <= 1000000) { x = t; y = y - 223144; }
t = x + x / 8; if (t <= 1000000) { x = t; y = y - 117783; }
t = x + x / 16; if (t <= 1000000) { x = t; y = y - 60624; }
t = x + x / 32; if (t <= 1000000) { x = t; y = y - 30771; }
t = x + x / 64; if (t <= 1000000) { x = t; y = y - 15504; }
t = x + x / 128; if (t <= 1000000) { x = t; y = y - 7782; }
t = x + x / 256; if (t <= 1000000) { x = t; y = y - 3898; }
t = x + x / 512; if (t <= 1000000) { x = t; y = y - 1951; }
t = x + x / 1024; if (t <= 1000000) { x = t; y = y - 976; }
t = x + x / 2048; if (t <= 1000000) { x = t; y = y - 488; }
t = x + x / 4096; if (t <= 1000000) { x = t; y = y - 244; }
t = x + x / 8192; if (t <= 1000000) { x = t; y = y - 122; }
t = x + x / 16384; if (t <= 1000000) { x = t; y = y - 61; }
t = x + x / 32768; if (t <= 1000000) { x = t; y = y - 31; }
t = x + x / 65536; if (t <= 1000000) { y = y - 15; }
return y;
}
}
}
)";
testCreationTimeGas(sourceCode);
// max gas is used for small x
testRunTimeGas("ln(int128)", std::vector<bytes>{encodeArgs(0), encodeArgs(10), encodeArgs(105), encodeArgs(30000)});
}
BOOST_AUTO_TEST_CASE(
mcopy_memory_expansion_gas,
*boost::unit_test::precondition(minEVMVersionCheck(EVMVersion::cancun()))
)
{
char const* sourceCode = R"(
contract C {
function no_expansion() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_write() public {
assembly {
mcopy(0xffff, 0, 1)
return(0xffff, 1)
}
}
function expansion_on_read() public {
assembly {
mcopy(0, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_read_write() public {
assembly {
mcopy(0xffff, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_zero_size() public {
assembly {
mcopy(0xffff, 0xffff, 0)
return(0, 1)
}
}
function expansion_on_0_0_0() public {
assembly {
mcopy(0, 0, 0)
return(0, 1)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("no_expansion()", {encodeArgs()});
testRunTimeGas("expansion_on_write()", {encodeArgs()});
testRunTimeGas("expansion_on_read()", {encodeArgs()});
testRunTimeGas("expansion_on_read_write()", {encodeArgs()});
testRunTimeGas("expansion_on_zero_size()", {encodeArgs()});
testRunTimeGas("expansion_on_0_0_0()", {encodeArgs()});
}
BOOST_AUTO_TEST_CASE(
mcopy_word_gas,
*boost::unit_test::precondition(minEVMVersionCheck(EVMVersion::cancun()))
)
{
char const* sourceCode = R"(
contract C {
function no_overlap() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x4000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_right() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x3000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_left() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x1000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_full() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x2000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("no_overlap()", {encodeArgs()});
testRunTimeGas("overlap_right()", {encodeArgs()});
testRunTimeGas("overlap_left()", {encodeArgs()});
testRunTimeGas("overlap_full()", {encodeArgs()});
}
BOOST_AUTO_TEST_SUITE_END()
}