-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcid.ts
More file actions
45 lines (40 loc) · 1.33 KB
/
Copy pathcid.ts
File metadata and controls
45 lines (40 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Content addressing via CIDv1 (sha2-256, raw codec).
*
* bafybei… = base32 multibase of (CIDv1 + raw + sha2-256 + 32-byte digest)
*
* Specification:
* https://github.com/multiformats/cid
*/
import { CID } from "multiformats/cid";
import * as raw from "multiformats/codecs/raw";
import { sha256 } from "multiformats/hashes/sha2";
/** Compute the CIDv1 (raw codec, sha2-256) for arbitrary bytes. */
export async function bytesToCid(bytes: Uint8Array): Promise<CID> {
const digest = await sha256.digest(bytes);
return CID.create(1, raw.code, digest);
}
/** Convenience: returns the canonical multibase string (e.g. `bafybei…`). */
export async function bytesToCidString(bytes: Uint8Array): Promise<string> {
return (await bytesToCid(bytes)).toString();
}
/** Parse a CID string. Throws if malformed. */
export function parseCid(s: string): CID {
return CID.parse(s);
}
/** Validate a string is a syntactically well-formed CID. */
export function isCid(s: string): boolean {
try {
CID.parse(s);
return true;
} catch {
return false;
}
}
/** Constant-time equality check for two CID strings. */
export function cidEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}