Fabcoin Core  0.16.2
P2P Digital Currency
Ethash.cpp
Go to the documentation of this file.
1 /*
2  This file is part of cpp-ethereum.
3 
4  cpp-ethereum is free software: you can redistribute it and/or modify
5  it under the terms of the GNU General Public License as published by
6  the Free Software Foundation, either version 3 of the License, or
7  (at your option) any later version.
8 
9  cpp-ethereum is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY; without even the implied warranty of
11  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  GNU General Public License for more details.
13 
14  You should have received a copy of the GNU General Public License
15  along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16 */
22 #include "Ethash.h"
23 #include <libethash/ethash.h>
24 #include <libethash/internal.h>
25 #include <libethereum/Interface.h>
27 #include <libethcore/CommonJS.h>
28 #include "EthashCPUMiner.h"
29 using namespace std;
30 using namespace dev;
31 using namespace eth;
32 
33 void Ethash::init()
34 {
36 }
37 
38 Ethash::Ethash()
39 {
40  map<string, GenericFarm<EthashProofOfWork>::SealerDescriptor> sealers;
41  sealers["cpu"] = GenericFarm<EthashProofOfWork>::SealerDescriptor{&EthashCPUMiner::instances, [](GenericMiner<EthashProofOfWork>::ConstructionInfo ci){ return new EthashCPUMiner(ci); }};
42  m_farm.setSealers(sealers);
43  m_farm.onSolutionFound([=](EthashProofOfWork::Solution const& sol)
44  {
45 // cdebug << m_farm.work().seedHash << m_farm.work().headerHash << sol.nonce << EthashAux::eval(m_farm.work().seedHash, m_farm.work().headerHash, sol.nonce).value;
46  setMixHash(m_sealing, sol.mixHash);
47  setNonce(m_sealing, sol.nonce);
48  if (!quickVerifySeal(m_sealing))
49  return false;
50 
51  if (m_onSealGenerated)
52  {
53  RLPStream ret;
54  m_sealing.streamRLP(ret);
55  m_onSealGenerated(ret.out());
56  }
57  return true;
58  });
59 }
60 
61 strings Ethash::sealers() const
62 {
63  return {"cpu"};
64 }
65 
66 h256 Ethash::seedHash(BlockHeader const& _bi)
67 {
68  return EthashAux::seedHash((unsigned)_bi.number());
69 }
70 
71 StringHashMap Ethash::jsInfo(BlockHeader const& _bi) const
72 {
73  return { { "nonce", toJS(nonce(_bi)) }, { "seedHash", toJS(seedHash(_bi)) }, { "mixHash", toJS(mixHash(_bi)) }, { "boundary", toJS(boundary(_bi)) }, { "difficulty", toJS(_bi.difficulty()) } };
74 }
75 
76 void Ethash::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const
77 {
78  SealEngineFace::verify(_s, _bi, _parent, _block);
79 
80  if (_s != CheckNothingNew)
81  {
82  if (_bi.difficulty() < chainParams().u256Param("minimumDifficulty"))
83  BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(chainParams().u256Param("minimumDifficulty")), bigint(_bi.difficulty())) );
84 
85  if (_bi.gasLimit() < chainParams().u256Param("minGasLimit"))
86  BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().u256Param("minGasLimit")), bigint(_bi.gasLimit())) );
87 
88  if (_bi.gasLimit() > chainParams().u256Param("maxGasLimit"))
89  BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().u256Param("maxGasLimit")), bigint(_bi.gasLimit())) );
90 
91  if (_bi.number() && _bi.extraData().size() > chainParams().maximumExtraDataSize)
92  BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(chainParams().maximumExtraDataSize), bigint(_bi.extraData().size())) << errinfo_extraData(_bi.extraData()));
93 
94  u256 daoHardfork = chainParams().u256Param("daoHardforkBlock");
95  if (daoHardfork != 0 && daoHardfork + 9 >= daoHardfork && _bi.number() >= daoHardfork && _bi.number() <= daoHardfork + 9)
96  if (_bi.extraData() != fromHex("0x64616f2d686172642d666f726b"))
97  BOOST_THROW_EXCEPTION(ExtraDataIncorrect() << errinfo_comment("Received block from the wrong fork (invalid extradata)."));
98  }
99 
100  if (_parent)
101  {
102  // Check difficulty is correct given the two timestamps.
103  auto expected = calculateDifficulty(_bi, _parent);
104  auto difficulty = _bi.difficulty();
105  if (difficulty != expected)
106  BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)expected, (bigint)difficulty));
107 
108  auto gasLimit = _bi.gasLimit();
109  auto parentGasLimit = _parent.gasLimit();
110  if (
111  gasLimit < chainParams().u256Param("minGasLimit") ||
112  gasLimit > chainParams().u256Param("maxGasLimit") ||
113  gasLimit <= parentGasLimit - parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor") ||
114  gasLimit >= parentGasLimit + parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor"))
115  BOOST_THROW_EXCEPTION(
116  InvalidGasLimit()
117  << errinfo_min((bigint)((bigint)parentGasLimit - (bigint)(parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor"))))
118  << errinfo_got((bigint)gasLimit)
119  << errinfo_max((bigint)((bigint)parentGasLimit + parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor")))
120  );
121  }
122 
123  // check it hashes according to proof of work or that it's the genesis block.
124  if (_s == CheckEverything && _bi.parentHash() && !verifySeal(_bi))
125  {
126  InvalidBlockNonce ex;
127  ex << errinfo_nonce(nonce(_bi));
128  ex << errinfo_mixHash(mixHash(_bi));
129  ex << errinfo_seedHash(seedHash(_bi));
130  EthashProofOfWork::Result er = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
131  ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash));
132  ex << errinfo_hash256(_bi.hash(WithoutSeal));
133  ex << errinfo_difficulty(_bi.difficulty());
134  ex << errinfo_target(boundary(_bi));
135  BOOST_THROW_EXCEPTION(ex);
136  }
137  else if (_s == QuickNonce && _bi.parentHash() && !quickVerifySeal(_bi))
138  {
139  InvalidBlockNonce ex;
140  ex << errinfo_hash256(_bi.hash(WithoutSeal));
141  ex << errinfo_difficulty(_bi.difficulty());
142  ex << errinfo_nonce(nonce(_bi));
143  BOOST_THROW_EXCEPTION(ex);
144  }
145 }
146 
147 void Ethash::verifyTransaction(ImportRequirements::value _ir, TransactionBase const& _t, BlockHeader const& _bi) const
148 {
149  if (_ir & ImportRequirements::TransactionSignatures)
150  {
151  if (_bi.number() >= chainParams().u256Param("homsteadForkBlock"))
152  _t.checkLowS();
153  if (_bi.number() >= chainParams().u256Param("EIP158ForkBlock"))
154  {
155  int chainID(chainParams().u256Param("chainID"));
156  _t.checkChainId(chainID);
157  }
158  else
159  _t.checkChainId(-4);
160  }
161  // Unneeded as it's checked again in Executive. Keep it here since tests assume it's checked.
162  if (_ir & ImportRequirements::TransactionBasic && _t.baseGasRequired(evmSchedule(EnvInfo(_bi))) > _t.gas())
163  BOOST_THROW_EXCEPTION(OutOfGasIntrinsic());
164 }
165 
166 u256 Ethash::childGasLimit(BlockHeader const& _bi, u256 const& _gasFloorTarget) const
167 {
168  u256 gasFloorTarget = _gasFloorTarget == Invalid256 ? 3141562 : _gasFloorTarget;
169  u256 gasLimit = _bi.gasLimit();
170  u256 boundDivisor = chainParams().u256Param("gasLimitBoundDivisor");
171  if (gasLimit < gasFloorTarget)
172  return min<u256>(gasFloorTarget, gasLimit + gasLimit / boundDivisor - 1);
173  else
174  return max<u256>(gasFloorTarget, gasLimit - gasLimit / boundDivisor + 1 + (_bi.gasUsed() * 6 / 5) / boundDivisor);
175 }
176 
177 void Ethash::manuallySubmitWork(const h256& _mixHash, Nonce _nonce)
178 {
179  m_farm.submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr);
180 }
181 
182 u256 Ethash::calculateDifficulty(BlockHeader const& _bi, BlockHeader const& _parent) const
183 {
184  const unsigned c_expDiffPeriod = 100000;
185 
186  if (!_bi.number())
187  throw GenesisBlockCannotBeCalculated();
188  auto minimumDifficulty = chainParams().u256Param("minimumDifficulty");
189  auto difficultyBoundDivisor = chainParams().u256Param("difficultyBoundDivisor");
190  auto durationLimit = chainParams().u256Param("durationLimit");
191 
192  bigint target; // stick to a bigint for the target. Don't want to risk going negative.
193  if (_bi.number() < chainParams().u256Param("homsteadForkBlock"))
194  // Frontier-era difficulty adjustment
195  target = _bi.timestamp() >= _parent.timestamp() + durationLimit ? _parent.difficulty() - (_parent.difficulty() / difficultyBoundDivisor) : (_parent.difficulty() + (_parent.difficulty() / difficultyBoundDivisor));
196  else
197  // Homestead-era difficulty adjustment
198  target = _parent.difficulty() + _parent.difficulty() / 2048 * max<bigint>(1 - (bigint(_bi.timestamp()) - _parent.timestamp()) / 10, -99);
199 
200  bigint o = target;
201  unsigned periodCount = unsigned(_parent.number() + 1) / c_expDiffPeriod;
202  if (periodCount > 1)
203  o += (bigint(1) << (periodCount - 2)); // latter will eventually become huge, so ensure it's a bigint.
204 
205  o = max<bigint>(minimumDifficulty, o);
206  return u256(min<bigint>(o, std::numeric_limits<u256>::max()));
207 }
208 
209 void Ethash::populateFromParent(BlockHeader& _bi, BlockHeader const& _parent) const
210 {
211  SealEngineFace::populateFromParent(_bi, _parent);
212  _bi.setDifficulty(calculateDifficulty(_bi, _parent));
213  _bi.setGasLimit(childGasLimit(_parent));
214 }
215 
216 bool Ethash::quickVerifySeal(BlockHeader const& _bi) const
217 {
218  if (_bi.number() >= ETHASH_EPOCH_LENGTH * 2048)
219  return false;
220 
221  auto h = _bi.hash(WithoutSeal);
222  auto m = mixHash(_bi);
223  auto n = nonce(_bi);
224  auto b = boundary(_bi);
225  bool ret = !!ethash_quick_check_difficulty(
226  (ethash_h256_t const*)h.data(),
227  (uint64_t)(u64)n,
228  (ethash_h256_t const*)m.data(),
229  (ethash_h256_t const*)b.data());
230  return ret;
231 }
232 
233 bool Ethash::verifySeal(BlockHeader const& _bi) const
234 {
235  bool pre = quickVerifySeal(_bi);
236 #if !ETH_DEBUG
237  if (!pre)
238  {
239  cwarn << "Fail on preVerify";
240  return false;
241  }
242 #endif
243 
244  auto result = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
245  bool slow = result.value <= boundary(_bi) && result.mixHash == mixHash(_bi);
246 
247 #if ETH_DEBUG
248  if (!pre && slow)
249  {
250  cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false.";
251  cwarn << "headerHash:" << _bi.hash(WithoutSeal);
252  cwarn << "nonce:" << nonce(_bi);
253  cwarn << "mixHash:" << mixHash(_bi);
254  cwarn << "difficulty:" << _bi.difficulty();
255  cwarn << "boundary:" << boundary(_bi);
256  cwarn << "result.value:" << result.value;
257  cwarn << "result.mixHash:" << result.mixHash;
258  }
259 #endif // ETH_DEBUG
260 
261  return slow;
262 }
263 
264 void Ethash::generateSeal(BlockHeader const& _bi)
265 {
266  m_sealing = _bi;
267  m_farm.setWork(m_sealing);
268  m_farm.start(m_sealer);
269  m_farm.setWork(m_sealing); // TODO: take out one before or one after...
270  bytes shouldPrecompute = option("precomputeDAG");
271  if (!shouldPrecompute.empty() && shouldPrecompute[0] == 1)
272  ensurePrecomputed((unsigned)_bi.number());
273 }
274 
275 bool Ethash::shouldSeal(Interface*)
276 {
277  return true;
278 }
279 
280 void Ethash::ensurePrecomputed(unsigned _number)
281 {
282  if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10)
283  // 90% of the way to the new epoch
284  EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true);
285 }
Too little gas to pay for the base transaction cost.
Adapted from code found on http://stackoverflow.com/questions/180947/base64-decode-snippet-in-c Origi...
Definition: Arith256.cpp:15
u256 const & number() const
Definition: BlockHeader.h:162
h256 hash(IncludeSeal _i=WithSeal) const
Definition: BlockHeader.cpp:64
Encapsulation of a block header.
Definition: BlockHeader.h:95
boost::multiprecision::number< boost::multiprecision::cpp_int_backend<>> bigint
Definition: Common.h:121
bool ethash_quick_check_difficulty(ethash_h256_t const *header_hash, uint64_t const nonce, ethash_h256_t const *mix_hash, ethash_h256_t const *boundary)
Difficulty quick check for POW preverification.
Definition: internal.c:354
#define h(i)
Definition: sha.cpp:736
bytes const & out() const
Read the byte stream.
Definition: RLP.h:433
bool verify(Public const &_k, Signature const &_s, h256 const &_hash)
Verify signature.
Definition: Common.cpp:255
std::vector< std::string > strings
Definition: Common.h:147
std::hash for asio::adress
Definition: Common.h:323
boost::error_info< struct tag_min, bigint > errinfo_min
Definition: Exceptions.h:78
boost::error_info< struct tag_max, bigint > errinfo_max
Definition: Exceptions.h:79
int64_t baseGasRequired(EVMSchedule const &_es) const
Definition: Transaction.h:148
#define ETHASH_EPOCH_LENGTH
Definition: ethash.h:34
h256 const & parentHash() const
Definition: BlockHeader.h:154
boost::error_info< struct tag_mixHash, h256 > errinfo_mixHash
Definition: Exceptions.h:40
boost::error_info< struct tag_hash, h256 > errinfo_hash256
Definition: Exceptions.h:81
bytes fromHex(std::string const &_s, WhenError _throw=WhenError::DontThrow)
Definition: CommonData.cpp:99
boost::error_info< struct tag_ethashResult, std::tuple< h256, h256 >> errinfo_ethashResult
Definition: Exceptions.h:41
std::string toJS(FixedHash< S > const &_h)
Definition: CommonJS.h:34
ExecStats::duration max
Definition: ExecStats.cpp:36
bytes const & extraData() const
Definition: BlockHeader.h:164
boost::error_info< struct tag_got, bigint > errinfo_got
Definition: Exceptions.h:77
std::vector< byte > bytes
Definition: Common.h:75
const u256 Invalid256
Definition: Common.cpp:38
boost::error_info< struct tag_target, h256 > errinfo_target
Definition: Exceptions.h:38
#define cwarn
Definition: Log.h:304
boost::error_info< struct tag_extraData, bytes > errinfo_extraData
Definition: Exceptions.h:85
void checkChainId(int chainId=-4) const
void setGasLimit(u256 const &_v)
Definition: BlockHeader.h:147
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u256
Definition: Common.h:125
std::unordered_map< std::string, std::string > StringHashMap
Definition: Common.h:143
Main API hub for interfacing with Ethereum.
Definition: Interface.h:67
#define b(i, j)
boost::error_info< struct tag_difficulty, u256 > errinfo_difficulty
Definition: Exceptions.h:37
u256 const & timestamp() const
Definition: BlockHeader.h:156
Type of a seedhash/blockhash e.t.c.
Definition: ethash.h:48
boost::multiprecision::number< boost::multiprecision::cpp_int_backend< 64, 64, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void >> u64
Definition: Common.h:123
boost::error_info< struct tag_seedHash, h256 > errinfo_seedHash
Definition: Exceptions.h:39
boost::error_info< struct tag_comment, std::string > errinfo_comment
Definition: Assertions.h:78
u256 const & gasLimit() const
Definition: BlockHeader.h:163
A miner - a member and adoptee of the Farm.
Definition: GenericMiner.h:43
boost::tuple< errinfo_required, errinfo_got > RequirementError
Definition: Exceptions.h:80
u256 const & gasUsed() const
Definition: BlockHeader.h:161
Class for writing to an RLP bytestream.
Definition: RLP.h:383
u256 const & difficulty() const
Definition: BlockHeader.h:166
void setDifficulty(u256 const &_v)
Definition: BlockHeader.h:150
Encodes a transaction, ready to be exported to or freshly imported from RLP.
Definition: Transaction.h:50
#define ETH_REGISTER_SEAL_ENGINE(Name)
Definition: SealEngine.h:148
boost::error_info< struct tag_nonce, h64 > errinfo_nonce
Definition: Exceptions.h:36