forked from bcosorg/bcos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Executive.cpp
461 lines (393 loc) · 14 KB
/
Executive.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
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file Executive.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include "Executive.h"
#include <boost/timer.hpp>
#include <json/json.h>
#include <libdevcore/CommonIO.h>
#include <libdevcore/easylog.h>
#include <libevm/VMFactory.h>
#include <libevm/VM.h>
#include <libethcore/CommonJS.h>
#include "Interface.h"
#include "State.h"
#include "ExtVM.h"
#include "BlockChain.h"
#include "Block.h"
using namespace std;
using namespace dev;
using namespace dev::eth;
StandardTrace::StandardTrace():
m_trace(Json::arrayValue)
{}
bool changesMemory(Instruction _inst)
{
return
_inst == Instruction::MSTORE ||
_inst == Instruction::MSTORE8 ||
_inst == Instruction::MLOAD ||
_inst == Instruction::CREATE ||
_inst == Instruction::CALL ||
_inst == Instruction::CALLCODE ||
_inst == Instruction::SHA3 ||
_inst == Instruction::CALLDATACOPY ||
_inst == Instruction::CODECOPY ||
_inst == Instruction::EXTCODECOPY ||
_inst == Instruction::DELEGATECALL;
}
bool changesStorage(Instruction _inst)
{
return _inst == Instruction::SSTORE;
}
void StandardTrace::operator()(uint64_t _steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, VM* voidVM, ExtVMFace const* voidExt)
{
(void)_steps;
ExtVM const& ext = dynamic_cast<ExtVM const&>(*voidExt);
VM& vm = *voidVM;
Json::Value r(Json::objectValue);
Json::Value stack(Json::arrayValue);
if (!m_options.disableStack)
{
for (auto const& i: vm.stack())
stack.append("0x" + toHex(toCompactBigEndian(i, 1)));
r["stack"] = stack;
}
bool newContext = false;
Instruction lastInst = Instruction::STOP;
if (m_lastInst.size() == ext.depth)
{
// starting a new context
assert(m_lastInst.size() == ext.depth);
m_lastInst.push_back(inst);
newContext = true;
}
else if (m_lastInst.size() == ext.depth + 2)
{
m_lastInst.pop_back();
lastInst = m_lastInst.back();
}
else if (m_lastInst.size() == ext.depth + 1)
{
// continuing in previous context
lastInst = m_lastInst.back();
m_lastInst.back() = inst;
}
else
{
LOG(WARNING) << "GAA!!! Tracing VM and more than one new/deleted stack frame between steps!";
LOG(WARNING) << "Attmepting naive recovery...";
m_lastInst.resize(ext.depth + 1);
}
Json::Value memJson(Json::arrayValue);
if (!m_options.disableMemory && (changesMemory(lastInst) || newContext))
{
for (unsigned i = 0; i < vm.memory().size(); i += 32)
{
bytesConstRef memRef(vm.memory().data() + i, 32);
memJson.append(toHex(memRef, 2, HexPrefix::DontAdd));
}
r["memory"] = memJson;
}
if (!m_options.disableStorage && (m_options.fullStorage || changesStorage(lastInst) || newContext))
{
Json::Value storage(Json::objectValue);
for (auto const& i: ext.state().storage(ext.myAddress))
storage["0x" + toHex(toCompactBigEndian(i.second.first, 1))] = "0x" + toHex(toCompactBigEndian(i.second.second, 1));
r["storage"] = storage;
}
if (m_showMnemonics)
r["op"] = instructionInfo(inst).name;
r["pc"] = toString(PC);
r["gas"] = toString(gas);
r["gasCost"] = toString(gasCost);
if (!!newMemSize)
r["memexpand"] = toString(newMemSize);
m_trace.append(r);
}
string StandardTrace::json(bool _styled) const
{
return _styled ? Json::StyledWriter().write(m_trace) : Json::FastWriter().write(m_trace);
}
Executive::Executive(Block& _s, BlockChain const& _bc, unsigned _level):
m_s(_s.mutableState()),
m_envInfo(_s.info(), _bc.lastHashes(_s.info().parentHash())),
m_depth(_level),
m_sealEngine(*_bc.sealEngine())
{
}
Executive::Executive(Block& _s, LastHashes const& _lh, unsigned _level):
m_s(_s.mutableState()),
m_envInfo(_s.info(), _lh),
m_depth(_level),
m_sealEngine(*_s.sealEngine())
{
}
Executive::Executive(State& _s, Block const& _block, unsigned _txIndex, BlockChain const& _bc, unsigned _level):
m_s(_s = _block.fromPending(_txIndex)),
m_envInfo(_block.info(), _bc.lastHashes(_block.info().parentHash()), _txIndex ? _block.receipt(_txIndex - 1).gasUsed() : 0),
m_depth(_level),
m_sealEngine(*_bc.sealEngine())
{
}
u256 Executive::gasUsed() const
{
return m_t.gas() - m_gas;
}
u256 Executive::gasUsedNoRefunds() const
{
return m_t.gas() - m_gas + m_refunded;
}
void Executive::accrueSubState(SubState& _parentContext)
{
if (m_ext)
_parentContext += m_ext->sub;
}
void Executive::initialize(Transaction const& _transaction)
{
m_t = _transaction;
// Avoid transactions that would take us beyond the block gas limit.
u256 startGasUsed = m_envInfo.gasUsed();
//判断交易使用的gas和初始gas是否大于环境设置的gaslimit
if (startGasUsed + (bigint)m_t.gas() > m_envInfo.gasLimit())
{
LOG(TRACE) << "Cannot fit tx in block" << m_envInfo.number() << ": Require <" << (m_envInfo.gasLimit() - startGasUsed) << " Got" << m_t.gas();
m_excepted = TransactionException::BlockGasLimitReached;
BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(m_envInfo.gasLimit() - startGasUsed), (bigint)m_t.gas()));
}
m_baseGasRequired = m_t.gasRequired(m_sealEngine.evmSchedule(m_envInfo));
// Avoid unaffordable transactions.
bigint gasCost = (bigint)m_t.gas() * m_t.gasPrice();
bigint totalCost = m_t.value() + gasCost;
m_gasCost = (u256)gasCost; // Convert back to 256-bit, safe now.
}
bool Executive::execute()
{
LOG(TRACE)<<"Executive::execute";
m_s.subBalance(m_t.safeSender(), m_gasCost);
if (m_t.isCreation())
return create(m_t.sender(), m_t.value(), m_t.gasPrice(), m_t.gas() - (u256)m_baseGasRequired, &m_t.data(), m_t.sender());
else
return call(m_t.receiveAddress(), m_t.safeSender(), m_t.value(), m_t.gasPrice(), bytesConstRef(&m_t.data()), m_t.gas() - (u256)m_baseGasRequired);
}
bool Executive::call(Address _receiveAddress, Address _senderAddress, u256 _value, u256 _gasPrice, bytesConstRef _data, u256 _gas)
{
CallParameters params{_senderAddress, _receiveAddress, _receiveAddress, _value, _value, _gas, _data, {}, {}};
return call(params, _gasPrice, _senderAddress);
}
bool Executive::call(CallParameters const& _p, u256 const& _gasPrice, Address const& _origin)
{
LOG(TRACE)<<"Executive::call"<<toString(_p.senderAddress);
// If external transaction.
if (m_t)
{
// FIXME: changelog contains unrevertable balance change that paid
// for the transaction.
// Increment associated nonce for sender.
m_s.incNonce(_p.senderAddress);
}
m_savepoint = m_s.savepoint();
if (m_sealEngine.isPrecompiled(_p.codeAddress))
{
bigint g = m_sealEngine.costOfPrecompiled(_p.codeAddress, _p.data);
if (_p.gas < g)
{
m_excepted = TransactionException::OutOfGasBase;
// Bail from exception.
return true; // true actually means "all finished - nothing more to be done regarding go().
}
else
{
m_gas = (u256)(_p.gas - g);
m_sealEngine.executePrecompiled(_p.codeAddress, _p.data, _p.out);
}
}
else
{
m_gas = _p.gas;
if (m_s.addressHasCode(_p.codeAddress))
{
m_outRef = _p.out; // Save ref to expected output buffer to be used in go()
bytes const& c = m_s.code(_p.codeAddress);
h256 codeHash = m_s.codeHash(_p.codeAddress);
m_ext = make_shared<ExtVM>(m_s, m_envInfo, m_sealEngine, _p.receiveAddress, _p.senderAddress, _origin, _p.apparentValue, _gasPrice, _p.data, &c, codeHash, m_depth);
}
}
// Transfer ether.
m_s.transferBalance(_p.senderAddress, _p.receiveAddress, _p.valueTransfer);
return !m_ext;
}
bool Executive::create(Address _sender, u256 _endowment, u256 _gasPrice, u256 _gas, bytesConstRef _init, Address _origin)
{
LOG(TRACE)<<"Executive::create"<<_sender;
u256 nonce = m_s.getNonce(_sender);
m_s.incNonce(_sender);
m_savepoint = m_s.savepoint();
m_isCreation = true;
// We can allow for the reverted state (i.e. that with which m_ext is constructed) to contain the m_orig.address, since
// we delete it explicitly if we decide we need to revert.
m_newAddress = right160(sha3(rlpList(_sender, nonce)));
LOG(TRACE)<<"Executive::create "<<m_newAddress<<","<<_sender<<","<<nonce;
m_gas = _gas;
m_s.transferBalance(_sender, m_newAddress, _endowment);
if (m_envInfo.number() >= m_sealEngine.chainParams().u256Param("EIP158ForkBlock"))
m_s.incNonce(m_newAddress);
// Schedule _init execution if not empty.
if (!_init.empty())
m_ext = make_shared<ExtVM>(m_s, m_envInfo, m_sealEngine, m_newAddress, _sender, _origin, _endowment, _gasPrice, bytesConstRef(), _init, sha3(_init), m_depth);
else if (m_s.addressHasCode(m_newAddress))
// Overwrite with empty code in case the account already has a code
// (address collision -- not real life case but we can check it with
// synthetic tests).
m_s.setNewCode(m_newAddress, {});
return !m_ext;
}
OnOpFunc Executive::simpleTrace()
{
return [](uint64_t steps, uint64_t PC, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, VM* voidVM, ExtVMFace const* voidExt)
{
ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
VM& vm = *voidVM;
ostringstream o;
o << endl << " STACK" << endl;
for (auto i: vm.stack())
o << (h256)i << endl;
o << " MEMORY" << endl << ((vm.memory().size() > 1000) ? " mem size greater than 1000 bytes " : memDump(vm.memory()));
o << " STORAGE" << endl;
for (auto const& i: ext.state().storage(ext.myAddress))
o << showbase << hex << i.second.first << ": " << i.second.second << endl;
LOG(TRACE) << o.str();
LOG(TRACE) << " < " << dec << ext.depth << " : " << ext.myAddress << " : #" << steps << " : " << hex << setw(4) << setfill('0') << PC << " : " << instructionInfo(inst).name << " : " << dec << gas << " : -" << dec << gasCost << " : " << newMemSize << "x32" << " >";
};
}
bool Executive::go(OnOpFunc const& _onOp)
{
LOG(TRACE)<<"Executive::go";
if (m_ext)
{
Timer t;
try
{
// Create VM instance. Force Interpreter if tracing requested.
auto vm = _onOp ? VMFactory::create(VMKind::Interpreter) : VMFactory::create();
if (m_isCreation)
{
auto out = vm->exec(m_gas, *m_ext, _onOp);
if (m_res)
{
m_res->gasForDeposit = m_gas;
m_res->depositSize = out.size();
}
if (out.size() > m_ext->evmSchedule().maxCodeSize)
BOOST_THROW_EXCEPTION(OutOfGas());
else if (out.size() * m_ext->evmSchedule().createDataGas <= m_gas)
{
if (m_res)
m_res->codeDeposit = CodeDeposit::Success;
m_gas -= out.size() * m_ext->evmSchedule().createDataGas;
}
else
{
if (m_ext->evmSchedule().exceptionalFailedCodeDeposit)
BOOST_THROW_EXCEPTION(OutOfGas());
else
{
if (m_res)
m_res->codeDeposit = CodeDeposit::Failed;
out.clear();
}
}
if (m_res)
m_res->output = out; // copy output to execution result
LOG(TRACE)<<"Executive::go setCode "<<m_newAddress<<","<<toHex(out);
m_s.setNewCode(m_ext->myAddress, std::move(out));
}
else
{
if (m_res)
{
m_res->output = vm->exec(m_gas, *m_ext, _onOp); // take full output
bytesConstRef{&m_res->output}.copyTo(m_outRef);
}
else
vm->exec(m_gas, *m_ext, m_outRef, _onOp); // take only expected output
}
}
catch (VMException const& _e)
{
clog(StateSafeExceptions) << "Safe VM Exception. " << diagnostic_information(_e);
m_gas = 0;
m_excepted = toTransactionException(_e);
revert();
}
catch (Exception const& _e)
{
// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
LOG(WARNING) << "Unexpected exception in VM. There may be a bug in this implementation. " << diagnostic_information(_e);
exit(1);
// Another solution would be to reject this transaction, but that also
// has drawbacks. Essentially, the amount of ram has to be increased here.
}
catch (std::exception const& _e)
{
// TODO: AUDIT: check that this can never reasonably happen. Consider what to do if it does.
LOG(WARNING) << "Unexpected std::exception in VM. Not enough RAM? " << _e.what();
exit(1);
// Another solution would be to reject this transaction, but that also
// has drawbacks. Essentially, the amount of ram has to be increased here.
}
ctxstat<<"VM took:"<<(t.elapsed()*1000000)<<" Hash="<<(m_t.sha3())<<",Randid="<<m_t.randomid();
}
return true;
}
void Executive::finalize()
{
// Accumulate refunds for suicides.
if (m_ext)
m_ext->sub.refunds += m_ext->evmSchedule().suicideRefundGas * m_ext->sub.suicides.size();
// SSTORE refunds...
// must be done before the miner gets the fees.
m_refunded = m_ext ? min((m_t.gas() - m_gas) / 2, m_ext->sub.refunds) : 0;
m_gas += m_refunded;
if (m_t)
{
//m_s.addBalance(m_t.sender(), m_gas * m_t.gasPrice());
//u256 feesEarned = (m_t.gas() - m_gas) * m_t.gasPrice();
//m_s.addBalance(m_envInfo.author(), feesEarned);
}
// Suicides...
if (m_ext)
for (auto a: m_ext->sub.suicides)
m_s.kill(a);
// Logs..
if (m_ext)
m_logs = m_ext->sub.logs;
if (m_res) // Collect results
{
m_res->gasUsed = gasUsed();
m_res->excepted = m_excepted; // TODO: m_except is used only in ExtVM::call
m_res->newAddress = m_newAddress;
m_res->gasRefunded = m_ext ? m_ext->sub.refunds : 0;
}
}
void Executive::revert()
{
if (m_ext)
m_ext->sub.clear();
// Set result address to the null one.
m_newAddress = {};
m_s.rollback(m_savepoint);
}