Suite of AT Protocol TypeScript libraries built on web standards
1import { create as createDigest } from "multiformats/hashes/digest";
2import { sha256 as hasher } from "multiformats/hashes/sha2";
3import {
4 type Cid,
5 createCid,
6 DAG_CBOR_MULTICODEC,
7 decodeCid,
8 RAW_BIN_MULTICODEC,
9 SHA2_256_MULTIHASH_CODE,
10} from "../data/cid.ts";
11import type { LexValue } from "../data/lex.ts";
12import { decode, decodeAll, encode } from "./encoding.ts";
13
14export { hasher };
15export { decode, decodeAll, encode };
16export type { Cid, LexValue };
17
18export function cidForLex(value: LexValue): Promise<Cid> {
19 return cidForCbor(encode(value));
20}
21
22export async function cidForCbor(bytes: Uint8Array): Promise<Cid> {
23 const digest = await hasher.digest(bytes);
24 return createCid(DAG_CBOR_MULTICODEC, digest);
25}
26
27export async function verifyCidForBytes(
28 cid: Cid,
29 bytes: Uint8Array,
30): Promise<void> {
31 const digest = await hasher.digest(bytes);
32 const expected = createCid(cid.code, digest);
33 if (!cid.equals(expected)) {
34 throw new Error(
35 `Not a valid CID for bytes. Expected: ${expected.toString()} Got: ${cid.toString()}`,
36 );
37 }
38}
39
40export async function cidForRawBytes(bytes: Uint8Array): Promise<Cid> {
41 const digest = await hasher.digest(bytes);
42 return createCid(RAW_BIN_MULTICODEC, digest);
43}
44
45export function cidForRawHash(hash: Uint8Array): Cid {
46 const digest = createDigest(hasher.code, hash);
47 return createCid(RAW_BIN_MULTICODEC, digest);
48}
49
50export function parseCidFromBytes(cidBytes: Uint8Array): Cid {
51 const version = cidBytes[0];
52 if (version !== 0x01) {
53 throw new Error(`Unsupported CID version: ${version}`);
54 }
55 const code = cidBytes[1];
56 if (code !== RAW_BIN_MULTICODEC && code !== DAG_CBOR_MULTICODEC) {
57 throw new Error(`Unsupported CID codec: ${code}`);
58 }
59 const hashType = cidBytes[2];
60 if (hashType !== SHA2_256_MULTIHASH_CODE) {
61 throw new Error(`Unsupported CID hash function: ${hashType}`);
62 }
63 const hashLength = cidBytes[3];
64 if (hashLength !== 32) {
65 throw new Error(`Unexpected CID hash length: ${hashLength}`);
66 }
67 if (hashLength !== cidBytes.length - 4) {
68 throw new Error(`Unexpected CID bytes length: ${hashLength}`);
69 }
70 const hashBytes = cidBytes.slice(4);
71 const digest = createDigest(hashType, hashBytes);
72 return createCid(code, digest);
73}
74
75export function decodeCidFromBytes(bytes: Uint8Array): Cid {
76 return decodeCid(bytes);
77}