@andamio/core 0.1.1 → 0.3.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.
@@ -69,37 +69,58 @@ declare function isValidSltHash(hash: string): boolean;
69
69
  * Computes the task token name (hash) from task data.
70
70
  * This hash is used as the task_hash on-chain (content-addressed identifier).
71
71
  *
72
- * The algorithm matches the on-chain Plutus validator serialization.
72
+ * The algorithm matches the on-chain Aiken/Haskell hash_project_data function:
73
+ * - Serialize task data as Plutus Data (CBOR with tag 121 for Constructor 0)
74
+ * - Use indefinite-length arrays for constructor fields
75
+ * - Hash with Blake2b-256
73
76
  *
74
77
  * @module @andamio/core/hashing
75
78
  */
76
79
  /**
77
- * Native asset in ListValue format: [policyId.tokenName, quantity]
80
+ * Native asset in Cardano format: [policyId, tokenName, quantity]
81
+ *
82
+ * @example
83
+ * ```typescript
84
+ * const asset: NativeAsset = [
85
+ * "abc123def456...".repeat(4), // 56 hex chars (28 bytes) - policy ID
86
+ * "746f6b656e", // hex-encoded token name
87
+ * 1000n // quantity as bigint
88
+ * ];
89
+ * ```
78
90
  */
79
- type NativeAsset = [string, number];
91
+ type NativeAsset = [
92
+ policyId: string,
93
+ tokenName: string,
94
+ quantity: bigint
95
+ ];
80
96
  /**
81
- * Task data structure matching the Atlas TX API ManageTasksTxRequest
97
+ * Task data structure matching the Aiken ProjectData type.
82
98
  *
83
- * Fields must be arranged in this specific order for hashing:
84
- * 1. project_content (string, max 140 chars)
85
- * 2. expiration_time (number, Unix timestamp in milliseconds)
86
- * 3. lovelace_amount (number)
87
- * 4. native_assets (array of [asset_class, quantity] tuples)
99
+ * Serialized as Plutus Data Constructor 0 (CBOR tag 121) with fields:
100
+ * 1. project_content (ByteArray - UTF-8 encoded, NFC normalized)
101
+ * 2. deadline (Int - milliseconds)
102
+ * 3. lovelace_am (Int - micro-ADA)
103
+ * 4. tokens (List<FlatValue> - native assets)
88
104
  */
89
105
  interface TaskData {
106
+ /** Task description (max 140 characters) */
90
107
  project_content: string;
91
- expiration_time: number;
92
- lovelace_amount: number;
93
- native_assets: NativeAsset[];
108
+ /** Unix timestamp in milliseconds */
109
+ expiration_time: bigint;
110
+ /** Lovelace amount (micro-ADA) */
111
+ lovelace_amount: bigint;
112
+ /** Native assets attached to task */
113
+ native_assets: readonly NativeAsset[];
94
114
  }
95
115
  /**
96
116
  * Compute the task hash (token name / task_hash) from task data.
97
117
  *
98
- * This produces the same hash as the on-chain Plutus validator, allowing
99
- * clients to pre-compute or verify task hashes.
118
+ * This produces the same hash as the on-chain Aiken hash_project_data function,
119
+ * allowing clients to pre-compute or verify task hashes.
100
120
  *
101
121
  * @param task - Task data object
102
122
  * @returns 64-character hex string (256-bit Blake2b hash)
123
+ * @throws Error if task data validation fails
103
124
  *
104
125
  * @example
105
126
  * ```typescript
@@ -107,8 +128,8 @@ interface TaskData {
107
128
  *
108
129
  * const task = {
109
130
  * project_content: "Open Task #1",
110
- * expiration_time: 1769027280000,
111
- * lovelace_amount: 15000000,
131
+ * expiration_time: 1769027280000n,
132
+ * lovelace_amount: 15000000n,
112
133
  * native_assets: []
113
134
  * };
114
135
  *
@@ -136,9 +157,9 @@ declare function isValidTaskHash(hash: string): boolean;
136
157
  * Useful for comparing against on-chain data.
137
158
  *
138
159
  * @param task - Task data object
139
- * @returns Hex string of the CBOR-encoded data (before hashing)
160
+ * @returns Hex string of the CBOR-encoded Plutus Data (before hashing)
140
161
  */
141
- declare function debugTaskCBOR(task: TaskData): string;
162
+ declare function debugTaskBytes(task: TaskData): string;
142
163
 
143
164
  /**
144
165
  * Commitment Hash Utility
@@ -273,4 +294,4 @@ declare const verifyAssignmentInfoHash: typeof verifyCommitmentHash;
273
294
  */
274
295
  declare const isValidAssignmentInfoHash: typeof isValidCommitmentHash;
275
296
 
276
- export { type EvidenceVerificationResult, type TaskData, type TiptapDoc, type TiptapMark, type TiptapNode, computeAssignmentInfoHash, computeCommitmentHash, computeSltHash, computeSltHashDefinite, computeTaskHash, debugTaskCBOR, isValidAssignmentInfoHash, isValidCommitmentHash, isValidSltHash, isValidTaskHash, normalizeForHashing, verifyAssignmentInfoHash, verifyCommitmentHash, verifyEvidenceDetailed, verifySltHash, verifyTaskHash };
297
+ export { type EvidenceVerificationResult, type NativeAsset, type TaskData, type TiptapDoc, type TiptapMark, type TiptapNode, computeAssignmentInfoHash, computeCommitmentHash, computeSltHash, computeSltHashDefinite, computeTaskHash, debugTaskBytes, isValidAssignmentInfoHash, isValidCommitmentHash, isValidSltHash, isValidTaskHash, normalizeForHashing, verifyAssignmentInfoHash, verifyCommitmentHash, verifyEvidenceDetailed, verifySltHash, verifyTaskHash };
@@ -79,10 +79,10 @@ function concatUint8Arrays(arrays) {
79
79
  }
80
80
  return result;
81
81
  }
82
- var PLUTUS_CHUNK_SIZE2 = 64;
83
82
  function computeTaskHash(task) {
84
- const cborData = encodeTaskAsPlutusData(task);
85
- return blake__default.default.blake2bHex(cborData, void 0, 32);
83
+ validateTaskData(task);
84
+ const bytes = encodeTaskAsPlutusData(task);
85
+ return blake__default.default.blake2bHex(bytes, void 0, 32);
86
86
  }
87
87
  function verifyTaskHash(task, expectedHash) {
88
88
  const computedHash = computeTaskHash(task);
@@ -94,108 +94,148 @@ function isValidTaskHash(hash) {
94
94
  }
95
95
  return /^[0-9a-fA-F]{64}$/.test(hash);
96
96
  }
97
- function debugTaskCBOR(task) {
98
- const cborData = encodeTaskAsPlutusData(task);
99
- return uint8ArrayToHex(cborData);
97
+ function debugTaskBytes(task) {
98
+ validateTaskData(task);
99
+ const bytes = encodeTaskAsPlutusData(task);
100
+ return uint8ArrayToHex(bytes);
100
101
  }
101
102
  function encodeTaskAsPlutusData(task) {
102
- const chunks = [];
103
- chunks.push(new Uint8Array([216, 121]));
104
- chunks.push(new Uint8Array([159]));
105
- chunks.push(encodePlutusBuiltinByteString2(new TextEncoder().encode(task.project_content)));
106
- chunks.push(encodePlutusInteger(task.expiration_time));
107
- chunks.push(encodePlutusInteger(task.lovelace_amount));
108
- chunks.push(encodeNativeAssets(task.native_assets));
109
- chunks.push(new Uint8Array([255]));
110
- return concatUint8Arrays2(chunks);
103
+ const normalizedContent = task.project_content.normalize("NFC");
104
+ const contentBytes = new TextEncoder().encode(normalizedContent);
105
+ return concatUint8Arrays2([
106
+ // Tag 121 (Plutus Data Constructor 0) + indefinite array start
107
+ new Uint8Array([216, 121, 159]),
108
+ // Field 1: project_content (ByteArray)
109
+ encodeCborBytes(contentBytes),
110
+ // Field 2: deadline (Int)
111
+ encodeCborUint(task.expiration_time),
112
+ // Field 3: lovelace_am (Int)
113
+ encodeCborUint(task.lovelace_amount),
114
+ // Field 4: tokens (List<FlatValue>)
115
+ encodeTokensList(task.native_assets),
116
+ // Break (end of indefinite array)
117
+ new Uint8Array([255])
118
+ ]);
111
119
  }
112
- function encodeNativeAssets(assets) {
120
+ function encodeTokensList(assets) {
113
121
  if (assets.length === 0) {
114
122
  return new Uint8Array([128]);
115
123
  }
116
- const chunks = [];
117
- chunks.push(new Uint8Array([159]));
118
- for (const [assetClass, quantity] of assets) {
119
- chunks.push(new Uint8Array([130]));
120
- chunks.push(encodePlutusBuiltinByteString2(new TextEncoder().encode(assetClass)));
121
- chunks.push(encodePlutusInteger(quantity));
124
+ const parts = [new Uint8Array([159])];
125
+ for (const [policyId, tokenName, quantity] of assets) {
126
+ parts.push(new Uint8Array([216, 121, 159]));
127
+ parts.push(encodeCborBytes(hexToBytes(policyId)));
128
+ parts.push(encodeCborBytes(hexToBytes(tokenName)));
129
+ parts.push(encodeCborUint(quantity));
130
+ parts.push(new Uint8Array([255]));
122
131
  }
123
- chunks.push(new Uint8Array([255]));
124
- return concatUint8Arrays2(chunks);
132
+ parts.push(new Uint8Array([255]));
133
+ return concatUint8Arrays2(parts);
125
134
  }
126
- function encodePlutusBuiltinByteString2(buffer) {
127
- if (buffer.length <= PLUTUS_CHUNK_SIZE2) {
128
- return encodeCBORByteString2(buffer);
135
+ var MAX_UINT64 = 18446744073709551615n;
136
+ function encodeCborUint(n) {
137
+ if (n < 0n) {
138
+ throw new Error("Negative integers not supported");
129
139
  }
130
- const chunks = [];
131
- chunks.push(new Uint8Array([95]));
132
- for (let i = 0; i < buffer.length; i += PLUTUS_CHUNK_SIZE2) {
133
- const chunk = buffer.subarray(i, Math.min(i + PLUTUS_CHUNK_SIZE2, buffer.length));
134
- chunks.push(encodeCBORByteString2(chunk));
140
+ if (n > MAX_UINT64) {
141
+ throw new Error(
142
+ `Integer exceeds maximum CBOR uint64 value (got ${n}, max ${MAX_UINT64})`
143
+ );
144
+ }
145
+ if (n < 24n) {
146
+ return new Uint8Array([Number(n)]);
147
+ } else if (n < 256n) {
148
+ return new Uint8Array([24, Number(n)]);
149
+ } else if (n < 65536n) {
150
+ return new Uint8Array([25, Number(n >> 8n) & 255, Number(n) & 255]);
151
+ } else if (n < 4294967296n) {
152
+ return new Uint8Array([
153
+ 26,
154
+ Number(n >> 24n & 0xffn),
155
+ Number(n >> 16n & 0xffn),
156
+ Number(n >> 8n & 0xffn),
157
+ Number(n & 0xffn)
158
+ ]);
159
+ } else {
160
+ return new Uint8Array([
161
+ 27,
162
+ Number(n >> 56n & 0xffn),
163
+ Number(n >> 48n & 0xffn),
164
+ Number(n >> 40n & 0xffn),
165
+ Number(n >> 32n & 0xffn),
166
+ Number(n >> 24n & 0xffn),
167
+ Number(n >> 16n & 0xffn),
168
+ Number(n >> 8n & 0xffn),
169
+ Number(n & 0xffn)
170
+ ]);
135
171
  }
136
- chunks.push(new Uint8Array([255]));
137
- return concatUint8Arrays2(chunks);
138
172
  }
139
- function encodePlutusInteger(n) {
140
- if (n >= 0) {
141
- if (n <= 23) {
142
- return new Uint8Array([n]);
143
- } else if (n <= 255) {
144
- return new Uint8Array([24, n]);
145
- } else if (n <= 65535) {
146
- return new Uint8Array([25, n >> 8, n & 255]);
147
- } else if (n <= 4294967295) {
148
- return new Uint8Array([26, n >> 24 & 255, n >> 16 & 255, n >> 8 & 255, n & 255]);
149
- } else {
150
- const buf = new Uint8Array(9);
151
- buf[0] = 27;
152
- const big = BigInt(n);
153
- const view = new DataView(buf.buffer);
154
- view.setBigUint64(1, big, false);
155
- return buf;
156
- }
173
+ function encodeCborBytes(bytes) {
174
+ const len = bytes.length;
175
+ let header;
176
+ if (len < 24) {
177
+ header = new Uint8Array([64 + len]);
178
+ } else if (len < 256) {
179
+ header = new Uint8Array([88, len]);
180
+ } else if (len < 65536) {
181
+ header = new Uint8Array([89, len >> 8 & 255, len & 255]);
157
182
  } else {
158
- const absVal = -1 - n;
159
- if (absVal <= 23) {
160
- return new Uint8Array([32 + absVal]);
161
- } else if (absVal <= 255) {
162
- return new Uint8Array([56, absVal]);
163
- } else if (absVal <= 65535) {
164
- return new Uint8Array([57, absVal >> 8, absVal & 255]);
165
- } else if (absVal <= 4294967295) {
166
- return new Uint8Array([58, absVal >> 24 & 255, absVal >> 16 & 255, absVal >> 8 & 255, absVal & 255]);
167
- } else {
168
- const buf = new Uint8Array(9);
169
- buf[0] = 59;
170
- const big = BigInt(absVal);
171
- const view = new DataView(buf.buffer);
172
- view.setBigUint64(1, big, false);
173
- return buf;
183
+ throw new Error("Byte string too long for CBOR encoding");
184
+ }
185
+ return concatUint8Arrays2([header, bytes]);
186
+ }
187
+ function validateTaskData(task) {
188
+ if (task.project_content.length > 140) {
189
+ throw new Error(
190
+ `project_content exceeds 140 characters (got ${task.project_content.length})`
191
+ );
192
+ }
193
+ if (task.expiration_time < 0n) {
194
+ throw new Error("expiration_time must be non-negative");
195
+ }
196
+ if (task.lovelace_amount < 0n) {
197
+ throw new Error("lovelace_amount must be non-negative");
198
+ }
199
+ for (const [policyId, tokenName, quantity] of task.native_assets) {
200
+ if (policyId.length !== 56) {
201
+ throw new Error(
202
+ `policyId must be 56 hex chars (got ${policyId.length})`
203
+ );
204
+ }
205
+ if (!/^[0-9a-fA-F]*$/.test(policyId)) {
206
+ throw new Error("policyId contains invalid hex characters");
207
+ }
208
+ if (tokenName.length > 64 || tokenName.length % 2 !== 0) {
209
+ throw new Error(
210
+ `tokenName must be 0-64 hex chars with even length (got ${tokenName.length})`
211
+ );
212
+ }
213
+ if (tokenName.length > 0 && !/^[0-9a-fA-F]*$/.test(tokenName)) {
214
+ throw new Error("tokenName contains invalid hex characters");
215
+ }
216
+ if (quantity < 0n) {
217
+ throw new Error("asset quantity must be non-negative");
174
218
  }
175
219
  }
176
220
  }
177
- function encodeCBORByteString2(buffer) {
178
- const len = buffer.length;
179
- if (len <= 23) {
180
- const result = new Uint8Array(1 + len);
181
- result[0] = 64 + len;
182
- result.set(buffer, 1);
183
- return result;
184
- } else if (len <= 255) {
185
- const result = new Uint8Array(2 + len);
186
- result[0] = 88;
187
- result[1] = len;
188
- result.set(buffer, 2);
189
- return result;
190
- } else if (len <= 65535) {
191
- const result = new Uint8Array(3 + len);
192
- result[0] = 89;
193
- result[1] = len >> 8;
194
- result[2] = len & 255;
195
- result.set(buffer, 3);
196
- return result;
221
+ function hexToBytes(hex) {
222
+ if (hex.length === 0) {
223
+ return new Uint8Array([]);
197
224
  }
198
- throw new Error("Byte string too long for CBOR encoding");
225
+ if (hex.length % 2 !== 0) {
226
+ throw new Error(`Invalid hex string: odd length (${hex.length})`);
227
+ }
228
+ const bytes = new Uint8Array(hex.length / 2);
229
+ for (let i = 0; i < bytes.length; i++) {
230
+ const byte = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
231
+ if (Number.isNaN(byte)) {
232
+ throw new Error(
233
+ `Invalid hex character at position ${i * 2}: "${hex.slice(i * 2, i * 2 + 2)}"`
234
+ );
235
+ }
236
+ bytes[i] = byte;
237
+ }
238
+ return bytes;
199
239
  }
200
240
  function concatUint8Arrays2(arrays) {
201
241
  const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
@@ -282,7 +322,7 @@ exports.computeCommitmentHash = computeCommitmentHash;
282
322
  exports.computeSltHash = computeSltHash;
283
323
  exports.computeSltHashDefinite = computeSltHashDefinite;
284
324
  exports.computeTaskHash = computeTaskHash;
285
- exports.debugTaskCBOR = debugTaskCBOR;
325
+ exports.debugTaskBytes = debugTaskBytes;
286
326
  exports.isValidAssignmentInfoHash = isValidAssignmentInfoHash;
287
327
  exports.isValidCommitmentHash = isValidCommitmentHash;
288
328
  exports.isValidSltHash = isValidSltHash;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/utils/hashing/slt-hash.ts","../../../src/utils/hashing/task-hash.ts","../../../src/utils/hashing/commitment-hash.ts"],"names":["blake","PLUTUS_CHUNK_SIZE","encodePlutusBuiltinByteString","concatUint8Arrays","encodeCBORByteString"],"mappings":";;;;;;;;;AAyBA,IAAM,iBAAA,GAAoB,EAAA;AA0BnB,SAAS,eAAe,IAAA,EAAwB;AACrD,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,CAAI,CAAC,GAAA,KAAQ,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AAChE,EAAA,MAAM,QAAA,GAAW,oBAAoB,QAAQ,CAAA;AAC7C,EAAA,OAAOA,sBAAA,CAAM,UAAA,CAAW,QAAA,EAAU,MAAA,EAAW,EAAE,CAAA;AACjD;AAKO,IAAM,sBAAA,GAAyB;AAS/B,SAAS,aAAA,CAAc,MAAgB,YAAA,EAA+B;AAC3E,EAAA,MAAM,YAAA,GAAe,eAAe,IAAI,CAAA;AACxC,EAAA,OAAO,YAAA,CAAa,WAAA,EAAY,KAAM,YAAA,CAAa,WAAA,EAAY;AACjE;AAUO,SAAS,eAAe,IAAA,EAAuB;AACpD,EAAA,IAAI,IAAA,CAAK,WAAW,EAAA,EAAI;AACtB,IAAA,OAAO,KAAA;AAAA,EACT;AACA,EAAA,OAAO,mBAAA,CAAoB,KAAK,IAAI,CAAA;AACtC;AAaA,SAAS,oBAAoB,KAAA,EAAiC;AAC5D,EAAA,MAAM,SAAuB,EAAC;AAG9B,EAAA,MAAA,CAAO,KAAK,IAAI,UAAA,CAAW,CAAC,GAAI,CAAC,CAAC,CAAA;AAGlC,EAAA,KAAA,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A,YAAA,EAAc,YAAY,WAAA,EAAY;AAAA,IACtC,OAAA,EAAS,UACL,sCAAA,GACA;AAAA,GACN;AACF;AASO,IAAM,yBAAA,GAA4B;AAKlC,IAAM,wBAAA,GAA2B;AAKjC,IAAM,yBAAA,GAA4B","file":"index.js","sourcesContent":["/**\n * SLT Hash Utility\n *\n * Computes the module token name (hash) from a list of Student Learning Targets (SLTs).\n * This hash is used as the token name when minting module tokens on-chain.\n *\n * The algorithm matches the on-chain Plutus validator:\n * ```haskell\n * sltsToBbs MintModuleV2{slts} = blake2b_256 $ serialiseData $ toBuiltinData $ map stringToBuiltinByteString slts\n * ```\n *\n * Serialization format:\n * 1. Convert each SLT string to UTF-8 bytes\n * 2. Encode as CBOR indefinite-length array of byte strings\n * 3. Hash with Blake2b-256 (32 bytes / 256 bits)\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Plutus chunk size for byte strings.\n * Strings longer than this are encoded as indefinite-length chunked byte strings.\n */\nconst PLUTUS_CHUNK_SIZE = 64;\n\n/**\n * Compute the module hash matching Plutus on-chain encoding.\n *\n * Plutus's `stringToBuiltinByteString` chunks byte strings at 64 bytes.\n * This function replicates that behavior:\n * - Strings <= 64 bytes: encoded as regular CBOR byte strings\n * - Strings > 64 bytes: encoded as indefinite-length chunked byte strings\n *\n * @param slts - Array of Student Learning Target strings\n * @returns 64-character hex string (256-bit Blake2b hash)\n *\n * @example\n * ```typescript\n * import { computeSltHash } from \"@andamio/core/hashing\";\n *\n * const slts = [\n * \"I can mint an access token.\",\n * \"I can complete an assignment to earn a credential.\"\n * ];\n *\n * const moduleHash = computeSltHash(slts);\n * // Returns: \"8dcbe1b925d87e6c547bbd8071c23a712db4c32751454b0948f8c846e9246b5c\"\n * ```\n */\nexport function computeSltHash(slts: string[]): string {\n const sltBytes = slts.map((slt) => new TextEncoder().encode(slt));\n const cborData = encodeAsPlutusArray(sltBytes);\n return blake.blake2bHex(cborData, undefined, 32);\n}\n\n/**\n * @deprecated Use `computeSltHash` instead. This alias is kept for backwards compatibility.\n */\nexport const computeSltHashDefinite = computeSltHash;\n\n/**\n * Verify that a given hash matches the computed hash for SLTs.\n *\n * @param slts - Array of Student Learning Target strings\n * @param expectedHash - The hash to verify (64-character hex string)\n * @returns true if the computed hash matches the expected hash\n */\nexport function verifySltHash(slts: string[], expectedHash: string): boolean {\n const computedHash = computeSltHash(slts);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validate that a string is a valid SLT hash format.\n *\n * SLT hashes are 64-character hexadecimal strings (256-bit Blake2b hash).\n *\n * @param hash - String to validate\n * @returns true if the string is a valid SLT hash format\n */\nexport function isValidSltHash(hash: string): boolean {\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n// =============================================================================\n// Plutus-Compatible Encoding (Internal)\n// =============================================================================\n\n/**\n * Encode an array of byte buffers matching Plutus serialization.\n *\n * Uses indefinite-length array with chunked byte strings for long values.\n *\n * @internal\n */\nfunction encodeAsPlutusArray(items: Uint8Array[]): Uint8Array {\n const chunks: Uint8Array[] = [];\n\n // Start indefinite array\n chunks.push(new Uint8Array([0x9f]));\n\n // Encode each item (with chunking for long strings)\n for (const item of items) {\n chunks.push(encodePlutusBuiltinByteString(item));\n }\n\n // End indefinite array\n chunks.push(new Uint8Array([0xff]));\n\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a byte buffer matching Plutus's stringToBuiltinByteString.\n *\n * - Strings <= 64 bytes: regular CBOR byte string\n * - Strings > 64 bytes: indefinite-length chunked byte string (64-byte chunks)\n *\n * @internal\n */\nfunction encodePlutusBuiltinByteString(buffer: Uint8Array): Uint8Array {\n if (buffer.length <= PLUTUS_CHUNK_SIZE) {\n // Short string: encode normally\n return encodeCBORByteString(buffer);\n }\n\n // Long string: use indefinite-length chunked encoding\n const chunks: Uint8Array[] = [];\n chunks.push(new Uint8Array([0x5f])); // Start indefinite byte string\n\n for (let i = 0; i < buffer.length; i += PLUTUS_CHUNK_SIZE) {\n const chunk = buffer.subarray(i, Math.min(i + PLUTUS_CHUNK_SIZE, buffer.length));\n chunks.push(encodeCBORByteString(chunk));\n }\n\n chunks.push(new Uint8Array([0xff])); // Break\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a byte buffer as a CBOR byte string (definite length).\n *\n * @internal\n */\nfunction encodeCBORByteString(buffer: Uint8Array): Uint8Array {\n const len = buffer.length;\n\n // CBOR byte string encoding (major type 2 = 0x40):\n // - 0-23 bytes: length inline (0x40 + len)\n // - 24-255 bytes: 0x58 + 1-byte length\n // - 256-65535 bytes: 0x59 + 2-byte length (big-endian)\n if (len <= 23) {\n const result = new Uint8Array(1 + len);\n result[0] = 0x40 + len;\n result.set(buffer, 1);\n return result;\n } else if (len <= 255) {\n const result = new Uint8Array(2 + len);\n result[0] = 0x58;\n result[1] = len;\n result.set(buffer, 2);\n return result;\n } else if (len <= 65535) {\n const result = new Uint8Array(3 + len);\n result[0] = 0x59;\n result[1] = len >> 8;\n result[2] = len & 0xff;\n result.set(buffer, 3);\n return result;\n }\n throw new Error(\"Byte string too long for CBOR encoding\");\n}\n\n/**\n * Concatenate multiple Uint8Arrays into one\n *\n * @internal\n */\nfunction concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n","/**\n * Task Hash Utility\n *\n * Computes the task token name (hash) from task data.\n * This hash is used as the task_hash on-chain (content-addressed identifier).\n *\n * The algorithm matches the on-chain Plutus validator serialization.\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Native asset in ListValue format: [policyId.tokenName, quantity]\n */\ntype NativeAsset = [string, number];\n\n/**\n * Task data structure matching the Atlas TX API ManageTasksTxRequest\n *\n * Fields must be arranged in this specific order for hashing:\n * 1. project_content (string, max 140 chars)\n * 2. expiration_time (number, Unix timestamp in milliseconds)\n * 3. lovelace_amount (number)\n * 4. native_assets (array of [asset_class, quantity] tuples)\n */\nexport interface TaskData {\n project_content: string;\n expiration_time: number;\n lovelace_amount: number;\n native_assets: NativeAsset[];\n}\n\n/**\n * Plutus chunk size for byte strings.\n */\nconst PLUTUS_CHUNK_SIZE = 64;\n\n/**\n * Compute the task hash (token name / task_hash) from task data.\n *\n * This produces the same hash as the on-chain Plutus validator, allowing\n * clients to pre-compute or verify task hashes.\n *\n * @param task - Task data object\n * @returns 64-character hex string (256-bit Blake2b hash)\n *\n * @example\n * ```typescript\n * import { computeTaskHash } from \"@andamio/core/hashing\";\n *\n * const task = {\n * project_content: \"Open Task #1\",\n * expiration_time: 1769027280000,\n * lovelace_amount: 15000000,\n * native_assets: []\n * };\n *\n * const taskHash = computeTaskHash(task);\n * // Returns the on-chain task_hash\n * ```\n */\nexport function computeTaskHash(task: TaskData): string {\n // Serialize task data matching Plutus format\n const cborData = encodeTaskAsPlutusData(task);\n\n // Hash with Blake2b-256\n return blake.blake2bHex(cborData, undefined, 32);\n}\n\n/**\n * Verify that a given hash matches the computed hash for a task.\n *\n * @param task - Task data object\n * @param expectedHash - The hash to verify (64-character hex string)\n * @returns true if the computed hash matches the expected hash\n */\nexport function verifyTaskHash(task: TaskData, expectedHash: string): boolean {\n const computedHash = computeTaskHash(task);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validate that a string is a valid task hash format.\n *\n * Task hashes are 64-character hexadecimal strings (256-bit Blake2b hash).\n */\nexport function isValidTaskHash(hash: string): boolean {\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n/**\n * Debug function to show the CBOR encoding of a task.\n * Useful for comparing against on-chain data.\n *\n * @param task - Task data object\n * @returns Hex string of the CBOR-encoded data (before hashing)\n */\nexport function debugTaskCBOR(task: TaskData): string {\n const cborData = encodeTaskAsPlutusData(task);\n return uint8ArrayToHex(cborData);\n}\n\n// =============================================================================\n// Plutus Data Encoding (Internal)\n// =============================================================================\n\n/**\n * Encode task data matching Plutus serialiseData $ toBuiltinData format.\n *\n * Plutus represents this as a constructor with fields in an INDEFINITE array:\n * Constr 0 [project_content, expiration_time, lovelace_amount, native_assets]\n *\n * IMPORTANT: Plutus uses indefinite-length arrays (0x9f...0xff) not definite (0x84).\n *\n * @internal\n */\nfunction encodeTaskAsPlutusData(task: TaskData): Uint8Array {\n const chunks: Uint8Array[] = [];\n\n // Plutus Constr 0 with indefinite array\n // CBOR tag 121 (0xd879) = Constr 0 in Plutus Data\n chunks.push(new Uint8Array([0xd8, 0x79])); // Tag 121 (Constr 0)\n chunks.push(new Uint8Array([0x9f])); // Start indefinite array\n\n // Field 1: project_content as BuiltinByteString\n chunks.push(encodePlutusBuiltinByteString(new TextEncoder().encode(task.project_content)));\n\n // Field 2: expiration_time as Integer\n chunks.push(encodePlutusInteger(task.expiration_time));\n\n // Field 3: lovelace_amount as Integer\n chunks.push(encodePlutusInteger(task.lovelace_amount));\n\n // Field 4: native_assets as List of pairs\n chunks.push(encodeNativeAssets(task.native_assets));\n\n // End indefinite array\n chunks.push(new Uint8Array([0xff])); // Break\n\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode native assets as Plutus List of (AssetClass, Integer) pairs.\n *\n * Each asset is a pair: (policyId.tokenName, quantity)\n * In Plutus, this is: List [(ByteString, Integer)]\n *\n * @internal\n */\nfunction encodeNativeAssets(assets: NativeAsset[]): Uint8Array {\n if (assets.length === 0) {\n // Empty list: definite-length array of 0 elements\n return new Uint8Array([0x80]); // Array(0)\n }\n\n const chunks: Uint8Array[] = [];\n\n // Start indefinite array\n chunks.push(new Uint8Array([0x9f]));\n\n for (const [assetClass, quantity] of assets) {\n // Each asset is a 2-element array: [bytestring, integer]\n chunks.push(new Uint8Array([0x82])); // Array of 2 elements\n chunks.push(encodePlutusBuiltinByteString(new TextEncoder().encode(assetClass)));\n chunks.push(encodePlutusInteger(quantity));\n }\n\n // End indefinite array\n chunks.push(new Uint8Array([0xff]));\n\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a byte buffer matching Plutus's stringToBuiltinByteString.\n *\n * - Strings <= 64 bytes: regular CBOR byte string\n * - Strings > 64 bytes: indefinite-length chunked byte string (64-byte chunks)\n *\n * @internal\n */\nfunction encodePlutusBuiltinByteString(buffer: Uint8Array): Uint8Array {\n if (buffer.length <= PLUTUS_CHUNK_SIZE) {\n return encodeCBORByteString(buffer);\n }\n\n // Long string: use indefinite-length chunked encoding\n const chunks: Uint8Array[] = [];\n chunks.push(new Uint8Array([0x5f])); // Start indefinite byte string\n\n for (let i = 0; i < buffer.length; i += PLUTUS_CHUNK_SIZE) {\n const chunk = buffer.subarray(i, Math.min(i + PLUTUS_CHUNK_SIZE, buffer.length));\n chunks.push(encodeCBORByteString(chunk));\n }\n\n chunks.push(new Uint8Array([0xff])); // Break\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a number as a CBOR integer (Plutus Integer).\n *\n * @internal\n */\nfunction encodePlutusInteger(n: number): Uint8Array {\n // CBOR integer encoding (major type 0 for positive, 1 for negative)\n if (n >= 0) {\n if (n <= 23) {\n return new Uint8Array([n]);\n } else if (n <= 0xff) {\n return new Uint8Array([0x18, n]);\n } else if (n <= 0xffff) {\n return new Uint8Array([0x19, n >> 8, n & 0xff]);\n } else if (n <= 0xffffffff) {\n return new Uint8Array([0x1a, (n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);\n } else {\n // 64-bit integer - use BigInt for precision\n const buf = new Uint8Array(9);\n buf[0] = 0x1b;\n const big = BigInt(n);\n const view = new DataView(buf.buffer);\n view.setBigUint64(1, big, false); // false = big-endian\n return buf;\n }\n } else {\n // Negative integers: major type 1, encode (-1 - n)\n const absVal = -1 - n;\n if (absVal <= 23) {\n return new Uint8Array([0x20 + absVal]);\n } else if (absVal <= 0xff) {\n return new Uint8Array([0x38, absVal]);\n } else if (absVal <= 0xffff) {\n return new Uint8Array([0x39, absVal >> 8, absVal & 0xff]);\n } else if (absVal <= 0xffffffff) {\n return new Uint8Array([0x3a, (absVal >> 24) & 0xff, (absVal >> 16) & 0xff, (absVal >> 8) & 0xff, absVal & 0xff]);\n } else {\n const buf = new Uint8Array(9);\n buf[0] = 0x3b;\n const big = BigInt(absVal);\n const view = new DataView(buf.buffer);\n view.setBigUint64(1, big, false);\n return buf;\n }\n }\n}\n\n/**\n * Encode a byte buffer as a CBOR byte string (definite length).\n *\n * @internal\n */\nfunction encodeCBORByteString(buffer: Uint8Array): Uint8Array {\n const len = buffer.length;\n\n if (len <= 23) {\n const result = new Uint8Array(1 + len);\n result[0] = 0x40 + len;\n result.set(buffer, 1);\n return result;\n } else if (len <= 255) {\n const result = new Uint8Array(2 + len);\n result[0] = 0x58;\n result[1] = len;\n result.set(buffer, 2);\n return result;\n } else if (len <= 65535) {\n const result = new Uint8Array(3 + len);\n result[0] = 0x59;\n result[1] = len >> 8;\n result[2] = len & 0xff;\n result.set(buffer, 3);\n return result;\n }\n throw new Error(\"Byte string too long for CBOR encoding\");\n}\n\n/**\n * Concatenate multiple Uint8Arrays into one\n *\n * @internal\n */\nfunction concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Convert Uint8Array to hex string\n *\n * @internal\n */\nfunction uint8ArrayToHex(arr: Uint8Array): string {\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n","/**\n * Commitment Hash Utility\n *\n * Functions for computing and verifying hashes of commitment evidence.\n * The hash is stored on-chain as `commitment_hash` in the course state datum,\n * while the full evidence (Tiptap JSON document) is stored in the database.\n *\n * This provides:\n * - Compact on-chain storage (64-char hex hash vs full JSON)\n * - Tamper-evidence (can verify DB content matches on-chain commitment)\n * - Privacy (evidence details not exposed on-chain)\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Tiptap document structure (simplified)\n * The actual structure can be more complex with nested content\n */\nexport type TiptapDoc = {\n type: \"doc\";\n content?: TiptapNode[];\n [key: string]: unknown;\n};\n\nexport type TiptapNode = {\n type: string;\n content?: TiptapNode[];\n text?: string;\n marks?: TiptapMark[];\n attrs?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nexport type TiptapMark = {\n type: string;\n attrs?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\n/**\n * Normalizes a value for consistent hashing.\n *\n * Normalization rules:\n * - Objects: Sort keys alphabetically, recursively normalize values\n * - Arrays: Preserve order, recursively normalize items\n * - Strings: Trim whitespace\n * - Numbers/Booleans/null: Keep as-is\n * - undefined: Convert to null\n *\n * @param value - Any JSON-serializable value\n * @returns Normalized value\n */\nexport function normalizeForHashing(value: unknown): unknown {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return value.trim();\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(normalizeForHashing);\n }\n\n if (typeof value === \"object\") {\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(value as Record<string, unknown>).sort();\n for (const key of keys) {\n const val = (value as Record<string, unknown>)[key];\n if (val !== undefined) {\n sorted[key] = normalizeForHashing(val);\n }\n }\n return sorted;\n }\n\n return value;\n}\n\n/**\n * Computes the commitment hash from evidence content.\n *\n * The hash is computed as:\n * 1. Normalize the evidence (sort keys, trim strings, etc.)\n * 2. Serialize to JSON string (deterministic due to normalization)\n * 3. Apply Blake2b-256 hash\n *\n * @param evidence - The evidence content (Tiptap JSON document or any JSON-serializable data)\n * @returns 64-character lowercase hex string (Blake2b-256 hash)\n *\n * @example\n * ```typescript\n * import { computeCommitmentHash } from \"@andamio/core/hashing\";\n *\n * const evidence = {\n * type: \"doc\",\n * content: [\n * { type: \"paragraph\", content: [{ type: \"text\", text: \"My submission\" }] }\n * ]\n * };\n *\n * const hash = computeCommitmentHash(evidence);\n * // Use this hash as commitment_hash in the transaction\n * ```\n */\nexport function computeCommitmentHash(evidence: unknown): string {\n const normalized = normalizeForHashing(evidence);\n const jsonString = JSON.stringify(normalized);\n const bytes = new TextEncoder().encode(jsonString);\n return blake.blake2bHex(bytes, undefined, 32);\n}\n\n/**\n * Verifies that evidence content matches an expected hash.\n *\n * Use this to verify that database evidence matches the on-chain commitment.\n *\n * @param evidence - The evidence content to verify\n * @param expectedHash - The expected hash (from on-chain data)\n * @returns True if the evidence produces the expected hash\n */\nexport function verifyCommitmentHash(\n evidence: unknown,\n expectedHash: string\n): boolean {\n const computedHash = computeCommitmentHash(evidence);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validates that a string is a valid commitment hash format.\n *\n * A valid hash is a 64-character hexadecimal string (Blake2b-256 output).\n *\n * @param hash - The string to validate\n * @returns True if the string is a valid hash format\n */\nexport function isValidCommitmentHash(hash: string): boolean {\n if (typeof hash !== \"string\") {\n return false;\n }\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n/**\n * Result of comparing evidence with an on-chain hash\n */\nexport type EvidenceVerificationResult = {\n /** Whether the evidence matches the on-chain hash */\n isValid: boolean;\n /** The hash computed from the evidence */\n computedHash: string;\n /** The expected hash (from on-chain) */\n expectedHash: string;\n /** Human-readable status message */\n message: string;\n};\n\n/**\n * Performs a detailed verification of evidence against an on-chain hash.\n *\n * Returns a detailed result object with both hashes and a status message,\n * useful for debugging and user feedback.\n *\n * @param evidence - The evidence content to verify\n * @param onChainHash - The hash from on-chain data\n * @returns Detailed verification result\n */\nexport function verifyEvidenceDetailed(\n evidence: unknown,\n onChainHash: string\n): EvidenceVerificationResult {\n if (!isValidCommitmentHash(onChainHash)) {\n return {\n isValid: false,\n computedHash: \"\",\n expectedHash: onChainHash,\n message: `Invalid on-chain hash format: expected 64 hex characters, got \"${onChainHash}\"`,\n };\n }\n\n const computedHash = computeCommitmentHash(evidence);\n const isValid = computedHash.toLowerCase() === onChainHash.toLowerCase();\n\n return {\n isValid,\n computedHash,\n expectedHash: onChainHash.toLowerCase(),\n message: isValid\n ? \"Evidence matches on-chain commitment\"\n : \"Evidence does not match on-chain commitment - content may have been modified\",\n };\n}\n\n// =============================================================================\n// Backwards Compatibility Aliases (deprecated)\n// =============================================================================\n\n/**\n * @deprecated Use `computeCommitmentHash` instead.\n */\nexport const computeAssignmentInfoHash = computeCommitmentHash;\n\n/**\n * @deprecated Use `verifyCommitmentHash` instead.\n */\nexport const verifyAssignmentInfoHash = verifyCommitmentHash;\n\n/**\n * @deprecated Use `isValidCommitmentHash` instead.\n */\nexport const isValidAssignmentInfoHash = isValidCommitmentHash;\n"]}
1
+ {"version":3,"sources":["../../../src/utils/hashing/slt-hash.ts","../../../src/utils/hashing/task-hash.ts","../../../src/utils/hashing/commitment-hash.ts"],"names":["blake","concatUint8Arrays"],"mappings":";;;;;;;;;AAyBA,IAAM,iBAAA,GAAoB,EAAA;AA0BnB,SAAS,eAAe,IAAA,EAAwB;AACrD,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,CAAI,CAAC,GAAA,KAAQ,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,GAAG,CAAC,CAAA;AAChE,EAAA,MAAM,QAAA,GAAW,oBAAoB,QAAQ,CAAA;AAC7C,EAAA,OAAOA,sBAAA,CAAM,UAAA,CAAW,QAAA,EAAU,MAAA,EAAW,EAAE,CAAA;AACjD;AAKO,IAAM,sBAAA,GAAyB;AAS/B,SAAS,aAAA,CAAc,MAAgB,YAAA,EAA+B;AAC3E,EAAA,MAAM,YAAA,GAAe,eAAe,IAAI,CAAA;AACxC,EAAA,OAAO,YAAA,CAAa,WAAA,EAAY,KAAM,YAAA,CAAa,WAAA,EAAY;AACjE;AAUO,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AAAA,IACtC,OAAA,EAAS,UACL,sCAAA,GACA;AAAA,GACN;AACF;AASO,IAAM,yBAAA,GAA4B;AAKlC,IAAM,wBAAA,GAA2B;AAKjC,IAAM,yBAAA,GAA4B","file":"index.js","sourcesContent":["/**\n * SLT Hash Utility\n *\n * Computes the module token name (hash) from a list of Student Learning Targets (SLTs).\n * This hash is used as the token name when minting module tokens on-chain.\n *\n * The algorithm matches the on-chain Plutus validator:\n * ```haskell\n * sltsToBbs MintModuleV2{slts} = blake2b_256 $ serialiseData $ toBuiltinData $ map stringToBuiltinByteString slts\n * ```\n *\n * Serialization format:\n * 1. Convert each SLT string to UTF-8 bytes\n * 2. Encode as CBOR indefinite-length array of byte strings\n * 3. Hash with Blake2b-256 (32 bytes / 256 bits)\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Plutus chunk size for byte strings.\n * Strings longer than this are encoded as indefinite-length chunked byte strings.\n */\nconst PLUTUS_CHUNK_SIZE = 64;\n\n/**\n * Compute the module hash matching Plutus on-chain encoding.\n *\n * Plutus's `stringToBuiltinByteString` chunks byte strings at 64 bytes.\n * This function replicates that behavior:\n * - Strings <= 64 bytes: encoded as regular CBOR byte strings\n * - Strings > 64 bytes: encoded as indefinite-length chunked byte strings\n *\n * @param slts - Array of Student Learning Target strings\n * @returns 64-character hex string (256-bit Blake2b hash)\n *\n * @example\n * ```typescript\n * import { computeSltHash } from \"@andamio/core/hashing\";\n *\n * const slts = [\n * \"I can mint an access token.\",\n * \"I can complete an assignment to earn a credential.\"\n * ];\n *\n * const moduleHash = computeSltHash(slts);\n * // Returns: \"8dcbe1b925d87e6c547bbd8071c23a712db4c32751454b0948f8c846e9246b5c\"\n * ```\n */\nexport function computeSltHash(slts: string[]): string {\n const sltBytes = slts.map((slt) => new TextEncoder().encode(slt));\n const cborData = encodeAsPlutusArray(sltBytes);\n return blake.blake2bHex(cborData, undefined, 32);\n}\n\n/**\n * @deprecated Use `computeSltHash` instead. This alias is kept for backwards compatibility.\n */\nexport const computeSltHashDefinite = computeSltHash;\n\n/**\n * Verify that a given hash matches the computed hash for SLTs.\n *\n * @param slts - Array of Student Learning Target strings\n * @param expectedHash - The hash to verify (64-character hex string)\n * @returns true if the computed hash matches the expected hash\n */\nexport function verifySltHash(slts: string[], expectedHash: string): boolean {\n const computedHash = computeSltHash(slts);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validate that a string is a valid SLT hash format.\n *\n * SLT hashes are 64-character hexadecimal strings (256-bit Blake2b hash).\n *\n * @param hash - String to validate\n * @returns true if the string is a valid SLT hash format\n */\nexport function isValidSltHash(hash: string): boolean {\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n// =============================================================================\n// Plutus-Compatible Encoding (Internal)\n// =============================================================================\n\n/**\n * Encode an array of byte buffers matching Plutus serialization.\n *\n * Uses indefinite-length array with chunked byte strings for long values.\n *\n * @internal\n */\nfunction encodeAsPlutusArray(items: Uint8Array[]): Uint8Array {\n const chunks: Uint8Array[] = [];\n\n // Start indefinite array\n chunks.push(new Uint8Array([0x9f]));\n\n // Encode each item (with chunking for long strings)\n for (const item of items) {\n chunks.push(encodePlutusBuiltinByteString(item));\n }\n\n // End indefinite array\n chunks.push(new Uint8Array([0xff]));\n\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a byte buffer matching Plutus's stringToBuiltinByteString.\n *\n * - Strings <= 64 bytes: regular CBOR byte string\n * - Strings > 64 bytes: indefinite-length chunked byte string (64-byte chunks)\n *\n * @internal\n */\nfunction encodePlutusBuiltinByteString(buffer: Uint8Array): Uint8Array {\n if (buffer.length <= PLUTUS_CHUNK_SIZE) {\n // Short string: encode normally\n return encodeCBORByteString(buffer);\n }\n\n // Long string: use indefinite-length chunked encoding\n const chunks: Uint8Array[] = [];\n chunks.push(new Uint8Array([0x5f])); // Start indefinite byte string\n\n for (let i = 0; i < buffer.length; i += PLUTUS_CHUNK_SIZE) {\n const chunk = buffer.subarray(i, Math.min(i + PLUTUS_CHUNK_SIZE, buffer.length));\n chunks.push(encodeCBORByteString(chunk));\n }\n\n chunks.push(new Uint8Array([0xff])); // Break\n return concatUint8Arrays(chunks);\n}\n\n/**\n * Encode a byte buffer as a CBOR byte string (definite length).\n *\n * @internal\n */\nfunction encodeCBORByteString(buffer: Uint8Array): Uint8Array {\n const len = buffer.length;\n\n // CBOR byte string encoding (major type 2 = 0x40):\n // - 0-23 bytes: length inline (0x40 + len)\n // - 24-255 bytes: 0x58 + 1-byte length\n // - 256-65535 bytes: 0x59 + 2-byte length (big-endian)\n if (len <= 23) {\n const result = new Uint8Array(1 + len);\n result[0] = 0x40 + len;\n result.set(buffer, 1);\n return result;\n } else if (len <= 255) {\n const result = new Uint8Array(2 + len);\n result[0] = 0x58;\n result[1] = len;\n result.set(buffer, 2);\n return result;\n } else if (len <= 65535) {\n const result = new Uint8Array(3 + len);\n result[0] = 0x59;\n result[1] = len >> 8;\n result[2] = len & 0xff;\n result.set(buffer, 3);\n return result;\n }\n throw new Error(\"Byte string too long for CBOR encoding\");\n}\n\n/**\n * Concatenate multiple Uint8Arrays into one\n *\n * @internal\n */\nfunction concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n","/**\n * Task Hash Utility\n *\n * Computes the task token name (hash) from task data.\n * This hash is used as the task_hash on-chain (content-addressed identifier).\n *\n * The algorithm matches the on-chain Aiken/Haskell hash_project_data function:\n * - Serialize task data as Plutus Data (CBOR with tag 121 for Constructor 0)\n * - Use indefinite-length arrays for constructor fields\n * - Hash with Blake2b-256\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Native asset in Cardano format: [policyId, tokenName, quantity]\n *\n * @example\n * ```typescript\n * const asset: NativeAsset = [\n * \"abc123def456...\".repeat(4), // 56 hex chars (28 bytes) - policy ID\n * \"746f6b656e\", // hex-encoded token name\n * 1000n // quantity as bigint\n * ];\n * ```\n */\nexport type NativeAsset = [\n policyId: string, // 56 hex chars (28 bytes)\n tokenName: string, // hex encoded (0-64 chars / 0-32 bytes)\n quantity: bigint, // arbitrary precision integer\n];\n\n/**\n * Task data structure matching the Aiken ProjectData type.\n *\n * Serialized as Plutus Data Constructor 0 (CBOR tag 121) with fields:\n * 1. project_content (ByteArray - UTF-8 encoded, NFC normalized)\n * 2. deadline (Int - milliseconds)\n * 3. lovelace_am (Int - micro-ADA)\n * 4. tokens (List<FlatValue> - native assets)\n */\nexport interface TaskData {\n /** Task description (max 140 characters) */\n project_content: string;\n /** Unix timestamp in milliseconds */\n expiration_time: bigint;\n /** Lovelace amount (micro-ADA) */\n lovelace_amount: bigint;\n /** Native assets attached to task */\n native_assets: readonly NativeAsset[];\n}\n\n/**\n * Compute the task hash (token name / task_hash) from task data.\n *\n * This produces the same hash as the on-chain Aiken hash_project_data function,\n * allowing clients to pre-compute or verify task hashes.\n *\n * @param task - Task data object\n * @returns 64-character hex string (256-bit Blake2b hash)\n * @throws Error if task data validation fails\n *\n * @example\n * ```typescript\n * import { computeTaskHash } from \"@andamio/core/hashing\";\n *\n * const task = {\n * project_content: \"Open Task #1\",\n * expiration_time: 1769027280000n,\n * lovelace_amount: 15000000n,\n * native_assets: []\n * };\n *\n * const taskHash = computeTaskHash(task);\n * // Returns the on-chain task_hash\n * ```\n */\nexport function computeTaskHash(task: TaskData): string {\n validateTaskData(task);\n const bytes = encodeTaskAsPlutusData(task);\n return blake.blake2bHex(bytes, undefined, 32);\n}\n\n/**\n * Verify that a given hash matches the computed hash for a task.\n *\n * @param task - Task data object\n * @param expectedHash - The hash to verify (64-character hex string)\n * @returns true if the computed hash matches the expected hash\n */\nexport function verifyTaskHash(task: TaskData, expectedHash: string): boolean {\n const computedHash = computeTaskHash(task);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validate that a string is a valid task hash format.\n *\n * Task hashes are 64-character hexadecimal strings (256-bit Blake2b hash).\n */\nexport function isValidTaskHash(hash: string): boolean {\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n/**\n * Debug function to show the CBOR encoding of a task.\n * Useful for comparing against on-chain data.\n *\n * @param task - Task data object\n * @returns Hex string of the CBOR-encoded Plutus Data (before hashing)\n */\nexport function debugTaskBytes(task: TaskData): string {\n validateTaskData(task);\n const bytes = encodeTaskAsPlutusData(task);\n return uint8ArrayToHex(bytes);\n}\n\n// =============================================================================\n// Plutus Data CBOR Encoding (Internal)\n// =============================================================================\n\n/**\n * Encode task data as Plutus Data matching Aiken/Haskell serialization.\n *\n * Format: tag(121) + indefinite-array + [content, deadline, lovelace, tokens] + break\n *\n * The key insight is that Haskell's `serialiseData . toBuiltinData` uses\n * indefinite-length CBOR arrays (0x9f ... 0xff) for Plutus Data constructors.\n *\n * @internal\n */\nfunction encodeTaskAsPlutusData(task: TaskData): Uint8Array {\n const normalizedContent = task.project_content.normalize(\"NFC\");\n const contentBytes = new TextEncoder().encode(normalizedContent);\n\n return concatUint8Arrays([\n // Tag 121 (Plutus Data Constructor 0) + indefinite array start\n new Uint8Array([0xd8, 121, 0x9f]),\n // Field 1: project_content (ByteArray)\n encodeCborBytes(contentBytes),\n // Field 2: deadline (Int)\n encodeCborUint(task.expiration_time),\n // Field 3: lovelace_am (Int)\n encodeCborUint(task.lovelace_amount),\n // Field 4: tokens (List<FlatValue>)\n encodeTokensList(task.native_assets),\n // Break (end of indefinite array)\n new Uint8Array([0xff]),\n ]);\n}\n\n/**\n * Encode a list of native assets as Plutus Data.\n *\n * Each FlatValue is encoded as a Plutus Data constructor with:\n * - PolicyId (ByteArray)\n * - AssetName (ByteArray)\n * - Quantity (Int)\n *\n * @internal\n */\nfunction encodeTokensList(assets: readonly NativeAsset[]): Uint8Array {\n if (assets.length === 0) {\n // Empty definite-length array\n return new Uint8Array([0x80]);\n }\n\n // Encode as indefinite-length array of FlatValue constructors\n const parts: Uint8Array[] = [new Uint8Array([0x9f])]; // indefinite array start\n\n for (const [policyId, tokenName, quantity] of assets) {\n // Each FlatValue is Constructor 0 with 3 fields\n parts.push(new Uint8Array([0xd8, 121, 0x9f])); // tag 121, indefinite array\n parts.push(encodeCborBytes(hexToBytes(policyId)));\n parts.push(encodeCborBytes(hexToBytes(tokenName)));\n parts.push(encodeCborUint(quantity));\n parts.push(new Uint8Array([0xff])); // break\n }\n\n parts.push(new Uint8Array([0xff])); // break (end of list)\n return concatUint8Arrays(parts);\n}\n\n/**\n * Maximum value for CBOR uint64 encoding.\n * @internal\n */\nconst MAX_UINT64 = 18446744073709551615n; // 2^64 - 1\n\n/**\n * Encode CBOR unsigned integer (major type 0).\n *\n * @internal\n */\nfunction encodeCborUint(n: bigint): Uint8Array {\n if (n < 0n) {\n throw new Error(\"Negative integers not supported\");\n }\n if (n > MAX_UINT64) {\n throw new Error(\n `Integer exceeds maximum CBOR uint64 value (got ${n}, max ${MAX_UINT64})`,\n );\n }\n\n if (n < 24n) {\n return new Uint8Array([Number(n)]);\n } else if (n < 256n) {\n return new Uint8Array([0x18, Number(n)]);\n } else if (n < 65536n) {\n return new Uint8Array([0x19, Number(n >> 8n) & 0xff, Number(n) & 0xff]);\n } else if (n < 4294967296n) {\n return new Uint8Array([\n 0x1a,\n Number((n >> 24n) & 0xffn),\n Number((n >> 16n) & 0xffn),\n Number((n >> 8n) & 0xffn),\n Number(n & 0xffn),\n ]);\n } else {\n // 8-byte unsigned integer\n return new Uint8Array([\n 0x1b,\n Number((n >> 56n) & 0xffn),\n Number((n >> 48n) & 0xffn),\n Number((n >> 40n) & 0xffn),\n Number((n >> 32n) & 0xffn),\n Number((n >> 24n) & 0xffn),\n Number((n >> 16n) & 0xffn),\n Number((n >> 8n) & 0xffn),\n Number(n & 0xffn),\n ]);\n }\n}\n\n/**\n * Encode CBOR byte string (major type 2).\n *\n * @internal\n */\nfunction encodeCborBytes(bytes: Uint8Array): Uint8Array {\n const len = bytes.length;\n let header: Uint8Array;\n\n if (len < 24) {\n header = new Uint8Array([0x40 + len]);\n } else if (len < 256) {\n header = new Uint8Array([0x58, len]);\n } else if (len < 65536) {\n header = new Uint8Array([0x59, (len >> 8) & 0xff, len & 0xff]);\n } else {\n throw new Error(\"Byte string too long for CBOR encoding\");\n }\n\n return concatUint8Arrays([header, bytes]);\n}\n\n/**\n * Validate TaskData before hashing.\n *\n * @throws Error if validation fails\n * @internal\n */\nfunction validateTaskData(task: TaskData): void {\n if (task.project_content.length > 140) {\n throw new Error(\n `project_content exceeds 140 characters (got ${task.project_content.length})`,\n );\n }\n\n if (task.expiration_time < 0n) {\n throw new Error(\"expiration_time must be non-negative\");\n }\n if (task.lovelace_amount < 0n) {\n throw new Error(\"lovelace_amount must be non-negative\");\n }\n\n for (const [policyId, tokenName, quantity] of task.native_assets) {\n if (policyId.length !== 56) {\n throw new Error(\n `policyId must be 56 hex chars (got ${policyId.length})`,\n );\n }\n if (!/^[0-9a-fA-F]*$/.test(policyId)) {\n throw new Error(\"policyId contains invalid hex characters\");\n }\n if (tokenName.length > 64 || tokenName.length % 2 !== 0) {\n throw new Error(\n `tokenName must be 0-64 hex chars with even length (got ${tokenName.length})`,\n );\n }\n if (tokenName.length > 0 && !/^[0-9a-fA-F]*$/.test(tokenName)) {\n throw new Error(\"tokenName contains invalid hex characters\");\n }\n if (quantity < 0n) {\n throw new Error(\"asset quantity must be non-negative\");\n }\n }\n}\n\n/**\n * Convert hex string to Uint8Array.\n *\n * @internal\n */\nfunction hexToBytes(hex: string): Uint8Array {\n if (hex.length === 0) {\n return new Uint8Array([]);\n }\n\n if (hex.length % 2 !== 0) {\n throw new Error(`Invalid hex string: odd length (${hex.length})`);\n }\n\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < bytes.length; i++) {\n const byte = parseInt(hex.slice(i * 2, i * 2 + 2), 16);\n if (Number.isNaN(byte)) {\n throw new Error(\n `Invalid hex character at position ${i * 2}: \"${hex.slice(i * 2, i * 2 + 2)}\"`,\n );\n }\n bytes[i] = byte;\n }\n return bytes;\n}\n\n/**\n * Concatenate multiple Uint8Arrays into one.\n *\n * @internal\n */\nfunction concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {\n const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (const arr of arrays) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\n\n/**\n * Convert Uint8Array to hex string.\n *\n * @internal\n */\nfunction uint8ArrayToHex(arr: Uint8Array): string {\n return Array.from(arr)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n","/**\n * Commitment Hash Utility\n *\n * Functions for computing and verifying hashes of commitment evidence.\n * The hash is stored on-chain as `commitment_hash` in the course state datum,\n * while the full evidence (Tiptap JSON document) is stored in the database.\n *\n * This provides:\n * - Compact on-chain storage (64-char hex hash vs full JSON)\n * - Tamper-evidence (can verify DB content matches on-chain commitment)\n * - Privacy (evidence details not exposed on-chain)\n *\n * @module @andamio/core/hashing\n */\n\nimport blake from \"blakejs\";\n\n/**\n * Tiptap document structure (simplified)\n * The actual structure can be more complex with nested content\n */\nexport type TiptapDoc = {\n type: \"doc\";\n content?: TiptapNode[];\n [key: string]: unknown;\n};\n\nexport type TiptapNode = {\n type: string;\n content?: TiptapNode[];\n text?: string;\n marks?: TiptapMark[];\n attrs?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nexport type TiptapMark = {\n type: string;\n attrs?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\n/**\n * Normalizes a value for consistent hashing.\n *\n * Normalization rules:\n * - Objects: Sort keys alphabetically, recursively normalize values\n * - Arrays: Preserve order, recursively normalize items\n * - Strings: Trim whitespace\n * - Numbers/Booleans/null: Keep as-is\n * - undefined: Convert to null\n *\n * @param value - Any JSON-serializable value\n * @returns Normalized value\n */\nexport function normalizeForHashing(value: unknown): unknown {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\") {\n return value.trim();\n }\n\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n\n if (Array.isArray(value)) {\n return value.map(normalizeForHashing);\n }\n\n if (typeof value === \"object\") {\n const sorted: Record<string, unknown> = {};\n const keys = Object.keys(value as Record<string, unknown>).sort();\n for (const key of keys) {\n const val = (value as Record<string, unknown>)[key];\n if (val !== undefined) {\n sorted[key] = normalizeForHashing(val);\n }\n }\n return sorted;\n }\n\n return value;\n}\n\n/**\n * Computes the commitment hash from evidence content.\n *\n * The hash is computed as:\n * 1. Normalize the evidence (sort keys, trim strings, etc.)\n * 2. Serialize to JSON string (deterministic due to normalization)\n * 3. Apply Blake2b-256 hash\n *\n * @param evidence - The evidence content (Tiptap JSON document or any JSON-serializable data)\n * @returns 64-character lowercase hex string (Blake2b-256 hash)\n *\n * @example\n * ```typescript\n * import { computeCommitmentHash } from \"@andamio/core/hashing\";\n *\n * const evidence = {\n * type: \"doc\",\n * content: [\n * { type: \"paragraph\", content: [{ type: \"text\", text: \"My submission\" }] }\n * ]\n * };\n *\n * const hash = computeCommitmentHash(evidence);\n * // Use this hash as commitment_hash in the transaction\n * ```\n */\nexport function computeCommitmentHash(evidence: unknown): string {\n const normalized = normalizeForHashing(evidence);\n const jsonString = JSON.stringify(normalized);\n const bytes = new TextEncoder().encode(jsonString);\n return blake.blake2bHex(bytes, undefined, 32);\n}\n\n/**\n * Verifies that evidence content matches an expected hash.\n *\n * Use this to verify that database evidence matches the on-chain commitment.\n *\n * @param evidence - The evidence content to verify\n * @param expectedHash - The expected hash (from on-chain data)\n * @returns True if the evidence produces the expected hash\n */\nexport function verifyCommitmentHash(\n evidence: unknown,\n expectedHash: string\n): boolean {\n const computedHash = computeCommitmentHash(evidence);\n return computedHash.toLowerCase() === expectedHash.toLowerCase();\n}\n\n/**\n * Validates that a string is a valid commitment hash format.\n *\n * A valid hash is a 64-character hexadecimal string (Blake2b-256 output).\n *\n * @param hash - The string to validate\n * @returns True if the string is a valid hash format\n */\nexport function isValidCommitmentHash(hash: string): boolean {\n if (typeof hash !== \"string\") {\n return false;\n }\n if (hash.length !== 64) {\n return false;\n }\n return /^[0-9a-fA-F]{64}$/.test(hash);\n}\n\n/**\n * Result of comparing evidence with an on-chain hash\n */\nexport type EvidenceVerificationResult = {\n /** Whether the evidence matches the on-chain hash */\n isValid: boolean;\n /** The hash computed from the evidence */\n computedHash: string;\n /** The expected hash (from on-chain) */\n expectedHash: string;\n /** Human-readable status message */\n message: string;\n};\n\n/**\n * Performs a detailed verification of evidence against an on-chain hash.\n *\n * Returns a detailed result object with both hashes and a status message,\n * useful for debugging and user feedback.\n *\n * @param evidence - The evidence content to verify\n * @param onChainHash - The hash from on-chain data\n * @returns Detailed verification result\n */\nexport function verifyEvidenceDetailed(\n evidence: unknown,\n onChainHash: string\n): EvidenceVerificationResult {\n if (!isValidCommitmentHash(onChainHash)) {\n return {\n isValid: false,\n computedHash: \"\",\n expectedHash: onChainHash,\n message: `Invalid on-chain hash format: expected 64 hex characters, got \"${onChainHash}\"`,\n };\n }\n\n const computedHash = computeCommitmentHash(evidence);\n const isValid = computedHash.toLowerCase() === onChainHash.toLowerCase();\n\n return {\n isValid,\n computedHash,\n expectedHash: onChainHash.toLowerCase(),\n message: isValid\n ? \"Evidence matches on-chain commitment\"\n : \"Evidence does not match on-chain commitment - content may have been modified\",\n };\n}\n\n// =============================================================================\n// Backwards Compatibility Aliases (deprecated)\n// =============================================================================\n\n/**\n * @deprecated Use `computeCommitmentHash` instead.\n */\nexport const computeAssignmentInfoHash = computeCommitmentHash;\n\n/**\n * @deprecated Use `verifyCommitmentHash` instead.\n */\nexport const verifyAssignmentInfoHash = verifyCommitmentHash;\n\n/**\n * @deprecated Use `isValidCommitmentHash` instead.\n */\nexport const isValidAssignmentInfoHash = isValidCommitmentHash;\n"]}