Skip to content

Commit

Permalink
[WIP] Tools to compute UnixFS IPFS hash.
Browse files Browse the repository at this point in the history
  • Loading branch information
chriseth committed Apr 25, 2019
1 parent fbe225a commit 47cae3e
Show file tree
Hide file tree
Showing 5 changed files with 410 additions and 0 deletions.
1 change: 1 addition & 0 deletions libdevcore/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ set(sources
JSON.h
Keccak256.cpp
Keccak256.h
picosha2.h
Result.h
StringUtils.cpp
StringUtils.h
Expand Down
37 changes: 37 additions & 0 deletions libdevcore/SwarmHash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <libdevcore/SwarmHash.h>

#include <libdevcore/Keccak256.h>
#include <libdevcore/picosha2.h>

using namespace std;
using namespace dev;
Expand Down Expand Up @@ -67,3 +68,39 @@ h256 dev::swarmHash(string const& _input)
{
return swarmHashIntermediate(_input, 0, _input.size());
}

namespace
{
bytes varintEncoding(size_t _n)
{
uint8_t leastSignificant = _n & 0x7f;
size_t moreSignificant = _n >> 7;
if (moreSignificant)
return bytes{uint8_t(uint8_t(0x80) | leastSignificant)} + varintEncoding(moreSignificant);
else
return bytes{leastSignificant};
}
}

bytes dev::ipfsHash(string const& _data)
{
bytes lengthAsVarint = varintEncoding(_data.size());

bytes protobufEncodedData;
// Type: File
protobufEncodedData += bytes{0x08, 0x02};
if (!_data.empty())
{
// Data (length delimited bytes)
protobufEncodedData += bytes{0x12};
protobufEncodedData += lengthAsVarint;
protobufEncodedData += asBytes(_data);
}
// filesize: length as varint
protobufEncodedData += bytes{0x18} + lengthAsVarint;

cout << toHex(protobufEncodedData) << endl;
// Multihash: sha2-256, 256 bits
// TODO Do not go to hex and back
return bytes{0x12, 0x20} + fromHex(picosha2::hash256_hex_string(protobufEncodedData));
}
6 changes: 6 additions & 0 deletions libdevcore/SwarmHash.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,11 @@ namespace dev

/// Compute the "swarm hash" of @a _input
h256 swarmHash(std::string const& _input);
/// Compute the "ipfs hash" of a file with the content @a _data.
/// The output will be the multihash of the UnixFS protobuf encoded data.
/// As hash function it will use sha2-256.
/// The effect is that the hash should be identical to the one produced by
/// the command `ipfs add <filename>`.
bytes ipfsHash(std::string const& _data);

}
Loading

0 comments on commit 47cae3e

Please sign in to comment.