-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ethash.cpp
316 lines (273 loc) · 11.1 KB
/
Ethash.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
/*
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 Ethash.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include "Ethash.h"
#include <libethash/ethash.h>
#include <libethash/internal.h>
#include <libethereum/Interface.h>
#include <libethcore/ChainOperationParams.h>
#include <libethcore/CommonJS.h>
#include "EthashCPUMiner.h"
using namespace std;
using namespace dev;
using namespace eth;
void Ethash::init()
{
ETH_REGISTER_SEAL_ENGINE(Ethash);
}
Ethash::Ethash()
{
map<string, GenericFarm<EthashProofOfWork>::SealerDescriptor> sealers;
sealers["cpu"] = GenericFarm<EthashProofOfWork>::SealerDescriptor{&EthashCPUMiner::instances, [](GenericMiner<EthashProofOfWork>::ConstructionInfo ci){ return new EthashCPUMiner(ci); }};
m_farm.setSealers(sealers);
m_farm.onSolutionFound([=](EthashProofOfWork::Solution const& sol)
{
std::unique_lock<Mutex> l(m_submitLock);
// cdebug << m_farm.work().seedHash << m_farm.work().headerHash << sol.nonce << EthashAux::eval(m_farm.work().seedHash, m_farm.work().headerHash, sol.nonce).value;
setMixHash(m_sealing, sol.mixHash);
setNonce(m_sealing, sol.nonce);
if (!quickVerifySeal(m_sealing))
return false;
if (m_onSealGenerated)
{
RLPStream ret;
m_sealing.streamRLP(ret);
l.unlock();
m_onSealGenerated(ret.out());
}
return true;
});
}
Ethash::~Ethash()
{
// onSolutionFound closure sometimes has references to destroyed members.
m_farm.onSolutionFound({});
}
strings Ethash::sealers() const
{
return {"cpu"};
}
h256 Ethash::seedHash(BlockHeader const& _bi)
{
return EthashAux::seedHash((unsigned)_bi.number());
}
StringHashMap Ethash::jsInfo(BlockHeader const& _bi) const
{
return { { "nonce", toJS(nonce(_bi)) }, { "seedHash", toJS(seedHash(_bi)) }, { "mixHash", toJS(mixHash(_bi)) }, { "boundary", toJS(boundary(_bi)) }, { "difficulty", toJS(_bi.difficulty()) } };
}
void Ethash::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const
{
SealEngineFace::verify(_s, _bi, _parent, _block);
if (_s != CheckNothingNew)
{
if (_bi.difficulty() < chainParams().minimumDifficulty)
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(chainParams().minimumDifficulty), bigint(_bi.difficulty())) );
if (_bi.gasLimit() < chainParams().minGasLimit)
BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().minGasLimit), bigint(_bi.gasLimit())) );
if (_bi.gasLimit() > chainParams().maxGasLimit)
BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().maxGasLimit), bigint(_bi.gasLimit())) );
if (_bi.number() && _bi.extraData().size() > chainParams().maximumExtraDataSize)
BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(chainParams().maximumExtraDataSize), bigint(_bi.extraData().size())) << errinfo_extraData(_bi.extraData()));
u256 const& daoHardfork = chainParams().daoHardforkBlock;
if (daoHardfork != 0 && daoHardfork + 9 >= daoHardfork && _bi.number() >= daoHardfork && _bi.number() <= daoHardfork + 9)
if (_bi.extraData() != fromHex("0x64616f2d686172642d666f726b"))
BOOST_THROW_EXCEPTION(ExtraDataIncorrect() << errinfo_comment("Received block from the wrong fork (invalid extradata)."));
}
if (_parent)
{
// Check difficulty is correct given the two timestamps.
auto expected = calculateDifficulty(_bi, _parent);
auto difficulty = _bi.difficulty();
if (difficulty != expected)
BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)expected, (bigint)difficulty));
auto gasLimit = _bi.gasLimit();
auto parentGasLimit = _parent.gasLimit();
if (
gasLimit < chainParams().minGasLimit ||
gasLimit > chainParams().maxGasLimit ||
gasLimit <= parentGasLimit - parentGasLimit / chainParams().gasLimitBoundDivisor ||
gasLimit >= parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor)
BOOST_THROW_EXCEPTION(
InvalidGasLimit()
<< errinfo_min((bigint)((bigint)parentGasLimit - (bigint)(parentGasLimit / chainParams().gasLimitBoundDivisor)))
<< errinfo_got((bigint)gasLimit)
<< errinfo_max((bigint)((bigint)parentGasLimit + parentGasLimit / chainParams().gasLimitBoundDivisor))
);
}
// check it hashes according to proof of work or that it's the genesis block.
if (_s == CheckEverything && _bi.parentHash() && !verifySeal(_bi))
{
InvalidBlockNonce ex;
ex << errinfo_nonce(nonce(_bi));
ex << errinfo_mixHash(mixHash(_bi));
ex << errinfo_seedHash(seedHash(_bi));
EthashProofOfWork::Result er = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash));
ex << errinfo_hash256(_bi.hash(WithoutSeal));
ex << errinfo_difficulty(_bi.difficulty());
ex << errinfo_target(boundary(_bi));
BOOST_THROW_EXCEPTION(ex);
}
else if (_s == QuickNonce && _bi.parentHash() && !quickVerifySeal(_bi))
{
InvalidBlockNonce ex;
ex << errinfo_hash256(_bi.hash(WithoutSeal));
ex << errinfo_difficulty(_bi.difficulty());
ex << errinfo_nonce(nonce(_bi));
BOOST_THROW_EXCEPTION(ex);
}
}
void Ethash::verifyTransaction(ImportRequirements::value _ir, TransactionBase const& _t, BlockHeader const& _header, u256 const& _startGasUsed) const
{
SealEngineFace::verifyTransaction(_ir, _t, _header, _startGasUsed);
if (_ir & ImportRequirements::TransactionSignatures)
{
if (_header.number() >= chainParams().EIP158ForkBlock)
{
int chainID = chainParams().chainID;
_t.checkChainId(chainID);
}
else
_t.checkChainId(-4);
}
if (_ir & ImportRequirements::TransactionBasic && _t.baseGasRequired(evmSchedule(_header.number())) > _t.gas())
BOOST_THROW_EXCEPTION(OutOfGasIntrinsic() << RequirementError((bigint)(_t.baseGasRequired(evmSchedule(_header.number()))), (bigint)_t.gas()));
// Avoid transactions that would take us beyond the block gas limit.
if (_startGasUsed + (bigint)_t.gas() > _header.gasLimit())
BOOST_THROW_EXCEPTION(BlockGasLimitReached() << RequirementError((bigint)(_header.gasLimit() - _startGasUsed), (bigint)_t.gas()));
}
u256 Ethash::childGasLimit(BlockHeader const& _bi, u256 const& _gasFloorTarget) const
{
u256 gasFloorTarget = _gasFloorTarget == Invalid256 ? 3141562 : _gasFloorTarget;
u256 gasLimit = _bi.gasLimit();
u256 boundDivisor = chainParams().gasLimitBoundDivisor;
if (gasLimit < gasFloorTarget)
return min<u256>(gasFloorTarget, gasLimit + gasLimit / boundDivisor - 1);
else
return max<u256>(gasFloorTarget, gasLimit - gasLimit / boundDivisor + 1 + (_bi.gasUsed() * 6 / 5) / boundDivisor);
}
void Ethash::manuallySubmitWork(const h256& _mixHash, Nonce _nonce)
{
m_farm.submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr);
}
u256 Ethash::calculateDifficulty(BlockHeader const& _bi, BlockHeader const& _parent) const
{
const unsigned c_expDiffPeriod = 100000;
if (!_bi.number())
throw GenesisBlockCannotBeCalculated();
auto const& minimumDifficulty = chainParams().minimumDifficulty;
auto const& difficultyBoundDivisor = chainParams().difficultyBoundDivisor;
auto const& durationLimit = chainParams().durationLimit;
bigint target; // stick to a bigint for the target. Don't want to risk going negative.
if (_bi.number() < chainParams().homesteadForkBlock)
// Frontier-era difficulty adjustment
target = _bi.timestamp() >= _parent.timestamp() + durationLimit ? _parent.difficulty() - (_parent.difficulty() / difficultyBoundDivisor) : (_parent.difficulty() + (_parent.difficulty() / difficultyBoundDivisor));
else
{
bigint const timestampDiff = bigint(_bi.timestamp()) - _parent.timestamp();
bigint const adjFactor = _bi.number() < chainParams().byzantiumForkBlock ?
max<bigint>(1 - timestampDiff / 10, -99) : // Homestead-era difficulty adjustment
max<bigint>((_parent.hasUncles() ? 2 : 1) - timestampDiff / 9, -99); // Byzantium-era difficulty adjustment
target = _parent.difficulty() + _parent.difficulty() / 2048 * adjFactor;
}
bigint o = target;
unsigned exponentialIceAgeBlockNumber = unsigned(_parent.number() + 1);
// EIP-649 modifies exponentialIceAgeBlockNumber
if (_bi.number() >= chainParams().byzantiumForkBlock)
{
if (exponentialIceAgeBlockNumber >= 3000000)
exponentialIceAgeBlockNumber -= 3000000;
else
exponentialIceAgeBlockNumber = 0;
}
unsigned periodCount = exponentialIceAgeBlockNumber / c_expDiffPeriod;
if (periodCount > 1)
o += (bigint(1) << (periodCount - 2)); // latter will eventually become huge, so ensure it's a bigint.
o = max<bigint>(minimumDifficulty, o);
return u256(min<bigint>(o, std::numeric_limits<u256>::max()));
}
void Ethash::populateFromParent(BlockHeader& _bi, BlockHeader const& _parent) const
{
SealEngineFace::populateFromParent(_bi, _parent);
_bi.setDifficulty(calculateDifficulty(_bi, _parent));
_bi.setGasLimit(childGasLimit(_parent));
}
bool Ethash::quickVerifySeal(BlockHeader const& _bi) const
{
if (_bi.number() >= ETHASH_EPOCH_LENGTH * 2048)
return false;
auto h = _bi.hash(WithoutSeal);
auto m = mixHash(_bi);
auto n = nonce(_bi);
auto b = boundary(_bi);
bool ret = !!ethash_quick_check_difficulty(
(ethash_h256_t const*)h.data(),
(uint64_t)(u64)n,
(ethash_h256_t const*)m.data(),
(ethash_h256_t const*)b.data());
return ret;
}
bool Ethash::verifySeal(BlockHeader const& _bi) const
{
bool pre = quickVerifySeal(_bi);
#if !ETH_DEBUG
if (!pre)
{
cwarn << "Fail on preVerify";
return false;
}
#endif
auto result = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
bool slow = result.value <= boundary(_bi) && result.mixHash == mixHash(_bi);
#if ETH_DEBUG
if (!pre && slow)
{
cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false.";
cwarn << "headerHash:" << _bi.hash(WithoutSeal);
cwarn << "nonce:" << nonce(_bi);
cwarn << "mixHash:" << mixHash(_bi);
cwarn << "difficulty:" << _bi.difficulty();
cwarn << "boundary:" << boundary(_bi);
cwarn << "result.value:" << result.value;
cwarn << "result.mixHash:" << result.mixHash;
}
#endif // ETH_DEBUG
return slow;
}
void Ethash::generateSeal(BlockHeader const& _bi)
{
{
Guard l(m_submitLock);
m_sealing = _bi;
m_farm.setWork(m_sealing);
m_farm.start(m_sealer);
m_farm.setWork(m_sealing); // TODO: take out one before or one after...
}
bytes shouldPrecompute = option("precomputeDAG");
if (!shouldPrecompute.empty() && shouldPrecompute[0] == 1)
ensurePrecomputed((unsigned)_bi.number());
}
bool Ethash::shouldSeal(Interface*)
{
return true;
}
void Ethash::ensurePrecomputed(unsigned _number)
{
if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10)
// 90% of the way to the new epoch
EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true);
}