feat: add CID.fromHash

This commit is contained in:
Derrick Hammer 2023-09-07 18:51:40 -04:00
parent 764685a111
commit 4a157d9eca
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
1 changed files with 17 additions and 0 deletions

View File

@ -3,6 +3,7 @@ import { Multihash } from "#multihash.js";
import { CID_TYPES, REGISTRY_TYPES } from "#constants.js";
import { decodeEndian, encodeEndian } from "#util.js";
import { concatBytes, equalBytes } from "@noble/curves/abstract/utils";
import { hexToBytes } from "@noble/hashes/utils";
export default class CID extends Multibase {
type: number;
@ -25,6 +26,22 @@ export default class CID extends Multibase {
return CID._init(bytes);
}
static fromHash(
bytes: string | Uint8Array,
size: number,
type = CID_TYPES.RAW,
): CID {
if (typeof bytes === "string") {
bytes = hexToBytes(bytes);
}
if (!Object.values(CID_TYPES).includes(type)) {
throw new Error(`invalid cid type ${type}`);
}
return new CID(type, new Multihash(bytes), size);
}
private static _init(bytes: Uint8Array): CID {
const type = bytes[0];
if (type === CID_TYPES.BRIDGE) {