Update swarm hash.

This commit is contained in:
chriseth
2019-06-27 12:48:51 +02:00
parent 8d18003808
commit aa11ad7d0a
6 changed files with 122 additions and 21 deletions
+48 -1
View File
@@ -61,9 +61,56 @@ h256 swarmHashIntermediate(string const& _input, size_t _offset, size_t _length)
return swarmHashSimple(ref, _length);
}
h256 bmtHash(bytesConstRef _data)
{
if (_data.size() <= 64)
return keccak256(_data);
size_t midPoint = _data.size() / 2;
return keccak256(
bmtHash(_data.cropped(0, midPoint)).asBytes() +
bmtHash(_data.cropped(midPoint)).asBytes()
);
}
h256 dev::swarmHash(string const& _input)
h256 chunkHash(bytesConstRef const _data, bool _forceHigherLevel = false)
{
bytes dataToHash;
if (_data.size() < 0x1000)
dataToHash = _data.toBytes();
else if (_data.size() == 0x1000 && !_forceHigherLevel)
dataToHash = _data.toBytes();
else
{
size_t maxRepresentedSize = 0x1000;
while (maxRepresentedSize * (0x1000 / 32) < _data.size())
maxRepresentedSize *= (0x1000 / 32);
// If remaining size is 0x1000, but maxRepresentedSize is not,
// we have to still do one level of the chunk hashes.
bool forceHigher = maxRepresentedSize > 0x1000;
for (size_t i = 0; i < _data.size(); i += maxRepresentedSize)
{
size_t size = std::min(maxRepresentedSize, _data.size() - i);
dataToHash += chunkHash(_data.cropped(i, size), forceHigher).asBytes();
}
}
dataToHash.resize(0x1000, 0);
return keccak256(toLittleEndian(_data.size()) + bmtHash(&dataToHash).asBytes());
}
}
h256 dev::bzzr0Hash(string const& _input)
{
return swarmHashIntermediate(_input, 0, _input.size());
}
h256 dev::bzzr1Hash(bytes const& _input)
{
if (_input.empty())
return h256{};
return chunkHash(&_input);
}
+10 -2
View File
@@ -26,7 +26,15 @@
namespace dev
{
/// Compute the "swarm hash" of @a _input
h256 swarmHash(std::string const& _input);
/// Compute the "swarm hash" of @a _input (OLD 0x1000-section version)
h256 bzzr0Hash(std::string const& _input);
/// Compute the "bzz hash" of @a _input (the NEW binary / BMT version)
h256 bzzr1Hash(bytes const& _input);
inline h256 bzzr1Hash(std::string const& _input)
{
return bzzr1Hash(asBytes(_input));
}
}