|
20 | 20 | #include <libdevcore/SwarmHash.h>
|
21 | 21 |
|
22 | 22 | #include <libdevcore/Keccak256.h>
|
| 23 | +#include <libdevcore/picosha2.h> |
23 | 24 |
|
24 | 25 | using namespace std;
|
25 | 26 | using namespace dev;
|
@@ -67,3 +68,39 @@ h256 dev::swarmHash(string const& _input)
|
67 | 68 | {
|
68 | 69 | return swarmHashIntermediate(_input, 0, _input.size());
|
69 | 70 | }
|
| 71 | + |
| 72 | +namespace |
| 73 | +{ |
| 74 | +bytes varintEncoding(size_t _n) |
| 75 | +{ |
| 76 | + uint8_t leastSignificant = _n & 0x7f; |
| 77 | + size_t moreSignificant = _n >> 7; |
| 78 | + if (moreSignificant) |
| 79 | + return bytes{uint8_t(uint8_t(0x80) | leastSignificant)} + varintEncoding(moreSignificant); |
| 80 | + else |
| 81 | + return bytes{leastSignificant}; |
| 82 | +} |
| 83 | +} |
| 84 | + |
| 85 | +bytes dev::ipfsHash(string const& _data) |
| 86 | +{ |
| 87 | + bytes lengthAsVarint = varintEncoding(_data.size()); |
| 88 | + |
| 89 | + bytes protobufEncodedData; |
| 90 | + // Type: File |
| 91 | + protobufEncodedData += bytes{0x08, 0x02}; |
| 92 | + if (!_data.empty()) |
| 93 | + { |
| 94 | + // Data (length delimited bytes) |
| 95 | + protobufEncodedData += bytes{0x12}; |
| 96 | + protobufEncodedData += lengthAsVarint; |
| 97 | + protobufEncodedData += asBytes(_data); |
| 98 | + } |
| 99 | + // filesize: length as varint |
| 100 | + protobufEncodedData += bytes{0x18} + lengthAsVarint; |
| 101 | + |
| 102 | + cout << toHex(protobufEncodedData) << endl; |
| 103 | + // Multihash: sha2-256, 256 bits |
| 104 | + // TODO Do not go to hex and back |
| 105 | + return bytes{0x12, 0x20} + fromHex(picosha2::hash256_hex_string(protobufEncodedData)); |
| 106 | +} |
0 commit comments