b017 0.0.0-b

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.
Files changed (32) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE.txt +56 -0
  3. package/README.md +206 -0
  4. package/dist/index.d.ts +13 -0
  5. package/dist/index.js +15 -0
  6. package/dist/lib/boltLib.d.ts +49 -0
  7. package/dist/lib/boltLib.js +177 -0
  8. package/dist/lib/multi/multiBoltLib.d.ts +4 -0
  9. package/dist/lib/multi/multiBoltLib.js +473 -0
  10. package/dist/lib/scanner/fingerprints.d.ts +25 -0
  11. package/dist/lib/scanner/fingerprints.js +95 -0
  12. package/dist/lib/scanner/verifyEvents.d.ts +37 -0
  13. package/dist/lib/scanner/verifyEvents.js +294 -0
  14. package/dist/lib/single/singleAncestor.d.ts +8 -0
  15. package/dist/lib/single/singleAncestor.js +72 -0
  16. package/dist/lib/single/singleSpend.d.ts +31 -0
  17. package/dist/lib/single/singleSpend.js +110 -0
  18. package/dist/tokens/BOLT.d.ts +17 -0
  19. package/dist/tokens/BOLT.js +9 -0
  20. package/dist/tokens/MultiBOLT.d.ts +44 -0
  21. package/dist/tokens/MultiBOLT.js +465 -0
  22. package/dist/tokens/templates/MinSimple.sx.template.d.ts +23 -0
  23. package/dist/tokens/templates/MinSimple.sx.template.js +57 -0
  24. package/dist/tokens/templates/MinSimpleBalance.sx.template.d.ts +24 -0
  25. package/dist/tokens/templates/MinSimpleBalance.sx.template.js +59 -0
  26. package/dist/tokens/templates/MinSimpleDiscount.sx.template.d.ts +23 -0
  27. package/dist/tokens/templates/MinSimpleDiscount.sx.template.js +58 -0
  28. package/dist/tokens/templates/SimpleMulti.sx.template.d.ts +19 -0
  29. package/dist/tokens/templates/SimpleMulti.sx.template.js +214 -0
  30. package/dist/tokens/templates/pay2Proof.d.ts +8 -0
  31. package/dist/tokens/templates/pay2Proof.js +59 -0
  32. package/package.json +58 -0
@@ -0,0 +1,294 @@
1
+ // verifyEvents.ts — the shared off-chain BOLT validator (the scanner).
2
+ //
3
+ // The protocol is a stream of TRANSACTIONAL EVENTS. A transfer/split/merge event is a
4
+ // commit -> settle PAIR of txs; a mint is a single genesis tx; a melt is a single terminal tx.
5
+ // Because most events are two txs, events can be collected into a BATCH, transmitted together,
6
+ // and parsed for authenticity by a multistep inspection.
7
+ //
8
+ // verifyEvent(txs) — validate ONE event: categorise its tx(s) by the token's txoType action
9
+ // byte, fingerprint EVERY interface (strict golden recognition for all token
10
+ // inputs/outputs — including split's 2 token outputs and merge's 2 token
11
+ // inputs; loose shape for the p2p proof / change / funding), and check the
12
+ // commit<->settle linkage.
13
+ // verifyEvents(txs) — validate a BATCH of events: recognise the type, pin the issuer across the
14
+ // whole batch, fingerprint every tx's arrangement, then pair the events —
15
+ // every commit must be matched by a settle (and vice-versa) via parentOutpoint.
16
+ // A lone mint or melt is a valid single-tx event.
17
+ //
18
+ // NOTE — a commit and its settle are bound TWO independent ways:
19
+ // (1) TOKEN LINEAGE — the settle's token parentOutpoint references the commit's token output.
20
+ // This is the binding verifyEvents/verifyEvent assert.
21
+ // (2) FUNDING CHAIN — in general the settle's funding input spends the commit's CHANGE output (the
22
+ // commit's last, change=true output). So the pair is also chained at the
23
+ // satoshi/funding level. This is a CONSTRUCTION property — a caller-supplied
24
+ // fundOverride can fund the settle from elsewhere — so it is NOT asserted here.
25
+ //
26
+ // Strict = golden byte fingerprint (recognizeType: leading-push layout + sha256(static code)).
27
+ // Loose = shape only (a P2PKH change output / external funding input may carry any pkh + value).
28
+ import { OP, Transaction, Utils } from "@bsv/sdk";
29
+ import { recognizeType, recognizeP2P, issuerPubKeyOf } from "./fingerprints.js";
30
+ const FIELDS = {
31
+ MinSimpleBOLT: { pubKeyHash: 0, commitment: 1, txoType: 2, parent: 3, grandparent: 4 },
32
+ MinSimpleDiscountBOLT: { pubKeyHash: 1, commitment: 2, txoType: 3, parent: 4, grandparent: 5 },
33
+ MinSimpleBalanceBOLT: { pubKeyHash: 1, commitment: 2, txoType: 3, parent: 4, grandparent: 5 },
34
+ SimpleMultiBOLT: { pubKeyHash: 2, commitment: 3, txoType: 6, parent: 8, grandparent: 9 },
35
+ };
36
+ const field = (lock, type, f) => lock.chunks[FIELDS[type][f]]?.data ?? [];
37
+ const fieldHex = (lock, type, f) => Utils.toHex(field(lock, type, f));
38
+ // A 36-byte outpoint is txid (32, internal byte order) + vout (4, LE). The display txid is reversed.
39
+ // A short/empty buffer (a tampered or absent field) yields a txid that cannot match any real tx, so
40
+ // the linkage check fails closed rather than throwing.
41
+ function parseOutpoint(op) {
42
+ const bytes = Array.isArray(op) ? op : [];
43
+ const txidHex = Utils.toHex([...bytes.slice(0, 32)].reverse());
44
+ const v = new Uint8Array(4);
45
+ v.set(bytes.slice(32, 36)); // missing bytes stay 0 — a short/absent field can't match a real outpoint
46
+ const vout = (v[0] | (v[1] << 8) | (v[2] << 16) | (v[3] << 24)) >>> 0;
47
+ return { txidHex, vout };
48
+ }
49
+ /** Thrown when an input tx (string) cannot be parsed; caught at the verify entry points and turned
50
+ * into an `ok: false` result so a malformed batch never escapes as an exception. */
51
+ class ParseError extends Error {
52
+ }
53
+ const toTx = (t) => {
54
+ if (typeof t !== "string")
55
+ return t;
56
+ try {
57
+ return Transaction.fromHex(t);
58
+ }
59
+ catch (e) {
60
+ throw new ParseError(`malformed transaction hex: ${e?.message ?? e}`);
61
+ }
62
+ };
63
+ const optHex = (b) => b == null ? undefined : typeof b === "string" ? b.toLowerCase() : Utils.toHex(b);
64
+ /** Classify an output's locking script. token = strict golden fingerprint; p2p = the b017 marker
65
+ * proof output; p2pkh = a plain pay-to-pubkey-hash (change); else "other". */
66
+ function classifyOut(lock, type) {
67
+ if (recognizeType(lock, type))
68
+ return "token";
69
+ if (recognizeP2P(lock))
70
+ return "p2p"; // golden p2Proof fingerprint (b017 marker + static skeleton)
71
+ const c = lock?.chunks ?? [];
72
+ if (c.length === 5 && c[0].op === OP.OP_DUP && c[1].op === OP.OP_HASH160 && c[2].data?.length === 20 &&
73
+ c[3].op === OP.OP_EQUALVERIFY && c[4].op === OP.OP_CHECKSIG)
74
+ return "p2pkh";
75
+ return "other";
76
+ }
77
+ /** Classify an input by fingerprinting the output it spends (via the attached source tx, else a
78
+ * source tx supplied in the batch); "external" when the source is outside the supplied set. */
79
+ function classifyIn(input, type, byId) {
80
+ const src = input.sourceTransaction ?? (input.sourceTXID ? byId.get(input.sourceTXID) : undefined);
81
+ const spent = src?.outputs?.[input.sourceOutputIndex]?.lockingScript;
82
+ if (!spent)
83
+ return "external"; // source not in the supplied set (or out-of-range vout)
84
+ return classifyOut(spent, type);
85
+ }
86
+ function categorise(tx, type, byId) {
87
+ const tokenOutIdx = tx.outputs.findIndex((o) => recognizeType(o.lockingScript, type));
88
+ if (tokenOutIdx >= 0) {
89
+ const lock = tx.outputs[tokenOutIdx].lockingScript;
90
+ const parentZero = field(lock, type, "parent").every((b) => b === 0);
91
+ if (parentZero)
92
+ return { shape: { kind: "mint", tokenIn: 0, tokenOut: 1, proofOut: 0 }, tokenOutIdx };
93
+ const S = (kind, tokenIn, tokenOut, proofOut) => ({ shape: { kind, tokenIn, tokenOut, proofOut }, tokenOutIdx });
94
+ switch (fieldHex(lock, type, "txoType")) {
95
+ case "21": return S("commit", 1, 1, 1); // transfer commit
96
+ case "23": return S("commit", 1, 1, 2); // split commit -> 2 p2p proofs
97
+ case "25": return S("commit", 2, 1, 1); // merge commit -> 2 token inputs
98
+ case "22": return S("settle", 1, 2, 0); // split settle -> 2 token outputs
99
+ case "24": return S("settle", 1, 1, 0); // merge settle
100
+ default: return S("settle", 1, 1, 0); // transfer settle (txoType 20 / 00) + any resting state
101
+ }
102
+ }
103
+ // No token output — a melt (spends a token, no token output)?
104
+ if (tx.inputs.some((i) => classifyIn(i, type, byId) === "token"))
105
+ return { shape: { kind: "melt", tokenIn: 1, tokenOut: 0, proofOut: 0 }, tokenOutIdx: -1 };
106
+ return null;
107
+ }
108
+ const actionKind = (txoTypeHex) => txoTypeHex === "23" ? "split" : txoTypeHex === "25" ? "merge" : "transfer";
109
+ /** Fingerprint every interface of a token tx and check it matches its action's golden shape:
110
+ * the leading token in/out are strictly recognised; the p2p proof outputs are exact in count;
111
+ * trailing change (p2pkh) + funding/proof inputs are loose; nothing may be "other". */
112
+ function checkArrangement(tx, type, shape, byId) {
113
+ const id = tx.id("hex").slice(0, 8);
114
+ const outs = tx.outputs.map((o) => classifyOut(o.lockingScript, type));
115
+ const ins = tx.inputs.map((i) => classifyIn(i, type, byId));
116
+ if (outs.includes("other"))
117
+ return `uninspected output in ${id} [${outs}]`;
118
+ if (ins.includes("other"))
119
+ return `uninspected input in ${id} [${ins}]`;
120
+ // outputs: [token × tokenOut] then [p2p × proofOut] then [p2pkh change × rest]
121
+ for (let k = 0; k < shape.tokenOut; k++)
122
+ if (outs[k] !== "token")
123
+ return `${shape.kind} ${id}: token output @${k} (got ${outs[k] ?? "none"}) [${outs}]`;
124
+ for (let k = 0; k < shape.proofOut; k++)
125
+ if (outs[shape.tokenOut + k] !== "p2p")
126
+ return `${shape.kind} ${id}: p2p output @${shape.tokenOut + k} [${outs}]`;
127
+ for (let k = shape.tokenOut + shape.proofOut; k < outs.length; k++)
128
+ if (outs[k] !== "p2pkh")
129
+ return `${shape.kind} ${id}: change p2pkh @${k} (got ${outs[k]}) [${outs}]`;
130
+ // inputs: [token × tokenIn] then [p2p proof × any (settle only, contiguous)] then [funding: external | p2pkh].
131
+ // A p2Proof input (consuming a commit's proof output) is STRICTLY fingerprinted (classifyIn ->
132
+ // recognizeP2P) and is only legitimate on a settle, immediately after the token input(s); a proof
133
+ // input on any other tx kind, or after the funding region, is rejected.
134
+ for (let k = 0; k < shape.tokenIn; k++)
135
+ if (ins[k] !== "token")
136
+ return `${shape.kind} ${id}: token input @${k} (got ${ins[k] ?? "none"}) [${ins}]`;
137
+ let k = shape.tokenIn;
138
+ if (shape.kind === "settle")
139
+ while (ins[k] === "p2p")
140
+ k++; // strict, contiguous proof inputs
141
+ for (; k < ins.length; k++)
142
+ if (!(ins[k] === "external" || ins[k] === "p2pkh"))
143
+ return `${shape.kind} ${id}: unexpected input @${k}: ${ins[k]} (a p2Proof input is only valid on a settle, immediately after the token input) [${ins}]`;
144
+ return null;
145
+ }
146
+ /** Resolve the token type of an event from its first recognised token interface (output, then a
147
+ * token input's source for a melt). */
148
+ function eventType(txs, byId, expected) {
149
+ for (const tx of txs) {
150
+ const i = tx.outputs.findIndex((o) => recognizeType(o.lockingScript, expected));
151
+ if (i >= 0)
152
+ return recognizeType(tx.outputs[i].lockingScript, expected);
153
+ }
154
+ for (const tx of txs)
155
+ for (const inp of tx.inputs) {
156
+ const s = inp.sourceTransaction ?? (inp.sourceTXID ? byId.get(inp.sourceTXID) : undefined);
157
+ if (s) {
158
+ const t = recognizeType(s.outputs[inp.sourceOutputIndex].lockingScript, expected);
159
+ if (t)
160
+ return t;
161
+ }
162
+ }
163
+ return undefined;
164
+ }
165
+ /**
166
+ * Verify ONE token event — a mint, a commit->settle pair, or a melt. Categorises each tx by its
167
+ * token's txoType action, fingerprints EVERY interface against the action's golden shape, and (for
168
+ * a commit+settle pair) checks the settle links back to the commit via parentOutpoint.
169
+ */
170
+ export function verifyEvent(eventTxs, opts = {}) {
171
+ if (!Array.isArray(eventTxs))
172
+ return { ok: false, reason: "event must be an array of transactions" };
173
+ let txs;
174
+ try {
175
+ txs = eventTxs.map(toTx);
176
+ }
177
+ catch (e) {
178
+ return { ok: false, reason: e instanceof ParseError ? e.message : `unparseable event: ${e}` };
179
+ }
180
+ if (txs.length === 0)
181
+ return { ok: false, reason: "empty event" };
182
+ const byId = new Map(txs.map((t) => [t.id("hex"), t]));
183
+ const type = eventType(txs, byId, opts.expectedType);
184
+ if (!type)
185
+ return { ok: false, reason: "no BOLT token recognised in event" };
186
+ /* v8 ignore next 2 -- eventType() already filtered by expectedType, so this is unreachable; kept as defense-in-depth */
187
+ if (opts.expectedType && type !== opts.expectedType)
188
+ return { ok: false, reason: `expected ${opts.expectedType}, got ${type}`, type };
189
+ for (const tx of txs) {
190
+ const cat = categorise(tx, type, byId);
191
+ if (!cat)
192
+ return { ok: false, reason: `tx ${tx.id("hex").slice(0, 8)} is not a token tx`, type };
193
+ const reason = checkArrangement(tx, type, cat.shape, byId);
194
+ if (reason)
195
+ return { ok: false, reason, type, kind: cat.shape.kind };
196
+ }
197
+ const commitTx = txs.find((t) => categorise(t, type, byId)?.shape.kind === "commit");
198
+ const settleTx = txs.find((t) => categorise(t, type, byId)?.shape.kind === "settle");
199
+ if (commitTx && settleTx) {
200
+ const cIdx = commitTx.outputs.findIndex((o) => recognizeType(o.lockingScript, type));
201
+ const sIdx = settleTx.outputs.findIndex((o) => recognizeType(o.lockingScript, type));
202
+ const p = parseOutpoint(field(settleTx.outputs[sIdx].lockingScript, type, "parent"));
203
+ if (!(p.txidHex === commitTx.id("hex") && p.vout === cIdx))
204
+ return { ok: false, reason: "settle.parent does not link to the commit token", type };
205
+ return { ok: true, type, kind: actionKind(fieldHex(commitTx.outputs[cIdx].lockingScript, type, "txoType")) };
206
+ }
207
+ const lone = categorise(txs[txs.length - 1], type, byId);
208
+ return { ok: true, type, kind: lone?.shape.kind === "melt" ? "melt" : "mint" };
209
+ }
210
+ /**
211
+ * Verify a BATCH of transactional events end to end. The multistep inspection: recognise the type,
212
+ * pin the issuer across every token output in the batch, fingerprint every tx's interface
213
+ * arrangement, then pair the events — every commit (txoType 21/23/25) must be matched by a settle
214
+ * that links back via parentOutpoint, and every settle must link to a commit in the batch. A lone
215
+ * mint (genesis) or melt (terminal) is a valid single-tx event.
216
+ */
217
+ export function verifyEvents(txsIn, opts = {}) {
218
+ if (!Array.isArray(txsIn))
219
+ return { ok: false, reason: "batch must be an array of transactions" };
220
+ let txs;
221
+ try {
222
+ txs = txsIn.map(toTx);
223
+ }
224
+ catch (e) {
225
+ return { ok: false, reason: e instanceof ParseError ? e.message : `unparseable batch: ${e}` };
226
+ }
227
+ if (txs.length === 0)
228
+ return { ok: false, reason: "empty batch" };
229
+ const byId = new Map(txs.map((t) => [t.id("hex"), t]));
230
+ const tokens = [];
231
+ for (const tx of txs) {
232
+ const txid = tx.id("hex");
233
+ tx.outputs.forEach((o, vout) => {
234
+ const type = recognizeType(o.lockingScript, opts.expectedType);
235
+ if (type)
236
+ tokens.push({ txid, vout, type, lock: o.lockingScript });
237
+ });
238
+ }
239
+ if (tokens.length === 0)
240
+ return { ok: false, reason: "no BOLT token output recognised" };
241
+ const type = tokens[0].type;
242
+ if (tokens.some((t) => t.type !== type))
243
+ return { ok: false, reason: "mixed token types in batch" };
244
+ /* v8 ignore next 2 -- recognizeType() already filtered by expectedType, so this is unreachable; kept as defense-in-depth */
245
+ if (opts.expectedType && type !== opts.expectedType)
246
+ return { ok: false, reason: `expected ${opts.expectedType}, got ${type}` };
247
+ // Issuer consistent across all token outputs, and == the trusted issuer (if supplied).
248
+ const issuers = new Set(tokens.map((t) => Utils.toHex(issuerPubKeyOf(t.lock, type))));
249
+ if (issuers.size !== 1)
250
+ return { ok: false, reason: "inconsistent issuerPubKey across batch" };
251
+ const issuerPubKeyHex = [...issuers][0];
252
+ /* v8 ignore next 2 -- a recognised token's last push is exactly 33 bytes (the registry layout), so this never fires; kept as defense-in-depth */
253
+ if (issuerPubKeyHex.length !== 66) // a compressed secp256k1 pubkey is exactly 33 bytes
254
+ return { ok: false, reason: "issuerPubKey is not a 33-byte compressed public key", type };
255
+ const trusted = optHex(opts.trustedIssuerPubKey);
256
+ if (trusted && trusted !== issuerPubKeyHex)
257
+ return { ok: false, reason: "issuerPubKey != trusted issuer" };
258
+ // Categorise every tx — each must be a well-formed BOLT event tx (mint / commit / settle / melt).
259
+ const cats = txs.map((tx) => ({ tx, cat: categorise(tx, type, byId) }));
260
+ for (const { tx, cat } of cats)
261
+ if (!cat)
262
+ return { ok: false, reason: `tx ${tx.id("hex").slice(0, 8)} is not a BOLT token tx`, type };
263
+ // Pair the events: every settle links back to a commit in the batch, and every commit is settled.
264
+ // (Checked before the per-interface arrangement so a structurally-incomplete batch reports the
265
+ // missing-pair reason, not an orphaned-input one.)
266
+ const key = (txid, vout) => `${txid}:${vout}`;
267
+ const commits = cats.filter((c) => c.cat.shape.kind === "commit");
268
+ const settled = new Set();
269
+ const events = [];
270
+ for (const s of cats.filter((c) => c.cat.shape.kind === "settle")) {
271
+ const sLock = s.tx.outputs[s.cat.tokenOutIdx].lockingScript;
272
+ const p = parseOutpoint(field(sLock, type, "parent"));
273
+ const commit = commits.find((c) => c.tx.id("hex") === p.txidHex && c.cat.tokenOutIdx === p.vout);
274
+ if (!commit)
275
+ return { ok: false, reason: `settle ${s.tx.id("hex").slice(0, 8)} links to no commit in the batch (orphan settle)`, type };
276
+ settled.add(key(commit.tx.id("hex"), commit.cat.tokenOutIdx));
277
+ const cLock = commit.tx.outputs[commit.cat.tokenOutIdx].lockingScript;
278
+ events.push({ kind: actionKind(fieldHex(cLock, type, "txoType")), txids: [commit.tx.id("hex"), s.tx.id("hex")] });
279
+ }
280
+ for (const c of commits)
281
+ if (!settled.has(key(c.tx.id("hex"), c.cat.tokenOutIdx)))
282
+ return { ok: false, reason: `commit ${c.tx.id("hex").slice(0, 8)} has no settle in the batch (unsettled commit)`, type };
283
+ // Per-interface arrangement: categorise + fingerprint every tx.
284
+ for (const { tx, cat } of cats) {
285
+ const reason = checkArrangement(tx, type, cat.shape, byId);
286
+ if (reason)
287
+ return { ok: false, reason, type };
288
+ }
289
+ // Standalone single-tx events (genesis mints, terminal melts).
290
+ for (const { tx, cat } of cats)
291
+ if (cat.shape.kind === "mint" || cat.shape.kind === "melt")
292
+ events.push({ kind: cat.shape.kind, txids: [tx.id("hex")] });
293
+ return { ok: true, type, issuerPubKeyHex, events };
294
+ }
@@ -0,0 +1,8 @@
1
+ import { Transaction } from "@bsv/sdk";
2
+ /** The 26 NFT ancestor-piece names, in unlockArgs order [0..25]. */
3
+ export declare const PIECE_NAMES: string[];
4
+ /** Extract one named NFT ancestor piece from an ancestor commit tx (its in[0] must have its
5
+ * sourceTransaction attached). `leadingValuePushes`: 0 = identity, 1 = discount/balance. */
6
+ export declare function ancestorPiece(name: string, ancestorTx: Transaction, leadingValuePushes: number): number[];
7
+ /** All 26 ancestor pieces in unlockArgs order — PIECE_NAMES mapped through ancestorPiece. */
8
+ export declare function singleAncestorPieces(ancestorTx: Transaction, leadingValuePushes: number): number[][];
@@ -0,0 +1,72 @@
1
+ // NFT ancestor reconstruction — the 26 ancestor-piece unlock args [0..25] a settle
2
+ // must carry when it reaches back over a chain of >= 4 txs (e.g. a coupon round-trip's 2nd hop: the
3
+ // settle s2 reconstructs the commit c1 where the current owner received the token). These bytes let
4
+ // the contract rebuild + hash the ancestor commit to verify the lineage binding.
5
+ //
6
+ // The ancestor is a COMMIT tx with the shape: in[0]=bolt (spends the prior token), in[1]=funding;
7
+ // out[0]=token, out[1]=p2pb(beneficiary), out[2]=change. We extract from it (and its in[0] unlock,
8
+ // which carries the same 37-arg layout). `leadingValuePushes` = number of immutable value pushes at
9
+ // the front of the lock (0 = MinSimpleBolt identity, 1 = Discount/Balance) so the token-data fields
10
+ // (pubKeyHash/commitment/txoType/parent/grandparent) are read at the right chunk offset.
11
+ //
12
+ // Mirrors the SimpleMultiBolt ancestor idiom (multiBoltLib): a PIECE_NAMES list + an
13
+ // ancestorPiece(name, tx) switch — common naming + shape across both token streams.
14
+ import { Script } from "@bsv/sdk";
15
+ import { le32, le64, scriptChunk, spentOutpoint } from "../boltLib.js";
16
+ /** The 26 NFT ancestor-piece names, in unlockArgs order [0..25]. */
17
+ export const PIECE_NAMES = [
18
+ "Version",
19
+ "Vin1Outpoint", "Vin1FundOutpoint", "Vin1ChangeOutput", "Vin1BeneficiaryPubKeyHash",
20
+ "Vin1Sig", "Vin1PubKey", "Vin1CTXHeader",
21
+ "Vin1CTXScriptCodePubKeyHash", "Vin1CTXScriptCodePubKeyHashCommitment", "Vin1CTXScriptCodeTxoType",
22
+ "Vin1CTXScriptCodeParentOutpoint", "Vin1CTXScriptCodeGrandparentOutpoint",
23
+ "Vin1CTXFooter", "Vin1NSequence",
24
+ "Vin2Outpoint", "Vin2Script", "Vin2NSequence",
25
+ "Vout1PubKeyHash", "Vout1PubKeyHashCommitment", "Vout1TxoType", "Vout1ParentOutpoint", "Vout1GrandparentOutpoint",
26
+ "ChangeValue", "ChangeScript", "NLockTime",
27
+ ];
28
+ /** Extract one named NFT ancestor piece from an ancestor commit tx (its in[0] must have its
29
+ * sourceTransaction attached). `leadingValuePushes`: 0 = identity, 1 = discount/balance. */
30
+ export function ancestorPiece(name, ancestorTx, leadingValuePushes) {
31
+ const in0 = ancestorTx.inputs[0];
32
+ const in1 = ancestorTx.inputs[1];
33
+ const u = in0.unlockingScript; // ancestor's bolt-spend unlock (37-arg layout)
34
+ const spentLock = Script.fromBinary(u.chunks[34]?.data ?? []); // its in[0] CTX scriptCode
35
+ const sd = (i) => scriptChunk(spentLock, leadingValuePushes + i); // prior token's data fields
36
+ const outLock = ancestorTx.outputs[0].lockingScript; // ancestor's OUTPUT token (vout0)
37
+ const od = (i) => scriptChunk(outLock, leadingValuePushes + i);
38
+ const changeOut = ancestorTx.outputs[2];
39
+ switch (name) {
40
+ case "Version": return le32(ancestorTx.version);
41
+ case "Vin1Outpoint": return spentOutpoint(ancestorTx, 0);
42
+ case "Vin1FundOutpoint": return scriptChunk(u, 26);
43
+ case "Vin1ChangeOutput": return scriptChunk(u, 27);
44
+ case "Vin1BeneficiaryPubKeyHash": return scriptChunk(u, 28);
45
+ case "Vin1Sig": return scriptChunk(u, 29);
46
+ case "Vin1PubKey": return scriptChunk(u, 30);
47
+ case "Vin1CTXHeader": return scriptChunk(u, 31);
48
+ case "Vin1CTXScriptCodePubKeyHash": return sd(0);
49
+ case "Vin1CTXScriptCodePubKeyHashCommitment": return sd(1);
50
+ case "Vin1CTXScriptCodeTxoType": return sd(2);
51
+ case "Vin1CTXScriptCodeParentOutpoint": return sd(3);
52
+ case "Vin1CTXScriptCodeGrandparentOutpoint": return sd(4);
53
+ case "Vin1CTXFooter": return scriptChunk(u, 35);
54
+ case "Vin1NSequence": return le32(in0.sequence ?? 0xffffffff);
55
+ case "Vin2Outpoint": return spentOutpoint(ancestorTx, 1);
56
+ case "Vin2Script": return in1.unlockingScript.toBinary();
57
+ case "Vin2NSequence": return le32(in1.sequence ?? 0xffffffff);
58
+ case "Vout1PubKeyHash": return od(0);
59
+ case "Vout1PubKeyHashCommitment": return od(1);
60
+ case "Vout1TxoType": return od(2);
61
+ case "Vout1ParentOutpoint": return od(3);
62
+ case "Vout1GrandparentOutpoint": return od(4);
63
+ case "ChangeValue": return le64(changeOut.satoshis);
64
+ case "ChangeScript": return changeOut.lockingScript.toBinary();
65
+ case "NLockTime": return le32(ancestorTx.lockTime);
66
+ default: return [];
67
+ }
68
+ }
69
+ /** All 26 ancestor pieces in unlockArgs order — PIECE_NAMES mapped through ancestorPiece. */
70
+ export function singleAncestorPieces(ancestorTx, leadingValuePushes) {
71
+ return PIECE_NAMES.map((name) => ancestorPiece(name, ancestorTx, leadingValuePushes));
72
+ }
@@ -0,0 +1,31 @@
1
+ import { Script, UnlockingScript, Transaction, PrivateKey, Hash } from "@bsv/sdk";
2
+ /** Number of leading ancestor-reconstruction args in the NFT unlock layout. */
3
+ export declare const SINGLE_ANCESTOR_ARG_COUNT = 26;
4
+ /** 26 empty ancestor pushes — the simple-transfer (and melt) case. */
5
+ export declare const emptySingleAncestorChunks: () => any[];
6
+ export interface SingleUnlockParams {
7
+ privateKey: PrivateKey;
8
+ /** The next owner's 20-byte pubKeyHash (commit + settle both commit-to the recipient). */
9
+ beneficiaryPubKeyHash: number[];
10
+ /** UNLOCK_SCRIPT_SUFFIX ASM for the specific contract (patched from its artifact). */
11
+ unlockScriptSuffixASM: string;
12
+ forceNoChange?: boolean;
13
+ forceNoFund?: boolean;
14
+ /** Prior txs in the lineage (mint, commit, ...). Used to detect a back-reaching settle. */
15
+ prevTxs?: Transaction[];
16
+ /** Optional overrides when the input's sourceTransaction isn't attached. */
17
+ sourceSatoshis?: number;
18
+ lockingScript?: Script;
19
+ /** Leading immutable value pushes in the lock (0 = identity, 1 = discount/balance). Needed to read
20
+ * the ancestor's token-data fields at the right chunk offset during back-reaching reconstruction. */
21
+ leadingValuePushes?: number;
22
+ }
23
+ /**
24
+ * Build a ScriptTemplate-compatible unlocker for an NFT-family bolt spend (transfer commit/settle, and
25
+ * a back-reaching settle that reconstructs its ancestor commit). Requires tx version >= 2.
26
+ */
27
+ export declare function singleSpendUnlock(params: SingleUnlockParams): {
28
+ sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>;
29
+ estimateLength: () => Promise<number>;
30
+ };
31
+ export { Hash };
@@ -0,0 +1,110 @@
1
+ // Shared spend/unlock assembler for the NFT-family BOLT templates (MinSimpleBolt / Discount / Balance).
2
+ //
3
+ // Produces VALID spends on the @bsv/sdk Spend engine for the simple transfer (mint -> commit -> settle):
4
+ // verified live across all three contracts (test/lib/singleSpend.test.ts) and byte-identical to the
5
+ // genuine sx golden (modulo the signature's low-S variant). Two caller requirements:
6
+ // • the spending tx MUST be version >= 2 (the contract asserts it from the preimage);
7
+ // • the template's UNLOCK_SCRIPT_SUFFIX must be the full compiled unlock (patched from the artifact by
8
+ // the build scripts) — a truncated suffix corrupts the optimal-sighash s-computation.
9
+ // The ancestor-reconstruction path (a settle reaching back over chains >= 4 txs, e.g. a coupon's 2nd
10
+ // hop) is implemented via singleAncestorPieces, validated against the canonical sx golden.
11
+ //
12
+ // All three compile to an IDENTICAL 37-arg unlock layout (no mintData / issuerPubKey /
13
+ // genesisOutpoint / miscData in the ancestor reconstruction):
14
+ //
15
+ // [0..25] ancestor pieces (26) — EMPTY for the simple transfer (mint->commit->settle); populated
16
+ // by singleAncestorPieces when a settle reaches back over a chain >= 4 txs (coupon 2nd hop).
17
+ // [26] fundOutpoint — the funding input's outpoint (36B)
18
+ // [27] changeOutput — serialised change output (value + varint len + script)
19
+ // [28] beneficiaryPubKeyHash — the next owner's 20-byte pkh
20
+ // [29] sig — checksig-format signature over the lock-only preimage
21
+ // [30] pubKey — signer's 33-byte compressed pubkey
22
+ // [31..36] ctxHeader, ctxCodeLen, ctxCodeUnlockScriptCode, ctxCodeLockScriptCode, ctxFooter,
23
+ // ctxCodeLockLen — the 6 BIP143 preimage pieces from splitCtx(ctx, 2)
24
+ //
25
+ // OCS subscript = `OP_CHECKSIGVERIFY OP_ENDIF` + lockingScript (the combined-checksig tail, 2-byte
26
+ // unlock-script-code prefix `ad68`), exactly as SimpleMultiBolt. splitCtx(ctx, 2) accordingly.
27
+ import { Script, UnlockingScript, TransactionSignature, Hash, } from "@bsv/sdk";
28
+ import { splitCtx, buildOutpoint, buildChangeOutput, createSignature, scriptChunksFromBin } from "../boltLib.js";
29
+ import { singleAncestorPieces } from "./singleAncestor.js";
30
+ /** Number of leading ancestor-reconstruction args in the NFT unlock layout. */
31
+ export const SINGLE_ANCESTOR_ARG_COUNT = 26;
32
+ const SIGNATURE_SCOPE = TransactionSignature.SIGHASH_FORKID | TransactionSignature.SIGHASH_ALL;
33
+ /** 26 empty ancestor pushes — the simple-transfer (and melt) case. */
34
+ export const emptySingleAncestorChunks = () => {
35
+ const out = [];
36
+ for (let i = 0; i < SINGLE_ANCESTOR_ARG_COUNT; i++)
37
+ out.push(...scriptChunksFromBin([]));
38
+ return out;
39
+ };
40
+ /**
41
+ * Build a ScriptTemplate-compatible unlocker for an NFT-family bolt spend (transfer commit/settle, and
42
+ * a back-reaching settle that reconstructs its ancestor commit). Requires tx version >= 2.
43
+ */
44
+ export function singleSpendUnlock(params) {
45
+ const { privateKey, beneficiaryPubKeyHash, unlockScriptSuffixASM, forceNoChange, forceNoFund, prevTxs } = params;
46
+ return {
47
+ sign: async (tx, inputIndex) => {
48
+ const input = tx.inputs[inputIndex];
49
+ const sourceTXID = input.sourceTXID || input.sourceTransaction?.id("hex");
50
+ if (!sourceTXID)
51
+ throw new Error("input sourceTXID or sourceTransaction required for signing");
52
+ const sourceSatoshis = params.sourceSatoshis ?? input.sourceTransaction?.outputs[input.sourceOutputIndex].satoshis;
53
+ if (sourceSatoshis === undefined)
54
+ throw new Error("sourceSatoshis or input sourceTransaction required");
55
+ const lockingScript = params.lockingScript ?? input.sourceTransaction?.outputs[input.sourceOutputIndex].lockingScript;
56
+ if (!lockingScript)
57
+ throw new Error("lockingScript or input sourceTransaction required");
58
+ // Detect a settle that reaches back to a prior token (needs the ancestor block). The simple
59
+ // mint->commit->settle lifecycle never does (txIdx <= 2): prevTxs at settle = [mint, commit].
60
+ // A back-reaching settle (e.g. a coupon's 2nd hop settleTx2 at txIdx 4) reconstructs the commit
61
+ // two hops back (prevTxs[txIdx-3]) where the current owner received the token.
62
+ const txIdx = (prevTxs?.length ?? 0);
63
+ const ancestorIdx = txIdx - 3;
64
+ const hasAncestor = ancestorIdx >= 1 && txIdx >= 4 && txIdx % 2 === 0;
65
+ const ancestorChunks = hasAncestor
66
+ ? singleAncestorPieces(prevTxs[ancestorIdx], params.leadingValuePushes ?? 0).flatMap((p) => scriptChunksFromBin(p))
67
+ : emptySingleAncestorChunks();
68
+ const otherInputs = tx.inputs.filter((_, i) => i !== inputIndex);
69
+ const ocsSubScript = new Script(Script.fromASM("OP_CHECKSIGVERIFY OP_ENDIF").chunks.concat(lockingScript.chunks));
70
+ const ctx = TransactionSignature.format({
71
+ sourceTXID,
72
+ sourceOutputIndex: input.sourceOutputIndex,
73
+ sourceSatoshis,
74
+ transactionVersion: tx.version,
75
+ otherInputs,
76
+ inputIndex,
77
+ outputs: tx.outputs,
78
+ inputSequence: input.sequence,
79
+ subscript: ocsSubScript,
80
+ lockTime: tx.lockTime,
81
+ scope: SIGNATURE_SCOPE,
82
+ });
83
+ const { ctxHeader, ctxCodeLen, ctxCodeUnlockScriptCode, ctxCodeLockScriptCode, ctxFooter, ctxCodeLockLen } = splitCtx(ctx, 2);
84
+ const ctxForSig = ctxHeader.concat(...[ctxCodeLockLen, ctxCodeLockScriptCode, ctxFooter]);
85
+ const { sigForScript, pubkeyForScript } = createSignature(privateKey, ctxForSig, SIGNATURE_SCOPE);
86
+ const fundInput = tx.inputs[tx.inputs.length - 1];
87
+ const fundOutpoint = forceNoFund
88
+ ? []
89
+ : buildOutpoint(fundInput.sourceTransaction, fundInput.sourceOutputIndex);
90
+ const changeOutput = forceNoChange ? [] : buildChangeOutput(tx, tx.outputs.length - 1);
91
+ return new UnlockingScript([
92
+ ...ancestorChunks, // [0..25]
93
+ ...scriptChunksFromBin(fundOutpoint), // [26]
94
+ ...scriptChunksFromBin(changeOutput), // [27]
95
+ ...scriptChunksFromBin(beneficiaryPubKeyHash), // [28]
96
+ ...scriptChunksFromBin(sigForScript), // [29]
97
+ ...scriptChunksFromBin(pubkeyForScript), // [30]
98
+ ...scriptChunksFromBin(ctxHeader), // [31]
99
+ ...scriptChunksFromBin(ctxCodeLen), // [32]
100
+ ...scriptChunksFromBin(ctxCodeUnlockScriptCode), // [33]
101
+ ...scriptChunksFromBin(ctxCodeLockScriptCode), // [34]
102
+ ...scriptChunksFromBin(ctxFooter), // [35]
103
+ ...scriptChunksFromBin(ctxCodeLockLen), // [36]
104
+ ...Script.fromASM(unlockScriptSuffixASM).chunks,
105
+ ]);
106
+ },
107
+ estimateLength: async () => 2000,
108
+ };
109
+ }
110
+ export { Hash };
@@ -0,0 +1,17 @@
1
+ import { Transaction, PrivateKey } from "@bsv/sdk";
2
+ export declare abstract class BOLT {
3
+ tx?: Transaction;
4
+ voutIdx?: number;
5
+ prevTxs: Transaction[];
6
+ pubKey: number[];
7
+ issuerPubKey: number[];
8
+ genesisOutpoint: number[];
9
+ privKey: PrivateKey;
10
+ mintData?: number[];
11
+ pubKeyHash?: number[];
12
+ constructor();
13
+ abstract mint(privKey: PrivateKey, sourceTransaction: Transaction, mintData?: string): any;
14
+ abstract commit(toPrivKey: PrivateKey): any;
15
+ abstract settle(toPrivKey: PrivateKey): any;
16
+ abstract transfer(toPrivKey: PrivateKey): any;
17
+ }
@@ -0,0 +1,9 @@
1
+ // Base BOLT Protocol Token class
2
+ export class BOLT {
3
+ constructor() {
4
+ this.prevTxs = []; // prior txs in the token's lineage
5
+ this.pubKey = [];
6
+ this.issuerPubKey = [];
7
+ this.genesisOutpoint = [];
8
+ }
9
+ }
@@ -0,0 +1,44 @@
1
+ import { Transaction, PrivateKey, TransactionOutput, TransactionInput } from "@bsv/sdk";
2
+ import { BOLT } from "./BOLT.js";
3
+ export type VerifierType = 'bsv';
4
+ export declare class SimpleMultiBOLT extends BOLT {
5
+ skipVerify: boolean;
6
+ verifier: VerifierType;
7
+ balance: number[];
8
+ balanceCommit: number[];
9
+ outputIndexN: number[];
10
+ mint(privKey: PrivateKey, sourceTransaction: Transaction, _mintData?: string, balance?: number[]): Promise<this>;
11
+ createTransferInputs: (toPrivKey: PrivateKey, _miscData: string, isCommitTx?: boolean, forceNoChange?: boolean, fundOverride?: TransactionInput | undefined, forceNoFund?: boolean) => (TransactionInput | {
12
+ sourceTransaction: Transaction;
13
+ sourceOutputIndex: number;
14
+ unlockingScriptTemplate: {
15
+ sign: (tx: Transaction, inputIndex: number) => Promise<import("@bsv/sdk").UnlockingScript>;
16
+ estimateLength: () => Promise<number>;
17
+ };
18
+ sequence: number;
19
+ })[];
20
+ createTransferOutputs: (toPrivKey: PrivateKey, isCommitTx?: boolean, forceNoChange?: boolean, customChangeScript?: any) => TransactionOutput[];
21
+ commit(toPrivKey: PrivateKey, commitTxMiscData?: string, forceNoChange?: boolean, fundOverride?: TransactionInput | undefined, forceNoFund?: boolean, customChangeScript?: any): Promise<this>;
22
+ settle(toPrivKey: PrivateKey, settleTxMiscData?: string, forceNoChange?: boolean, fundOverride?: TransactionInput | undefined, forceNoFund?: boolean, customChangeScript?: any): Promise<this>;
23
+ transfer(toPrivKey: PrivateKey, commitTxMiscData?: string, settleTxMiscData?: string, skipSettle?: boolean, forceNoChange?: boolean, fundOverride?: TransactionInput | undefined, forceNoFund?: boolean, customChangeScript?: any): Promise<this>;
24
+ private balanceToBigInt;
25
+ private bigIntToBalance;
26
+ private addBalances;
27
+ private subtractBalances;
28
+ private findProofVout;
29
+ private voutLE;
30
+ private signAndClean;
31
+ private getParentOutpoint;
32
+ merge(other: SimpleMultiBOLT, toKey: PrivateKey, fundingSource?: {
33
+ tx: Transaction;
34
+ vout: number;
35
+ key: PrivateKey;
36
+ }): Promise<SimpleMultiBOLT>;
37
+ split(toKeyA: PrivateKey, toKeyB: PrivateKey, splitBalanceCommit: number[], fundingSource?: {
38
+ tx: Transaction;
39
+ vout: number;
40
+ key: PrivateKey;
41
+ }): Promise<[SimpleMultiBOLT, SimpleMultiBOLT]>;
42
+ melt(meltPubKeyHash?: number[]): Promise<this>;
43
+ private verifyAndLogTransaction;
44
+ }