Extract multihash functions

This commit was merged in pull request #33.
This commit is contained in:
2018-04-07 19:24:45 +02:00
committed by Michael Bumann
parent 939baec1a8
commit 6e262537a4
3 changed files with 48 additions and 45 deletions
+4 -1
View File
@@ -1,5 +1,8 @@
import ContributorSerializer from './serializers/contributor';
import { fromBytes32, toBytes32 } from './utils/multihash';
export {
ContributorSerializer
ContributorSerializer,
fromBytes32,
toBytes32
};
+33
View File
@@ -0,0 +1,33 @@
import bs58 from 'npm:bs58';
import NpmBuffer from 'npm:buffer';
const Buffer = NpmBuffer.Buffer;
function fromBytes32({ digest, hashFunction, hashSize }) {
if (hashSize === 0) {
return;
}
const hashBytes = Buffer.from(digest.slice(2), 'hex');
const multiHashBytes = new (hashBytes.constructor)(2 + hashBytes.length);
multiHashBytes[0] = hashFunction;
multiHashBytes[1] = hashSize;
multiHashBytes.set(hashBytes, 2);
return bs58.encode(multiHashBytes);
}
function toBytes32(string) {
const decoded = bs58.decode(string);
return {
digest: `0x${decoded.slice(2).toString('hex')}`,
hashFunction: decoded[0],
hashSize: decoded[1],
};
}
export {
fromBytes32,
toBytes32
};