Ethash.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /*
  2. This file is part of cpp-ethereum.
  3. cpp-ethereum is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. cpp-ethereum is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. /** @file Ethash.cpp
  15. * @author Gav Wood <i@gavwood.com>
  16. * @date 2014
  17. */
  18. #include "Ethash.h"
  19. #include <libethash/ethash.h>
  20. #include <libethash/internal.h>
  21. #include <libethereum/Interface.h>
  22. #include <libethcore/ChainOperationParams.h>
  23. #include <libethcore/CommonJS.h>
  24. #include "EthashCPUMiner.h"
  25. #include "EthashGPUMiner.h"
  26. using namespace std;
  27. using namespace dev;
  28. using namespace eth;
  29. void Ethash::init()
  30. {
  31. ETH_REGISTER_SEAL_ENGINE(Ethash);
  32. }
  33. Ethash::Ethash()
  34. {
  35. map<string, GenericFarm<EthashProofOfWork>::SealerDescriptor> sealers;
  36. sealers["cpu"] = GenericFarm<EthashProofOfWork>::SealerDescriptor{&EthashCPUMiner::instances, [](GenericMiner<EthashProofOfWork>::ConstructionInfo ci){ return new EthashCPUMiner(ci); }};
  37. #if ETH_ETHASHCL
  38. sealers["opencl"] = GenericFarm<EthashProofOfWork>::SealerDescriptor{&EthashGPUMiner::instances, [](GenericMiner<EthashProofOfWork>::ConstructionInfo ci){ return new EthashGPUMiner(ci); }};
  39. #endif
  40. m_farm.setSealers(sealers);
  41. m_farm.onSolutionFound([=](EthashProofOfWork::Solution const& sol)
  42. {
  43. // cdebug << m_farm.work().seedHash << m_farm.work().headerHash << sol.nonce << EthashAux::eval(m_farm.work().seedHash, m_farm.work().headerHash, sol.nonce).value;
  44. setMixHash(m_sealing, sol.mixHash);
  45. setNonce(m_sealing, sol.nonce);
  46. if (!quickVerifySeal(m_sealing))
  47. return false;
  48. if (m_onSealGenerated)
  49. {
  50. RLPStream ret;
  51. m_sealing.streamRLP(ret);
  52. m_onSealGenerated(ret.out());
  53. }
  54. return true;
  55. });
  56. }
  57. strings Ethash::sealers() const
  58. {
  59. return {
  60. "cpu"
  61. #if ETH_ETHASHCL
  62. , "opencl"
  63. #endif
  64. };
  65. }
  66. h256 Ethash::seedHash(BlockHeader const& _bi)
  67. {
  68. return EthashAux::seedHash((unsigned)_bi.number());
  69. }
  70. StringHashMap Ethash::jsInfo(BlockHeader const& _bi) const
  71. {
  72. return { { "nonce", toJS(nonce(_bi)) }, { "seedHash", toJS(seedHash(_bi)) }, { "mixHash", toJS(mixHash(_bi)) }, { "boundary", toJS(boundary(_bi)) }, { "difficulty", toJS(_bi.difficulty()) } };
  73. }
  74. EVMSchedule const& Ethash::evmSchedule(EnvInfo const& _envInfo) const
  75. {
  76. if (_envInfo.number() >= chainParams().u256Param("EIP158ForkBlock"))
  77. return EIP158Schedule;
  78. else if (_envInfo.number() >= chainParams().u256Param("EIP150ForkBlock"))
  79. return EIP150Schedule;
  80. else if (_envInfo.number() >= chainParams().u256Param("homsteadForkBlock"))
  81. return HomesteadSchedule;
  82. else
  83. return FrontierSchedule;
  84. }
  85. void Ethash::verify(Strictness _s, BlockHeader const& _bi, BlockHeader const& _parent, bytesConstRef _block) const
  86. {
  87. SealEngineFace::verify(_s, _bi, _parent, _block);
  88. if (_s != CheckNothingNew)
  89. {
  90. if (_bi.difficulty() < chainParams().u256Param("minimumDifficulty"))
  91. BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError(bigint(chainParams().u256Param("minimumDifficulty")), bigint(_bi.difficulty())) );
  92. if (_bi.gasLimit() < chainParams().u256Param("minGasLimit"))
  93. BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().u256Param("minGasLimit")), bigint(_bi.gasLimit())) );
  94. if (_bi.gasLimit() > chainParams().u256Param("maxGasLimit"))
  95. BOOST_THROW_EXCEPTION(InvalidGasLimit() << RequirementError(bigint(chainParams().u256Param("maxGasLimit")), bigint(_bi.gasLimit())) );
  96. if (_bi.number() && _bi.extraData().size() > chainParams().maximumExtraDataSize)
  97. BOOST_THROW_EXCEPTION(ExtraDataTooBig() << RequirementError(bigint(chainParams().maximumExtraDataSize), bigint(_bi.extraData().size())) << errinfo_extraData(_bi.extraData()));
  98. u256 daoHardfork = chainParams().u256Param("daoHardforkBlock");
  99. if (daoHardfork != 0 && daoHardfork + 9 >= daoHardfork && _bi.number() >= daoHardfork && _bi.number() <= daoHardfork + 9)
  100. if (_bi.extraData() != fromHex("0x64616f2d686172642d666f726b"))
  101. BOOST_THROW_EXCEPTION(ExtraDataIncorrect() << errinfo_comment("Received block from the wrong fork (invalid extradata)."));
  102. }
  103. if (_parent)
  104. {
  105. // Check difficulty is correct given the two timestamps.
  106. auto expected = calculateDifficulty(_bi, _parent);
  107. auto difficulty = _bi.difficulty();
  108. if (difficulty != expected)
  109. BOOST_THROW_EXCEPTION(InvalidDifficulty() << RequirementError((bigint)expected, (bigint)difficulty));
  110. auto gasLimit = _bi.gasLimit();
  111. auto parentGasLimit = _parent.gasLimit();
  112. if (
  113. gasLimit < chainParams().u256Param("minGasLimit") ||
  114. gasLimit > chainParams().u256Param("maxGasLimit") ||
  115. gasLimit <= parentGasLimit - parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor") ||
  116. gasLimit >= parentGasLimit + parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor"))
  117. BOOST_THROW_EXCEPTION(
  118. InvalidGasLimit()
  119. << errinfo_min((bigint)((bigint)parentGasLimit - (bigint)(parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor"))))
  120. << errinfo_got((bigint)gasLimit)
  121. << errinfo_max((bigint)((bigint)parentGasLimit + parentGasLimit / chainParams().u256Param("gasLimitBoundDivisor")))
  122. );
  123. }
  124. // check it hashes according to proof of work or that it's the genesis block.
  125. if (_s == CheckEverything && _bi.parentHash() && !verifySeal(_bi))
  126. {
  127. InvalidBlockNonce ex;
  128. ex << errinfo_nonce(nonce(_bi));
  129. ex << errinfo_mixHash(mixHash(_bi));
  130. ex << errinfo_seedHash(seedHash(_bi));
  131. EthashProofOfWork::Result er = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
  132. ex << errinfo_ethashResult(make_tuple(er.value, er.mixHash));
  133. ex << errinfo_hash256(_bi.hash(WithoutSeal));
  134. ex << errinfo_difficulty(_bi.difficulty());
  135. ex << errinfo_target(boundary(_bi));
  136. BOOST_THROW_EXCEPTION(ex);
  137. }
  138. else if (_s == QuickNonce && _bi.parentHash() && !quickVerifySeal(_bi))
  139. {
  140. InvalidBlockNonce ex;
  141. ex << errinfo_hash256(_bi.hash(WithoutSeal));
  142. ex << errinfo_difficulty(_bi.difficulty());
  143. ex << errinfo_nonce(nonce(_bi));
  144. BOOST_THROW_EXCEPTION(ex);
  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.gasRequired(evmSchedule(EnvInfo(_bi))) > _t.gas())
  163. BOOST_THROW_EXCEPTION(OutOfGasIntrinsic());
  164. }
  165. u256 Ethash::childGasLimit(BlockHeader const& _bi, u256 const& _gasFloorTarget) const
  166. {
  167. u256 gasFloorTarget = _gasFloorTarget == Invalid256 ? 3141562 : _gasFloorTarget;
  168. u256 gasLimit = _bi.gasLimit();
  169. u256 boundDivisor = chainParams().u256Param("gasLimitBoundDivisor");
  170. if (gasLimit < gasFloorTarget)
  171. return min<u256>(gasFloorTarget, gasLimit + gasLimit / boundDivisor - 1);
  172. else
  173. return max<u256>(gasFloorTarget, gasLimit - gasLimit / boundDivisor + 1 + (_bi.gasUsed() * 6 / 5) / boundDivisor);
  174. }
  175. void Ethash::manuallySubmitWork(const h256& _mixHash, Nonce _nonce)
  176. {
  177. m_farm.submitProof(EthashProofOfWork::Solution{_nonce, _mixHash}, nullptr);
  178. }
  179. u256 Ethash::calculateDifficulty(BlockHeader const& _bi, BlockHeader const& _parent) const
  180. {
  181. const unsigned c_expDiffPeriod = 100000;
  182. if (!_bi.number())
  183. throw GenesisBlockCannotBeCalculated();
  184. auto minimumDifficulty = chainParams().u256Param("minimumDifficulty");
  185. auto difficultyBoundDivisor = chainParams().u256Param("difficultyBoundDivisor");
  186. auto durationLimit = chainParams().u256Param("durationLimit");
  187. bigint target; // stick to a bigint for the target. Don't want to risk going negative.
  188. if (_bi.number() < chainParams().u256Param("homsteadForkBlock"))
  189. // Frontier-era difficulty adjustment
  190. target = _bi.timestamp() >= _parent.timestamp() + durationLimit ? _parent.difficulty() - (_parent.difficulty() / difficultyBoundDivisor) : (_parent.difficulty() + (_parent.difficulty() / difficultyBoundDivisor));
  191. else
  192. // Homestead-era difficulty adjustment
  193. target = _parent.difficulty() + _parent.difficulty() / 2048 * max<bigint>(1 - (bigint(_bi.timestamp()) - _parent.timestamp()) / 10, -99);
  194. bigint o = target;
  195. unsigned periodCount = unsigned(_parent.number() + 1) / c_expDiffPeriod;
  196. if (periodCount > 1)
  197. o += (bigint(1) << (periodCount - 2)); // latter will eventually become huge, so ensure it's a bigint.
  198. o = max<bigint>(minimumDifficulty, o);
  199. return u256(min<bigint>(o, std::numeric_limits<u256>::max()));
  200. }
  201. void Ethash::populateFromParent(BlockHeader& _bi, BlockHeader const& _parent) const
  202. {
  203. SealEngineFace::populateFromParent(_bi, _parent);
  204. _bi.setDifficulty(calculateDifficulty(_bi, _parent));
  205. _bi.setGasLimit(childGasLimit(_parent));
  206. }
  207. bool Ethash::quickVerifySeal(BlockHeader const& _bi) const
  208. {
  209. if (_bi.number() >= ETHASH_EPOCH_LENGTH * 2048)
  210. return false;
  211. auto h = _bi.hash(WithoutSeal);
  212. auto m = mixHash(_bi);
  213. auto n = nonce(_bi);
  214. auto b = boundary(_bi);
  215. bool ret = !!ethash_quick_check_difficulty(
  216. (ethash_h256_t const*)h.data(),
  217. (uint64_t)(u64)n,
  218. (ethash_h256_t const*)m.data(),
  219. (ethash_h256_t const*)b.data());
  220. return ret;
  221. }
  222. bool Ethash::verifySeal(BlockHeader const& _bi) const
  223. {
  224. bool pre = quickVerifySeal(_bi);
  225. #if !ETH_DEBUG
  226. if (!pre)
  227. {
  228. cwarn << "Fail on preVerify";
  229. return false;
  230. }
  231. #endif
  232. auto result = EthashAux::eval(seedHash(_bi), _bi.hash(WithoutSeal), nonce(_bi));
  233. bool slow = result.value <= boundary(_bi) && result.mixHash == mixHash(_bi);
  234. #if ETH_DEBUG
  235. if (!pre && slow)
  236. {
  237. cwarn << "WARNING: evaluated result gives true whereas ethash_quick_check_difficulty gives false.";
  238. cwarn << "headerHash:" << _bi.hash(WithoutSeal);
  239. cwarn << "nonce:" << nonce(_bi);
  240. cwarn << "mixHash:" << mixHash(_bi);
  241. cwarn << "difficulty:" << _bi.difficulty();
  242. cwarn << "boundary:" << boundary(_bi);
  243. cwarn << "result.value:" << result.value;
  244. cwarn << "result.mixHash:" << result.mixHash;
  245. }
  246. #endif // ETH_DEBUG
  247. return slow;
  248. }
  249. void Ethash::generateSeal(BlockHeader const& _bi)
  250. {
  251. m_sealing = _bi;
  252. m_farm.setWork(m_sealing);
  253. m_farm.start(m_sealer);
  254. m_farm.setWork(m_sealing); // TODO: take out one before or one after...
  255. bytes shouldPrecompute = option("precomputeDAG");
  256. if (!shouldPrecompute.empty() && shouldPrecompute[0] == 1)
  257. ensurePrecomputed((unsigned)_bi.number());
  258. }
  259. void Ethash::onSealGenerated(std::function<void(bytes const&)> const& _f)
  260. {
  261. m_onSealGenerated = _f;
  262. }
  263. bool Ethash::shouldSeal(Interface*)
  264. {
  265. return true;
  266. }
  267. void Ethash::ensurePrecomputed(unsigned _number)
  268. {
  269. if (_number % ETHASH_EPOCH_LENGTH > ETHASH_EPOCH_LENGTH * 9 / 10)
  270. // 90% of the way to the new epoch
  271. EthashAux::computeFull(EthashAux::seedHash(_number + ETHASH_EPOCH_LENGTH), true);
  272. }