@parity/product-sdk-bulletin 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cid.ts CHANGED
@@ -1,126 +1,62 @@
1
- import { blake2b256, bytesToHex, hexToBytes } from "@parity/product-sdk-crypto";
2
- import { createLogger } from "@parity/product-sdk-logger";
1
+ /**
2
+ * CID helpers for converting between on-chain hex hashes and CIDs.
3
+ *
4
+ * Upstream `@parity/bulletin-sdk` exposes `calculateCid` (data → CID),
5
+ * `parseCid` (string → CID), `cidFromBytes` (full-encoded → CID), and
6
+ * `cidToBytes` (CID → full-encoded). The helpers here add a thin layer
7
+ * for the `0x`-prefixed hex shape that on-chain `TransactionInfo` uses,
8
+ * so callers don't need to do the digest plumbing themselves.
9
+ *
10
+ * Both helpers default to the chain default (blake2b-256, raw codec).
11
+ * Pass `HashAlgorithm` and `CidCodec` for other configurations
12
+ * (sha2-256, dag-pb, etc.).
13
+ */
3
14
  import { CID } from "multiformats/cid";
4
15
  import * as Digest from "multiformats/hashes/digest";
5
16
 
6
17
  import { BulletinCidError } from "./errors.js";
7
18
 
8
- const log = createLogger("bulletin");
9
-
10
19
  /**
11
20
  * Hash algorithms supported by the Bulletin Chain.
12
21
  *
13
- * Values are multihash codes as defined in the
14
- * {@link https://github.com/multiformats/multicodec multicodec table}.
22
+ * Values are multihash codes from the multicodec table.
15
23
  */
16
24
  export const HashAlgorithm = {
17
- /** BLAKE2b-256 — default for product-sdk and the chain SDK. */
25
+ /** BLAKE2b-256 — chain default. */
18
26
  Blake2b256: 0xb220,
19
- /** SHA2-256 — default for bulletin-deploy. */
27
+ /** SHA2-256. */
20
28
  Sha2_256: 0x12,
21
29
  /** Keccak-256 — Ethereum compatibility. */
22
30
  Keccak256: 0x1b,
23
31
  } as const;
24
-
25
- /** A multihash code supported by the Bulletin Chain. */
26
32
  export type HashAlgorithm = (typeof HashAlgorithm)[keyof typeof HashAlgorithm];
27
33
 
28
34
  /**
29
35
  * CID codecs supported by the Bulletin Chain.
30
- *
31
- * Values are multicodec codes.
32
36
  */
33
37
  export const CidCodec = {
34
38
  /** Raw binary — default for single-chunk data. */
35
39
  Raw: 0x55,
36
- /** DAG-PB — used for multi-chunk manifests / directory structures. */
40
+ /** DAG-PB — used for multi-chunk manifests / IPFS UnixFS. */
37
41
  DagPb: 0x70,
38
42
  /** DAG-CBOR — alternative DAG encoding. */
39
43
  DagCbor: 0x71,
40
44
  } as const;
41
-
42
- /** A multicodec code supported by the Bulletin Chain. */
43
45
  export type CidCodec = (typeof CidCodec)[keyof typeof CidCodec];
44
46
 
45
47
  const SUPPORTED_HASH_CODES = new Set<number>(Object.values(HashAlgorithm));
46
48
  const SUPPORTED_CODEC_CODES = new Set<number>(Object.values(CidCodec));
47
- const EXPECTED_HEX_LENGTH = 66; // "0x" + 64 hex chars = 32 bytes
48
-
49
- /**
50
- * Compute the CIDv1 (blake2b-256, raw codec) for arbitrary data.
51
- * Deterministic: same input always produces the same CID.
52
- */
53
- export function computeCid(data: Uint8Array): string {
54
- const hash = blake2b256(data);
55
- return CID.createV1(CidCodec.Raw, Digest.create(HashAlgorithm.Blake2b256, hash)).toString();
56
- }
57
-
58
- /**
59
- * Extract the content hash digest from a CIDv1 string and return it as a
60
- * `0x`-prefixed hex string — the preimage key format used by the host API.
61
- *
62
- * Accepts CIDv1 with any hash algorithm supported by the Bulletin Chain
63
- * (blake2b-256, sha2-256, keccak-256).
64
- *
65
- * @param cid - CIDv1 base32 string (as produced by {@link computeCid} or {@link hashToCid}).
66
- * @returns `0x`-prefixed hex string of the 32-byte hash digest.
67
- * @throws If the CID is not CIDv1 or uses an unsupported hash algorithm.
68
- */
69
- export function cidToPreimageKey(cid: string): `0x${string}` {
70
- const parsed = CID.parse(cid);
71
- if (parsed.version !== 1) {
72
- throw new BulletinCidError(`Expected CIDv1, got CIDv${parsed.version}`, cid);
73
- }
74
- if (!SUPPORTED_HASH_CODES.has(parsed.multihash.code)) {
75
- throw new BulletinCidError(
76
- `Unsupported hash algorithm 0x${parsed.multihash.code.toString(16)}; ` +
77
- `expected one of: ${[...SUPPORTED_HASH_CODES].map((c) => `0x${c.toString(16)}`).join(", ")}`,
78
- cid,
79
- );
80
- }
81
- return `0x${bytesToHex(parsed.multihash.digest)}`;
82
- }
49
+ const EXPECTED_HEX_LENGTH = 66; // "0x" + 64 hex chars (32-byte digest)
83
50
 
84
51
  /**
85
- * Reconstruct a CIDv1 from a `0x`-prefixed hex hash stored on-chain.
86
- *
87
- * This is the inverse of {@link cidToPreimageKey}: given a 32-byte content hash
88
- * and the CID configuration used when the data was stored, it rebuilds the
89
- * original CIDv1 so you can construct IPFS gateway URLs.
90
- *
91
- * The Bulletin Chain supports multiple hash algorithms and codecs — pass the
92
- * values that match the on-chain `TransactionInfo` to get the correct CID.
93
- * When omitted, defaults match {@link computeCid} (blake2b-256, raw).
94
- *
95
- * @param hexHash - `0x`-prefixed hex string of a 32-byte hash digest
96
- * (66 characters total: `"0x"` + 64 hex chars).
97
- * @param hashCode - Multihash code of the hashing algorithm (default: blake2b-256 `0xb220`).
98
- * Use {@link HashAlgorithm} for the supported values.
99
- * @param codec - Multicodec code of the CID codec (default: raw `0x55`).
100
- * Use {@link CidCodec} for the supported values.
101
- * @returns Base32-lower CIDv1 string.
102
- * @throws If `hexHash` is not exactly 66 characters, or if the hash/codec is unsupported.
52
+ * Reconstruct a CIDv1 from a `0x`-prefixed 32-byte hex hash.
103
53
  *
104
- * @example
105
- * ```ts
106
- * import { hashToCid, HashAlgorithm, CidCodec, gatewayUrl, getGateway } from "@parity/product-sdk-bulletin";
54
+ * Useful when reading on-chain `TransactionInfo.content_hash` and you need
55
+ * the CID to look up content via an IPFS gateway.
107
56
  *
108
- * // Default (blake2b-256, raw) matches computeCid output
109
- * const cid = hashToCid(onChainHash);
110
- *
111
- * // SHA2-256 content stored via bulletin-deploy
112
- * const cid2 = hashToCid(onChainHash, HashAlgorithm.Sha2_256);
113
- *
114
- * // DAG-PB manifest with blake2b-256
115
- * const cid3 = hashToCid(manifestHash, HashAlgorithm.Blake2b256, CidCodec.DagPb);
116
- *
117
- * const url = gatewayUrl(cid, getGateway("paseo"));
118
- * ```
119
- *
120
- * @see {@link cidToPreimageKey} for the reverse direction (CID → hex hash).
121
- * @see {@link computeCid} for computing a CID from raw data.
122
- * @see {@link HashAlgorithm} for supported hash algorithms.
123
- * @see {@link CidCodec} for supported CID codecs.
57
+ * @param hexHash - 66-char `0x`-prefixed hex of a 32-byte digest.
58
+ * @param hashCode - Multihash code (default: blake2b-256).
59
+ * @param codec - Multicodec code (default: raw).
124
60
  */
125
61
  export function hashToCid(
126
62
  hexHash: `0x${string}`,
@@ -133,6 +69,11 @@ export function hashToCid(
133
69
  `got ${hexHash.length} chars`,
134
70
  );
135
71
  }
72
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hexHash)) {
73
+ throw new BulletinCidError(
74
+ `Invalid hash format: expected 0x-prefixed 32-byte hex string, got: ${hexHash}`,
75
+ );
76
+ }
136
77
  if (!SUPPORTED_HASH_CODES.has(hashCode)) {
137
78
  throw new BulletinCidError(
138
79
  `Unsupported hash algorithm 0x${hashCode.toString(16)}; ` +
@@ -145,194 +86,129 @@ export function hashToCid(
145
86
  `expected one of: ${[...SUPPORTED_CODEC_CODES].map((c) => `0x${c.toString(16)}`).join(", ")}`,
146
87
  );
147
88
  }
148
- const digest = hexToBytes(hexHash.slice(2));
149
- const cid = CID.createV1(codec, Digest.create(hashCode, digest)).toString();
150
- log.debug("hashToCid", { hexHash, hashCode, codec, cid });
151
- return cid;
89
+ const digest = hexToBytes(hexHash);
90
+ return CID.createV1(codec, Digest.create(hashCode, digest)).toString();
152
91
  }
153
92
 
154
- if (import.meta.vitest) {
155
- const { describe, test, expect } = import.meta.vitest;
93
+ /**
94
+ * Extract the 32-byte content hash digest from a CIDv1 and return it as a
95
+ * `0x`-prefixed hex string.
96
+ *
97
+ * Useful for matching a CID against on-chain `TransactionInfo.content_hash`.
98
+ */
99
+ export function cidToPreimageKey(cid: string): `0x${string}` {
100
+ let parsed;
101
+ try {
102
+ parsed = CID.parse(cid);
103
+ } catch {
104
+ throw new BulletinCidError(`Invalid CID: ${cid}`, cid);
105
+ }
106
+ if (parsed.version !== 1) {
107
+ throw new BulletinCidError(`Expected CIDv1, got CIDv${parsed.version}`, cid);
108
+ }
109
+ if (!SUPPORTED_HASH_CODES.has(parsed.multihash.code)) {
110
+ throw new BulletinCidError(
111
+ `Unsupported hash algorithm 0x${parsed.multihash.code.toString(16)}; ` +
112
+ `expected one of: ${[...SUPPORTED_HASH_CODES].map((c) => `0x${c.toString(16)}`).join(", ")}`,
113
+ cid,
114
+ );
115
+ }
116
+ return `0x${bytesToHex(parsed.multihash.digest)}` as `0x${string}`;
117
+ }
156
118
 
157
- describe("computeCid", () => {
158
- test("produces known CID for known input", () => {
159
- const data = new TextEncoder().encode("hello bulletin");
160
- const cid = computeCid(data);
161
- expect(cid).toBe(computeCid(new TextEncoder().encode("hello bulletin")));
162
- expect(cid).toMatch(/^b[a-z2-7]+$/);
163
- });
119
+ function hexToBytes(hex: `0x${string}`): Uint8Array {
120
+ const out = new Uint8Array(32);
121
+ for (let i = 0; i < 32; i++) {
122
+ out[i] = Number.parseInt(hex.slice(2 + i * 2, 4 + i * 2), 16);
123
+ }
124
+ return out;
125
+ }
164
126
 
165
- test("deterministic — same input, same output", () => {
166
- const data = new Uint8Array([1, 2, 3, 4, 5]);
167
- expect(computeCid(data)).toBe(computeCid(data));
168
- });
127
+ function bytesToHex(bytes: Uint8Array): string {
128
+ let s = "";
129
+ for (let i = 0; i < bytes.length; i++) {
130
+ s += bytes[i]!.toString(16).padStart(2, "0");
131
+ }
132
+ return s;
133
+ }
169
134
 
170
- test("different inputs produce different CIDs", () => {
171
- const a = computeCid(new Uint8Array([1]));
172
- const b = computeCid(new Uint8Array([2]));
173
- expect(a).not.toBe(b);
174
- });
135
+ if (import.meta.vitest) {
136
+ const { describe, test, expect } = import.meta.vitest;
175
137
 
176
- test("empty input produces valid CID", () => {
177
- const cid = computeCid(new Uint8Array(0));
178
- expect(cid).toMatch(/^b[a-z2-7]+$/);
179
- });
138
+ describe("hashToCid", () => {
139
+ const sampleHex = `0x${"ab".repeat(32)}` as `0x${string}`;
180
140
 
181
- test("matches reference implementation (manual varint)", () => {
182
- const data = new TextEncoder().encode("test");
183
- const cid = computeCid(data);
184
- expect(cid[0]).toBe("b");
141
+ test("produces valid base32-lower CIDv1 (default: blake2b-256, raw)", () => {
142
+ const cid = hashToCid(sampleHex);
143
+ expect(cid).toMatch(/^b[a-z2-7]+$/);
185
144
  const parsed = CID.parse(cid);
186
145
  expect(parsed.version).toBe(1);
187
146
  expect(parsed.code).toBe(CidCodec.Raw);
147
+ expect(parsed.multihash.code).toBe(HashAlgorithm.Blake2b256);
188
148
  });
189
- });
190
149
 
191
- describe("cidToPreimageKey", () => {
192
- test("round-trips with computeCid — returns 0x-prefixed 64-char hex", () => {
193
- const data = new TextEncoder().encode("hello bulletin");
194
- const cid = computeCid(data);
195
- const key = cidToPreimageKey(cid);
196
- expect(key).toMatch(/^0x[0-9a-f]{64}$/);
150
+ test("supports sha2-256", () => {
151
+ const cid = hashToCid(sampleHex, HashAlgorithm.Sha2_256);
152
+ expect(CID.parse(cid).multihash.code).toBe(HashAlgorithm.Sha2_256);
197
153
  });
198
154
 
199
- test("deterministic same CID always yields same key", () => {
200
- const cid = computeCid(new Uint8Array([1, 2, 3]));
201
- expect(cidToPreimageKey(cid)).toBe(cidToPreimageKey(cid));
155
+ test("supports dag-pb codec", () => {
156
+ const cid = hashToCid(sampleHex, HashAlgorithm.Blake2b256, CidCodec.DagPb);
157
+ expect(CID.parse(cid).code).toBe(CidCodec.DagPb);
202
158
  });
203
159
 
204
- test("matches raw blake2b-256 hash", () => {
205
- const data = new TextEncoder().encode("test");
206
- const cid = computeCid(data);
207
- const key = cidToPreimageKey(cid);
208
- const hash = blake2b256(data);
209
- const expected = `0x${bytesToHex(hash)}`;
210
- expect(key).toBe(expected);
160
+ test("throws on short hex", () => {
161
+ expect(() => hashToCid("0xabcd" as `0x${string}`)).toThrow(BulletinCidError);
211
162
  });
212
163
 
213
- test("accepts CIDv1 with sha2-256", () => {
214
- const hash = new Uint8Array(32).fill(0xcd);
215
- const cidV1 = CID.createV1(CidCodec.Raw, Digest.create(HashAlgorithm.Sha2_256, hash));
216
- const key = cidToPreimageKey(cidV1.toString());
217
- expect(key).toMatch(/^0x[0-9a-f]{64}$/);
218
- expect(key).toBe(`0x${bytesToHex(hash)}`);
164
+ test("throws on long hex", () => {
165
+ const tooLong = `0x${"aa".repeat(33)}` as `0x${string}`;
166
+ expect(() => hashToCid(tooLong)).toThrow(BulletinCidError);
219
167
  });
220
168
 
221
- test("accepts CIDv1 with keccak-256", () => {
222
- const hash = new Uint8Array(32).fill(0xef);
223
- const cidV1 = CID.createV1(CidCodec.Raw, Digest.create(HashAlgorithm.Keccak256, hash));
224
- const key = cidToPreimageKey(cidV1.toString());
225
- expect(key).toBe(`0x${bytesToHex(hash)}`);
169
+ test("throws on non-hex characters", () => {
170
+ const bad = `0x${"zz".repeat(32)}` as `0x${string}`;
171
+ expect(() => hashToCid(bad)).toThrow(BulletinCidError);
226
172
  });
227
173
 
228
- test("throws BulletinCidError for CIDv0 input", () => {
229
- const hash = new Uint8Array(32).fill(0xab);
230
- const cidV0 = CID.create(0, 0x70, Digest.create(HashAlgorithm.Sha2_256, hash));
231
- expect(() => cidToPreimageKey(cidV0.toString())).toThrow(BulletinCidError);
174
+ test("throws on unsupported hash algorithm", () => {
175
+ expect(() => hashToCid(sampleHex, 0x99 as HashAlgorithm)).toThrow(BulletinCidError);
232
176
  });
233
177
 
234
- test("throws BulletinCidError for CIDv1 with unsupported hash algorithm", () => {
235
- const unsupportedCode = 0x99;
236
- const hash = new Uint8Array(32).fill(0xab);
237
- const cidV1 = CID.createV1(CidCodec.Raw, Digest.create(unsupportedCode, hash));
238
- expect(() => cidToPreimageKey(cidV1.toString())).toThrow(BulletinCidError);
178
+ test("throws on unsupported codec", () => {
179
+ expect(() => hashToCid(sampleHex, HashAlgorithm.Blake2b256, 0x99 as CidCodec)).toThrow(
180
+ BulletinCidError,
181
+ );
239
182
  });
240
183
  });
241
184
 
242
- describe("hashToCid", () => {
243
- test("round-trips with cidToPreimageKey — hex → CID → hex", () => {
244
- const data = new TextEncoder().encode("hello bulletin");
245
- const originalCid = computeCid(data);
246
- const hex = cidToPreimageKey(originalCid);
247
- const reconstructed = hashToCid(hex);
248
- expect(reconstructed).toBe(originalCid);
249
- });
250
-
251
- test("full cycle: data → CID → hex → CID", () => {
252
- const data = new Uint8Array([10, 20, 30, 40, 50]);
253
- const cid1 = computeCid(data);
254
- const hex = cidToPreimageKey(cid1);
255
- const cid2 = hashToCid(hex);
256
- expect(cid2).toBe(cid1);
257
- });
258
-
259
- test("deterministic — same hex always yields same CID", () => {
260
- const hex = cidToPreimageKey(computeCid(new Uint8Array([1, 2, 3])));
261
- expect(hashToCid(hex)).toBe(hashToCid(hex));
262
- });
263
-
264
- test("produces valid base32-lower CIDv1 (default: blake2b-256, raw)", () => {
265
- const hex = cidToPreimageKey(computeCid(new TextEncoder().encode("test")));
266
- const cid = hashToCid(hex);
267
- expect(cid).toMatch(/^b[a-z2-7]+$/);
268
- const parsed = CID.parse(cid);
269
- expect(parsed.version).toBe(1);
270
- expect(parsed.code).toBe(CidCodec.Raw);
271
- expect(parsed.multihash.code).toBe(HashAlgorithm.Blake2b256);
272
- });
273
-
274
- test("sha2-256 produces different CID from blake2b-256 for same hash", () => {
275
- const hex = `0x${"ab".repeat(32)}` as `0x${string}`;
276
- const blake = hashToCid(hex, HashAlgorithm.Blake2b256);
277
- const sha = hashToCid(hex, HashAlgorithm.Sha2_256);
278
- expect(blake).not.toBe(sha);
279
- // Both should be valid CIDv1
280
- expect(CID.parse(blake).version).toBe(1);
281
- expect(CID.parse(sha).version).toBe(1);
282
- });
283
-
284
- test("sha2-256 round-trips through cidToPreimageKey", () => {
185
+ describe("cidToPreimageKey", () => {
186
+ test("round-trip with hashToCid", () => {
285
187
  const hex = `0x${"cd".repeat(32)}` as `0x${string}`;
286
- const cid = hashToCid(hex, HashAlgorithm.Sha2_256);
287
- const extracted = cidToPreimageKey(cid);
288
- expect(extracted).toBe(hex);
188
+ const cid = hashToCid(hex);
189
+ expect(cidToPreimageKey(cid)).toBe(hex);
289
190
  });
290
191
 
291
- test("keccak-256 round-trips through cidToPreimageKey", () => {
192
+ test("round-trip with sha2-256", () => {
292
193
  const hex = `0x${"ef".repeat(32)}` as `0x${string}`;
293
- const cid = hashToCid(hex, HashAlgorithm.Keccak256);
294
- const extracted = cidToPreimageKey(cid);
295
- expect(extracted).toBe(hex);
296
- });
297
-
298
- test("dag-pb codec produces different CID from raw for same hash", () => {
299
- const hex = `0x${"ab".repeat(32)}` as `0x${string}`;
300
- const rawCid = hashToCid(hex, HashAlgorithm.Blake2b256, CidCodec.Raw);
301
- const dagPbCid = hashToCid(hex, HashAlgorithm.Blake2b256, CidCodec.DagPb);
302
- expect(rawCid).not.toBe(dagPbCid);
303
- expect(CID.parse(dagPbCid).code).toBe(CidCodec.DagPb);
304
- });
305
-
306
- test("dag-cbor codec works", () => {
307
- const hex = `0x${"ab".repeat(32)}` as `0x${string}`;
308
- const cid = hashToCid(hex, HashAlgorithm.Blake2b256, CidCodec.DagCbor);
309
- expect(CID.parse(cid).code).toBe(CidCodec.DagCbor);
310
- });
311
-
312
- test("throws BulletinCidError for hex that is too short", () => {
313
- expect(() => hashToCid("0xabcd" as `0x${string}`)).toThrow(BulletinCidError);
314
- });
315
-
316
- test("throws BulletinCidError for hex that is too long", () => {
317
- const tooLong = `0x${"aa".repeat(33)}` as `0x${string}`;
318
- expect(() => hashToCid(tooLong)).toThrow(BulletinCidError);
194
+ const cid = hashToCid(hex, HashAlgorithm.Sha2_256);
195
+ expect(cidToPreimageKey(cid)).toBe(hex);
319
196
  });
320
197
 
321
- test("throws for non-hex characters", () => {
322
- const bad = `0x${"zz".repeat(32)}` as `0x${string}`;
323
- expect(() => hashToCid(bad)).toThrow();
198
+ test("throws on invalid CID string", () => {
199
+ expect(() => cidToPreimageKey("not-a-cid")).toThrow(BulletinCidError);
324
200
  });
325
201
 
326
- test("throws BulletinCidError for unsupported hash algorithm", () => {
327
- const hex = `0x${"ab".repeat(32)}` as `0x${string}`;
328
- expect(() => hashToCid(hex, 0x99 as HashAlgorithm)).toThrow(BulletinCidError);
202
+ test("throws on CIDv0 input", () => {
203
+ const hash = new Uint8Array(32).fill(0xab);
204
+ const cidV0 = CID.create(0, 0x70, Digest.create(HashAlgorithm.Sha2_256, hash));
205
+ expect(() => cidToPreimageKey(cidV0.toString())).toThrow(BulletinCidError);
329
206
  });
330
207
 
331
- test("throws BulletinCidError for unsupported codec", () => {
332
- const hex = `0x${"ab".repeat(32)}` as `0x${string}`;
333
- expect(() => hashToCid(hex, HashAlgorithm.Blake2b256, 0x99 as CidCodec)).toThrow(
334
- BulletinCidError,
335
- );
208
+ test("throws on unsupported hash algorithm", () => {
209
+ const hash = new Uint8Array(32).fill(0xab);
210
+ const cidV1 = CID.createV1(CidCodec.Raw, Digest.create(0x99, hash));
211
+ expect(() => cidToPreimageKey(cidV1.toString())).toThrow(BulletinCidError);
336
212
  });
337
213
  });
338
214
  }