【发布时间】:2020-08-12 13:18:41
【问题描述】:
所以我正在尝试为学校项目实施加密货币,但我被困在区块验证部分,即挖矿。我使用了我在网上找到的这段代码,并将其改编为我的项目:
void Block::MineBlock(int nDifficulty)
{
std::string cstr(nDifficulty + 1, '\0');
for (int i = 0; i < nDifficulty; i++)
{
cstr[i] = '0';
}
cstr[nDifficulty] = '\0';
std::string str(cstr);
do
{
nNonce++;
blockHash = generateHash();
} while (blockHash.substr(0, nDifficulty) != str);
this->checked = true;
}
我的 nDifficulty 设置为 1。它无限循环是否正常? 这里也是 generateHash 函数:
std::string Block::generateHash()
{
std::stringstream ss;
ss << index << timestamp << filename << nNonce << prevHash;
return sha256(ss.str());
}
【问题讨论】:
-
如果要删除
std::string中的最后一个字符,请使用std::string::pop。不要将最后一个字符设置为\0- 这不会改变大小。 -
如果没有随机数产生满足难度要求的哈希,则此代码无限循环。这很常见。
-
那么有谁知道如何制作一个更容易散列的函数?
标签: c++ hash data-mining sha256 cryptocurrency