|
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,60 @@ 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 | +string base58Encode(bytes const& _data) |
| 85 | +{ |
| 86 | + static string const alphabet{"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}; |
| 87 | + bigint data(toHex(_data, HexPrefix::Add)); |
| 88 | + string output; |
| 89 | + while (data) |
| 90 | + { |
| 91 | + output += alphabet[size_t(data % alphabet.size())]; |
| 92 | + data /= alphabet.size(); |
| 93 | + } |
| 94 | + reverse(output.begin(), output.end()); |
| 95 | + return output; |
| 96 | +} |
| 97 | +} |
| 98 | + |
| 99 | +bytes dev::ipfsHash(string const& _data) |
| 100 | +{ |
| 101 | + bytes lengthAsVarint = varintEncoding(_data.size()); |
| 102 | + |
| 103 | + bytes protobufEncodedData; |
| 104 | + // Type: File |
| 105 | + protobufEncodedData += bytes{0x08, 0x02}; |
| 106 | + if (!_data.empty()) |
| 107 | + { |
| 108 | + // Data (length delimited bytes) |
| 109 | + protobufEncodedData += bytes{0x12}; |
| 110 | + protobufEncodedData += lengthAsVarint; |
| 111 | + protobufEncodedData += asBytes(_data); |
| 112 | + } |
| 113 | + // filesize: length as varint |
| 114 | + protobufEncodedData += bytes{0x18} + lengthAsVarint; |
| 115 | + |
| 116 | + // TODO check what this actually refers to |
| 117 | + // TODO Handle "large" files with multiple blocks |
| 118 | + bytes blockData = bytes{0x0a} + varintEncoding(protobufEncodedData.size()) + protobufEncodedData; |
| 119 | + |
| 120 | + cout << toHex(protobufEncodedData) << endl; |
| 121 | + cout << toHex(blockData) << endl; |
| 122 | + // Multihash: sha2-256, 256 bits |
| 123 | + // TODO Do not go to hex and back |
| 124 | + bytes hash = bytes{0x12, 0x20} + fromHex(picosha2::hash256_hex_string(blockData)); |
| 125 | + cout << "ipfs://" << base58Encode(hash) << endl; |
| 126 | + return hash; |
| 127 | +} |
0 commit comments