b017 0.0.0-b → 0.1.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.
Files changed (44) hide show
  1. package/CHANGELOG.md +280 -1
  2. package/README.md +120 -25
  3. package/dist/index.d.ts +15 -7
  4. package/dist/index.js +14 -5
  5. package/dist/lib/boltLib.d.ts +29 -3
  6. package/dist/lib/boltLib.js +60 -12
  7. package/dist/lib/genesis.d.ts +20 -0
  8. package/dist/lib/genesis.js +45 -0
  9. package/dist/lib/multi/multiBoltLib.d.ts +22 -2
  10. package/dist/lib/multi/multiBoltLib.js +111 -117
  11. package/dist/lib/scanner/beef.d.ts +11 -0
  12. package/dist/lib/scanner/beef.js +63 -0
  13. package/dist/lib/scanner/fingerprints.d.ts +12 -2
  14. package/dist/lib/scanner/fingerprints.js +44 -11
  15. package/dist/lib/scanner/verifyEvents.d.ts +84 -6
  16. package/dist/lib/scanner/verifyEvents.js +519 -44
  17. package/dist/lib/single/singleAncestor.d.ts +27 -3
  18. package/dist/lib/single/singleAncestor.js +49 -18
  19. package/dist/lib/single/singleSpend.d.ts +12 -3
  20. package/dist/lib/single/singleSpend.js +48 -16
  21. package/dist/tokens/BOLT.d.ts +6 -5
  22. package/dist/tokens/GenesisMultiBOLT.d.ts +29 -0
  23. package/dist/tokens/GenesisMultiBOLT.js +48 -0
  24. package/dist/tokens/MultiBOLT.d.ts +17 -11
  25. package/dist/tokens/MultiBOLT.js +79 -68
  26. package/dist/tokens/templates/AuthBolt.sx.template.d.ts +35 -0
  27. package/dist/tokens/templates/AuthBolt.sx.template.js +82 -0
  28. package/dist/tokens/templates/FixedMulti.sx.template.d.ts +13 -0
  29. package/dist/tokens/templates/FixedMulti.sx.template.js +23 -0
  30. package/dist/tokens/templates/MinSimple.sx.template.d.ts +10 -1
  31. package/dist/tokens/templates/MinSimple.sx.template.js +15 -1
  32. package/dist/tokens/templates/OpenMulti.sx.template.d.ts +13 -0
  33. package/dist/tokens/templates/OpenMulti.sx.template.js +23 -0
  34. package/dist/tokens/templates/SerialBolt.sx.template.d.ts +23 -0
  35. package/dist/tokens/templates/SerialBolt.sx.template.js +61 -0
  36. package/dist/tokens/templates/SimpleMulti.sx.template.d.ts +11 -5
  37. package/dist/tokens/templates/SimpleMulti.sx.template.js +30 -21
  38. package/dist/tokens/templates/pay2Proof.d.ts +2 -1
  39. package/dist/tokens/templates/pay2Proof.js +1 -1
  40. package/package.json +8 -3
  41. package/dist/tokens/templates/MinSimpleBalance.sx.template.d.ts +0 -24
  42. package/dist/tokens/templates/MinSimpleBalance.sx.template.js +0 -59
  43. package/dist/tokens/templates/MinSimpleDiscount.sx.template.d.ts +0 -23
  44. package/dist/tokens/templates/MinSimpleDiscount.sx.template.js +0 -58
@@ -1,6 +1,28 @@
1
- import { Script, Spend, Transaction, PrivateKey } from "@bsv/sdk";
1
+ import { Script, Spend, Transaction, PrivateKey, Signature, UnlockingScript } from "@bsv/sdk";
2
+ /** Signs on behalf of a key the caller may not hold. `sign(msg)` returns an ECDSA Signature over
3
+ * sha256(msg) — matching PrivateKey.sign — and may be async. `publicKey` is the 33-byte compressed key. */
4
+ export interface Signer {
5
+ publicKey: number[];
6
+ sign: (msg: number[]) => Signature | Promise<Signature>;
7
+ }
8
+ /** A recipient of a token: a PrivateKey or Signer the caller controls (so the builder can continue as
9
+ * the new owner), or just a compressed public key (33 bytes) when paying a third party. */
10
+ export type Recipient = PrivateKey | Signer | number[];
11
+ /** Normalise a PrivateKey or Signer to a Signer. */
12
+ export declare const toSigner: (x: PrivateKey | Signer) => Signer;
13
+ /** The recipient's compressed public key, whichever form it was given in. */
14
+ export declare const recipientPubKey: (r: Recipient) => number[];
15
+ /** A Signer for the recipient if the caller controls its key (so the builder can spend the token on a
16
+ * later hop); undefined when only a public key was given (the token has left this holder). */
17
+ export declare const recipientSigner: (r: Recipient) => Signer | undefined;
18
+ /**
19
+ * Verify every input of a tx with the @bsv/sdk Spend engine. THROWS on any failure (a missing source or unlocking
20
+ * script, a failing script - `Spend.validate()` throws rather than returning false - an output with no amount, or
21
+ * outputs worth more than inputs unless `skipOutputCheck`), so when it returns, `valid` is always `true`. The
22
+ * `{ valid, scriptExecutions }` shape is kept for existing callers.
23
+ */
2
24
  export declare const verifyTx: (tx: Transaction, skipOutputCheck?: boolean) => {
3
- valid: boolean;
25
+ valid: true;
4
26
  scriptExecutions: {
5
27
  spend: Spend;
6
28
  valid: boolean;
@@ -8,9 +30,13 @@ export declare const verifyTx: (tx: Transaction, skipOutputCheck?: boolean) => {
8
30
  };
9
31
  export declare const buildOutpoint: (tx: Transaction, outputIndex: number) => number[];
10
32
  export declare const buildChangeOutput: (tx: Transaction, outputIndex: number) => number[];
11
- export declare const createSignature: (privateKey: PrivateKey, preimage: number[], signatureScope: number) => {
33
+ export declare const createSignature: (signerOrKey: PrivateKey | Signer, preimage: number[], signatureScope: number) => Promise<{
12
34
  sigForScript: number[];
13
35
  pubkeyForScript: number[];
36
+ }>;
37
+ export declare const p2pkhUnlock: (signerOrKey: PrivateKey | Signer) => {
38
+ sign: (tx: Transaction, inputIndex: number) => Promise<UnlockingScript>;
39
+ estimateLength: () => Promise<number>;
14
40
  };
15
41
  export declare const splitCtx: (ctx: number[], unlockBytesLen?: number) => {
16
42
  ctxHeader: number[];
@@ -1,9 +1,24 @@
1
1
  // boltLib.ts — layout-agnostic helpers shared by both token streams:
2
2
  // verifyTx (bsv Spend), buildOutpoint, buildChangeOutput, createSignature, splitCtx,
3
3
  // and the tx-field primitives (le32/le64, spentOutpoint, vin*/vout*, …).
4
- import { Script, Spend, Utils, TransactionSignature, Hash } from "@bsv/sdk";
4
+ import { Script, Spend, Utils, TransactionSignature, Hash, UnlockingScript } from "@bsv/sdk";
5
5
  const { Reader, Writer } = Utils;
6
- // Verify every input of a tx with the @bsv/sdk Spend engine.
6
+ const isPrivateKey = (x) => !!x && typeof x.toPublicKey === "function" && typeof x.sign === "function";
7
+ /** Normalise a PrivateKey or Signer to a Signer. */
8
+ export const toSigner = (x) => isPrivateKey(x)
9
+ ? { publicKey: x.toPublicKey().encode(true), sign: (msg) => x.sign(msg) }
10
+ : x;
11
+ /** The recipient's compressed public key, whichever form it was given in. */
12
+ export const recipientPubKey = (r) => Array.isArray(r) ? r : isPrivateKey(r) ? r.toPublicKey().encode(true) : r.publicKey;
13
+ /** A Signer for the recipient if the caller controls its key (so the builder can spend the token on a
14
+ * later hop); undefined when only a public key was given (the token has left this holder). */
15
+ export const recipientSigner = (r) => Array.isArray(r) ? undefined : toSigner(r);
16
+ /**
17
+ * Verify every input of a tx with the @bsv/sdk Spend engine. THROWS on any failure (a missing source or unlocking
18
+ * script, a failing script - `Spend.validate()` throws rather than returning false - an output with no amount, or
19
+ * outputs worth more than inputs unless `skipOutputCheck`), so when it returns, `valid` is always `true`. The
20
+ * `{ valid, scriptExecutions }` shape is kept for existing callers.
21
+ */
7
22
  export const verifyTx = (tx, skipOutputCheck = false) => {
8
23
  let inputTotal = 0;
9
24
  const txid = tx.id("hex");
@@ -13,6 +28,7 @@ export const verifyTx = (tx, skipOutputCheck = false) => {
13
28
  if (typeof input.sourceTransaction !== "object") {
14
29
  throw new Error(`Verification failed: input ${i} of ${txid} is missing its source transaction.`);
15
30
  }
31
+ /* v8 ignore next 3 -- tx.id("hex") at the top of verifyTx already throws on an input with no unlocking script */
16
32
  if (typeof input.unlockingScript !== "object") {
17
33
  throw new Error(`Verification failed: input ${i} of ${txid} is missing its unlocking script.`);
18
34
  }
@@ -30,15 +46,12 @@ export const verifyTx = (tx, skipOutputCheck = false) => {
30
46
  transactionVersion: tx.version,
31
47
  otherInputs,
32
48
  unlockingScript: input.unlockingScript,
33
- inputSequence: input.sequence || 0xffffffff,
49
+ inputSequence: input.sequence ?? 0xffffffff,
34
50
  inputIndex: i,
35
51
  outputs: tx.outputs,
36
52
  lockTime: tx.lockTime,
37
53
  });
38
- const valid = spend.validate();
39
- scriptExecutions.push({ spend, valid });
40
- if (!valid)
41
- return { valid: false, scriptExecutions };
54
+ scriptExecutions.push({ spend, valid: spend.validate() }); // throws on a failing script
42
55
  }
43
56
  let outputTotal = 0;
44
57
  for (const out of tx.outputs) {
@@ -69,13 +82,48 @@ export const buildChangeOutput = (tx, outputIndex) => {
69
82
  writer.write(scriptBin);
70
83
  return writer.toArray();
71
84
  };
72
- // Sign a preimage (signs sha256(preimage); the engine double-hashes) -> checksig-format sig + pubkey.
73
- export const createSignature = (privateKey, preimage, signatureScope) => {
74
- const rawSignature = privateKey.sign(Hash.sha256(preimage));
85
+ // Sign a preimage (the signer signs sha256(preimage); the engine double-hashes) -> checksig-format
86
+ // sig + pubkey. Accepts a PrivateKey or a Signer; async because a Signer may be a remote wallet.
87
+ export const createSignature = async (signerOrKey, preimage, signatureScope) => {
88
+ const signer = toSigner(signerOrKey);
89
+ const rawSignature = await signer.sign(Hash.sha256(preimage));
75
90
  const sig = new TransactionSignature(rawSignature.r, rawSignature.s, signatureScope);
76
91
  const sigForScript = sig.toChecksigFormat();
77
- const pubkeyForScript = privateKey.toPublicKey().encode(true);
78
- return { sigForScript, pubkeyForScript };
92
+ return { sigForScript, pubkeyForScript: signer.publicKey };
93
+ };
94
+ // A P2PKH unlock driven by a Signer, for funding inputs the builder spends. Byte-identical to the SDK's
95
+ // P2PKH().unlock for a PrivateKey, but accepts a Signer so wallet-held funding works in the same pass.
96
+ export const p2pkhUnlock = (signerOrKey) => {
97
+ const signer = toSigner(signerOrKey);
98
+ const scope = TransactionSignature.SIGHASH_FORKID | TransactionSignature.SIGHASH_ALL;
99
+ return {
100
+ sign: async (tx, inputIndex) => {
101
+ const input = tx.inputs[inputIndex];
102
+ const src = input.sourceTransaction?.outputs[input.sourceOutputIndex];
103
+ const sourceTXID = input.sourceTXID ?? input.sourceTransaction?.id("hex");
104
+ if (!sourceTXID || !src)
105
+ throw new Error("p2pkhUnlock requires the input's source transaction");
106
+ const preimage = TransactionSignature.format({
107
+ sourceTXID,
108
+ sourceOutputIndex: input.sourceOutputIndex,
109
+ sourceSatoshis: src.satoshis,
110
+ transactionVersion: tx.version,
111
+ otherInputs: tx.inputs.filter((_, i) => i !== inputIndex),
112
+ inputIndex,
113
+ outputs: tx.outputs,
114
+ inputSequence: input.sequence,
115
+ subscript: src.lockingScript,
116
+ lockTime: tx.lockTime,
117
+ scope,
118
+ });
119
+ const { sigForScript, pubkeyForScript } = await createSignature(signer, preimage, scope);
120
+ return new UnlockingScript([
121
+ { op: sigForScript.length, data: sigForScript },
122
+ { op: pubkeyForScript.length, data: pubkeyForScript },
123
+ ]);
124
+ },
125
+ estimateLength: async () => 108,
126
+ };
79
127
  };
80
128
  // Split a BIP143 preimage into header(104) + scriptCodeLen + unlockScriptCode + lockScriptCode +
81
129
  // footer(52) + lockLen. unlockBytesLen = bytes of unlock-script-code prefix (2 for SimpleMultiBolt).
@@ -0,0 +1,20 @@
1
+ import { Transaction } from "@bsv/sdk";
2
+ export declare const NULL_OUTPOINT: readonly number[];
3
+ /** mintData is pushed with at most PUSHDATA1 (the covenant's canonical skip is capped there). */
4
+ export declare const MINT_DATA_MAX_BYTES = 255;
5
+ /** The 36-byte outpoint txid(LE) || vout(LE32). */
6
+ export declare const outpointOf: (tx: Transaction, vout: number) => number[];
7
+ export interface GenesisFieldInput {
8
+ /** The token tx this output's vin0 spends, or undefined for a mint. */
9
+ prevTx?: Transaction;
10
+ /** Which output of prevTx is that token. */
11
+ prevVoutIdx?: number;
12
+ /** Lock chunk index of parentOutpoint in this contract (FixedBolt/OpenBolt 10, SerialBolt 5). */
13
+ parentIdx: number;
14
+ /** OpenBolt merge commit: re-root to vin0's token outpoint. */
15
+ reroot?: boolean;
16
+ }
17
+ /** Field 0 (genesis / LMG) for a new token output. */
18
+ export declare function genesisFieldFor({ prevTx, prevVoutIdx, parentIdx, reroot }: GenesisFieldInput): number[];
19
+ /** Field 1 (mintData) for a new token output: the issuer's bytes on the mint, empty (OP_0) after. */
20
+ export declare function mintDataFor(isMint: boolean, mintData?: number[]): number[];
@@ -0,0 +1,45 @@
1
+ // genesis.ts
2
+ // The two leading lock pushes of the genesis family (FixedBolt, OpenBolt, SerialBolt; genesis layout v3):
3
+ //
4
+ // field 0 genesisOutpoint (FixedBolt, SerialBolt) | lastMergeOrGenesisOutpoint (OpenBolt), 36 bytes
5
+ // - the MINT output carries a null (36 zero bytes) field;
6
+ // - the GENESIS SPEND (the first spend of the mint) writes the mint outpoint it spends;
7
+ // - OpenBolt only: a MERGE COMMIT re-roots it to vin0's token outpoint (which is also the merge
8
+ // output's parentOutpoint);
9
+ // - every other hop copies it unchanged.
10
+ // field 1 mintData: the issuer's bytes (0..255) on the MINT only; OP_0 on every later output.
11
+ //
12
+ // The covenant enforces each rule; this computes the values a builder must write (the same rules the
13
+ // sibling toolchain's simulator stamps onto its reference chains).
14
+ import { Utils } from "@bsv/sdk";
15
+ export const NULL_OUTPOINT = Object.freeze(new Array(36).fill(0x00));
16
+ /** mintData is pushed with at most PUSHDATA1 (the covenant's canonical skip is capped there). */
17
+ export const MINT_DATA_MAX_BYTES = 255;
18
+ /** The 36-byte outpoint txid(LE) || vout(LE32). */
19
+ export const outpointOf = (tx, vout) => {
20
+ const w = new Utils.Writer();
21
+ w.write(tx.hash());
22
+ w.writeUInt32LE(vout);
23
+ return w.toArray();
24
+ };
25
+ const isNull = (b) => !b || b.length === 0 || b.every((x) => x === 0);
26
+ /** Field 0 (genesis / LMG) for a new token output. */
27
+ export function genesisFieldFor({ prevTx, prevVoutIdx = 0, parentIdx, reroot = false }) {
28
+ if (!prevTx)
29
+ return [...NULL_OUTPOINT]; // the mint
30
+ const prevLock = prevTx.outputs[prevVoutIdx].lockingScript;
31
+ const prevParent = prevLock.chunks[parentIdx]?.data;
32
+ if (isNull(prevParent))
33
+ return outpointOf(prevTx, prevVoutIdx); // genesis spend: the mint outpoint it spends
34
+ if (reroot)
35
+ return outpointOf(prevTx, prevVoutIdx); // OpenBolt merge commit: vin0's token outpoint
36
+ return [...prevLock.chunks[0].data]; // copied (a genesis-family token always carries the 36-byte field)
37
+ }
38
+ /** Field 1 (mintData) for a new token output: the issuer's bytes on the mint, empty (OP_0) after. */
39
+ export function mintDataFor(isMint, mintData = []) {
40
+ if (!isMint)
41
+ return [];
42
+ if (mintData.length > MINT_DATA_MAX_BYTES)
43
+ throw new Error(`mintData is ${mintData.length} bytes; at most ${MINT_DATA_MAX_BYTES} (PUSHDATA1)`);
44
+ return [...mintData];
45
+ }
@@ -1,4 +1,24 @@
1
1
  import { Transaction } from "@bsv/sdk";
2
+ /** How a fungible contract lays out its scriptSig ancestor pieces and its lock pushes. */
3
+ export interface MultiLayout {
4
+ readonly name: string;
5
+ /** Ancestor piece names, per ancestor (TxA then TxB use the same list). */
6
+ readonly pieces: readonly string[];
7
+ /** Leading lock pushes before the SimpleMultiBolt fields (0 for SMB, 2 for the genesis family). */
8
+ readonly leading: number;
9
+ }
10
+ /** Unlock chunk index where a token spend's own (current-tx) args start = 2 x pieces. */
11
+ export declare const skipOf: (l: MultiLayout) => number;
12
+ /** Unlock chunk index of ctxHeader: skip + 5 interop + fund, change, pkh1, pkh2, nextBalanceCommit,
13
+ * nextTxoType, inputIndexN, sig, pubKey. */
14
+ export declare const args2ctxOf: (l: MultiLayout) => number;
15
+ /** Lock chunk index of txoType. */
16
+ export declare const txoTypeIdxOf: (l: MultiLayout) => number;
2
17
  export declare const PIECE_NAMES: string[];
3
- export declare const ancestorPiece: (name: string, tx: Transaction) => number[];
4
- export declare const createEmptyFungibleAncestorChunksSMB: () => any[];
18
+ export declare const SIMPLE_MULTI_LAYOUT: MultiLayout;
19
+ /** FixedBolt: + the ancestor spent token's mintData after each CTXHeader (77 pieces, skip 154). */
20
+ export declare const FIXED_BOLT_LAYOUT: MultiLayout;
21
+ /** OpenBolt: + each spent token's LMG before its mintData, and the rebuilt output's LMG (80 pieces, skip 160). */
22
+ export declare const OPEN_BOLT_LAYOUT: MultiLayout;
23
+ export declare const ancestorPiece: (name: string, tx: Transaction, layout?: MultiLayout) => number[];
24
+ export declare const createEmptyFungibleAncestorChunksSMB: (layout?: MultiLayout) => any[];
@@ -1,28 +1,39 @@
1
1
  // multiBoltLib.ts
2
- // SimpleMultiBolt-specific ancestor reconstruction + CTX helpers.
2
+ // Fungible-family ancestor reconstruction + CTX helpers: SimpleMultiBolt and the genesis family
3
+ // (FixedBolt, OpenBolt), each described by a MultiLayout.
4
+ //
5
+ // FixedBolt / OpenBolt (genesis layout v3) put two leading lock pushes before the SimpleMultiBolt fields:
6
+ // genesisOutpoint | lastMergeOrGenesisOutpoint (36 B, null on the mint), then mintData (issuer bytes on the
7
+ // mint only, OP_0 after). So every lock / CTX-scriptCode field index is +2, and the ancestor pieces gain
8
+ // Vin{1,2}CTXMintData (FixedBolt: 77 per ancestor, skip 154) plus Vin{1,2}CTXLmg and Vout1Lmg (OpenBolt: 80,
9
+ // skip 160). Piece semantics mirror the sibling toolchain's simulator (the source of truth).
3
10
  //
4
11
  // SimpleMultiBolt is the optimised fungible contract: 16-byte balance, mandatory change/funding.
5
12
  // - 11 lock data chunks.
6
- // - 198 unlock args; 89 ancestor pieces per ancestor.
13
+ // - 170 unlock args; 75 ancestor pieces per ancestor. (Was 198/89 until the dead ancestor args - the
14
+ // S2-unread issuer keys and the unreachable has2TokenOutputs Vout2* args - were removed.)
7
15
  //
8
16
  // Layout constants:
9
- // - ctxHeader sits at unlock chunk index 192 -> ARGS2CTX_SMB = 192
17
+ // - ctxHeader sits at unlock chunk index 164 -> ARGS2CTX_SMB = 164
10
18
  // - lock data-push count -> PUSHDATAS_SMB = 11
11
- // - live section start in a token unlock script -> SKIP_SMB = 178
19
+ // - live section start in a token unlock script -> SKIP_SMB = 150
12
20
  // - txoType lock chunk index -> TXOTYPE_IDX_SMB = 6
13
21
  //
14
22
  // Self-contained: depends only on @bsv/sdk (no sx tooling at runtime).
15
23
  import { Script, Utils } from "@bsv/sdk";
16
24
  import { txVersion, txLockTime, spentOutpoint, vinChunk, vinSequence, vinScript, voutChunk, outputValue, outputScript, scriptChunksFromBin, } from "../boltLib.js";
17
25
  const { Reader, Writer } = Utils;
18
- const ARGS2CTX_SMB = 192;
19
- const PUSHDATAS_SMB = 11;
20
- const SKIP_SMB = 178;
21
- const TXOTYPE_IDX_SMB = 6;
26
+ /** Unlock chunk index where a token spend's own (current-tx) args start = 2 x pieces. */
27
+ export const skipOf = (l) => 2 * l.pieces.length;
28
+ /** Unlock chunk index of ctxHeader: skip + 5 interop + fund, change, pkh1, pkh2, nextBalanceCommit,
29
+ * nextTxoType, inputIndexN, sig, pubKey. */
30
+ export const args2ctxOf = (l) => skipOf(l) + 14;
31
+ /** Lock chunk index of txoType. */
32
+ export const txoTypeIdxOf = (l) => 6 + l.leading;
22
33
  // ---- CTX reconstruction from a prior token tx's vin unlocking script ----
23
34
  // ctxHeader is at ARGS2CTX_SMB; ctxCodeLockScriptCode/footer/lockLen at +3/+4/+5.
24
35
  // piece 0 = ctxHeader (104 bytes); piece 2 = ctxFooter (the bytes after the scriptCode).
25
- const getVinCTXPieceSMB = (tx, vinIndex, piece) => {
36
+ const getVinCTXPieceSMB = (tx, vinIndex, piece, ARGS2CTX_SMB) => {
26
37
  const w = new Utils.Writer();
27
38
  const inputScript = tx.inputs[vinIndex]?.unlockingScript;
28
39
  if (!inputScript?.chunks?.[ARGS2CTX_SMB])
@@ -49,8 +60,8 @@ const getVinCTXPieceSMB = (tx, vinIndex, piece) => {
49
60
  return w.toArray();
50
61
  };
51
62
  // Extract a single committed lock-data arg out of the reconstructed CTX scriptCode.
52
- // argIdx indexes the 11 SMB lock data chunks (balance=0 ... issuerPubKey=10).
53
- const getVinCTXDataArgSMB = (tx, vinIndex, argIdx) => {
63
+ // argIdx indexes the lock data chunks (SMB: balance=0 ... issuerPubKey=10; the genesis family +2).
64
+ const getVinCTXDataArgSMB = (tx, vinIndex, argIdx, ARGS2CTX_SMB) => {
54
65
  const inputScript = tx.inputs[vinIndex]?.unlockingScript;
55
66
  if (!inputScript?.chunks?.[ARGS2CTX_SMB])
56
67
  return [];
@@ -78,13 +89,13 @@ const getVinCTXDataArgSMB = (tx, vinIndex, argIdx) => {
78
89
  };
79
90
  // SimpleMultiBolt action bytes (no swap): 20 transferSettle, 21 transferCommit,
80
91
  // 22 splitSettle, 23 splitCommit, 24 mergeSettle, 25 mergeCommit.
81
- const determineTxTypeSMB = (tx) => {
92
+ const determineTxTypeSMB = (tx, layout) => {
82
93
  const firstToken = tx.outputs[0];
83
- const txoType = firstToken.lockingScript.chunks[TXOTYPE_IDX_SMB];
94
+ const txoType = firstToken.lockingScript.chunks[txoTypeIdxOf(layout)];
84
95
  const typeByte = txoType?.data?.[0] || -1;
85
96
  return typeByte.toString(16);
86
97
  };
87
- // The 89 SimpleMultiBolt ancestor piece names per ancestor.
98
+ // The 75 SimpleMultiBolt ancestor piece names per ancestor.
88
99
  export const PIECE_NAMES = [
89
100
  "Version",
90
101
  "Vin1Outpoint",
@@ -97,7 +108,7 @@ export const PIECE_NAMES = [
97
108
  "Vin1CTXPubKeyHash", "Vin1CTXPubKeyHashCommit", "Vin1CTXPubKeyHashCommit2",
98
109
  "Vin1CTXOtherGrandparentOutpoint",
99
110
  "Vin1CTXTxoType", "Vin1CTXOutputIndexN",
100
- "Vin1CTXParentOutpoint", "Vin1CTXGrandparentOutpoint", "Vin1CTXIssuerPubKey",
111
+ "Vin1CTXParentOutpoint", "Vin1CTXGrandparentOutpoint",
101
112
  "Vin1CTXFooter", "Vin1NSequence",
102
113
  "Vin2Outpoint",
103
114
  "Vin2GrandparentProofVoutIdx", "Vin2InteropProofVoutIdx",
@@ -109,27 +120,47 @@ export const PIECE_NAMES = [
109
120
  "Vin2CTXPubKeyHash", "Vin2CTXPubKeyHashCommit", "Vin2CTXPubKeyHashCommit2",
110
121
  "Vin2CTXOtherGrandparentOutpoint",
111
122
  "Vin2CTXTxoType", "Vin2CTXOutputIndexN",
112
- "Vin2CTXParentOutpoint", "Vin2CTXGrandparentOutpoint", "Vin2CTXIssuerPubKey",
123
+ "Vin2CTXParentOutpoint", "Vin2CTXGrandparentOutpoint",
113
124
  "Vin2CTXFooter", "Vin2NSequence",
114
125
  "VinFundOutpoint", "VinFundScript", "VinFundNSequence",
115
126
  "Vout1Balance", "Vout1BalanceCommit",
116
127
  "Vout1PubKeyHash", "Vout1PubKeyHashCommit", "Vout1PubKeyHashCommit2",
117
128
  "Vout1OtherGrandparentOutpoint",
118
129
  "Vout1TxoType", "Vout1OutputIndexN",
119
- "Vout1ParentOutpoint", "Vout1GrandparentOutpoint", "Vout1IssuerPubKey",
120
- "Vout2Balance", "Vout2BalanceCommit",
121
- "Vout2PubKeyHash", "Vout2PubKeyHashCommit", "Vout2PubKeyHashCommit2",
122
- "Vout2OtherGrandparentOutpoint",
123
- "Vout2TxoType", "Vout2OutputIndexN",
124
- "Vout2ParentOutpoint", "Vout2GrandparentOutpoint", "Vout2IssuerPubKey",
130
+ "Vout1ParentOutpoint", "Vout1GrandparentOutpoint",
125
131
  "ProofPubKeyHash1", "ProofPubKeyHash2",
126
132
  "ChangeValue", "ChangeScript", "NLockTime",
127
133
  ];
128
- // Extract one named ancestor piece from a SimpleMultiBolt transaction.
129
- export const ancestorPiece = (name, tx) => {
134
+ const insertAfter = (list, anchor, ...names) => {
135
+ const i = list.indexOf(anchor);
136
+ return [...list.slice(0, i + 1), ...names, ...list.slice(i + 1)];
137
+ };
138
+ const insertBefore = (list, anchor, ...names) => {
139
+ const i = list.indexOf(anchor);
140
+ return [...list.slice(0, i), ...names, ...list.slice(i)];
141
+ };
142
+ export const SIMPLE_MULTI_LAYOUT = { name: "SimpleMultiBolt", pieces: PIECE_NAMES, leading: 0 };
143
+ /** FixedBolt: + the ancestor spent token's mintData after each CTXHeader (77 pieces, skip 154). */
144
+ export const FIXED_BOLT_LAYOUT = {
145
+ name: "FixedBolt",
146
+ pieces: insertAfter(insertAfter(PIECE_NAMES, "Vin1CTXHeader", "Vin1CTXMintData"), "Vin2CTXHeader", "Vin2CTXMintData"),
147
+ leading: 2,
148
+ };
149
+ /** OpenBolt: + each spent token's LMG before its mintData, and the rebuilt output's LMG (80 pieces, skip 160). */
150
+ export const OPEN_BOLT_LAYOUT = {
151
+ name: "OpenBolt",
152
+ pieces: insertBefore(insertAfter(insertAfter(PIECE_NAMES, "Vin1CTXHeader", "Vin1CTXLmg", "Vin1CTXMintData"), "Vin2CTXHeader", "Vin2CTXLmg", "Vin2CTXMintData"), "Vout1Balance", "Vout1Lmg"),
153
+ leading: 2,
154
+ };
155
+ // Extract one named ancestor piece from a fungible-family transaction (SimpleMultiBolt by default).
156
+ export const ancestorPiece = (name, tx, layout = SIMPLE_MULTI_LAYOUT) => {
130
157
  let res = [];
131
158
  const ancestorTx = tx;
132
- const txType = determineTxTypeSMB(ancestorTx);
159
+ const SKIP_SMB = skipOf(layout);
160
+ const A2C = args2ctxOf(layout);
161
+ const L = layout.leading;
162
+ const ctxArg = (vin, k) => getVinCTXDataArgSMB(ancestorTx, vin, k + L, A2C);
163
+ const txType = determineTxTypeSMB(ancestorTx, layout);
133
164
  const hasTwoTokenInputs = txType === "25"; // mergeCommit (swap removed)
134
165
  const hasTwoBolts = txType === "23"; // splitCommit
135
166
  const fundVinIdx = ancestorTx.inputs.length - 1;
@@ -188,43 +219,47 @@ export const ancestorPiece = (name, tx) => {
188
219
  res = vinChunk(ancestorTx, 0, SKIP_SMB + 13);
189
220
  break;
190
221
  case "Vin1CTXHeader":
191
- res = getVinCTXPieceSMB(ancestorTx, 0, 0);
222
+ res = getVinCTXPieceSMB(ancestorTx, 0, 0, A2C);
223
+ break;
224
+ // genesis family: the ancestor spent token's leading pushes (lock chunk 0 = genesis / LMG, 1 = mintData)
225
+ case "Vin1CTXLmg":
226
+ res = getVinCTXDataArgSMB(ancestorTx, 0, 0, A2C);
227
+ break;
228
+ case "Vin1CTXMintData":
229
+ res = getVinCTXDataArgSMB(ancestorTx, 0, 1, A2C);
192
230
  break;
193
231
  case "Vin1CTXBalance":
194
- res = getVinCTXDataArgSMB(ancestorTx, 0, 0);
232
+ res = ctxArg(0, 0);
195
233
  break;
196
234
  case "Vin1CTXBalanceCommit":
197
- res = getVinCTXDataArgSMB(ancestorTx, 0, 1);
235
+ res = ctxArg(0, 1);
198
236
  break;
199
237
  case "Vin1CTXPubKeyHash":
200
- res = getVinCTXDataArgSMB(ancestorTx, 0, 2);
238
+ res = ctxArg(0, 2);
201
239
  break;
202
240
  case "Vin1CTXPubKeyHashCommit":
203
- res = getVinCTXDataArgSMB(ancestorTx, 0, 3);
241
+ res = ctxArg(0, 3);
204
242
  break;
205
243
  case "Vin1CTXPubKeyHashCommit2":
206
- res = getVinCTXDataArgSMB(ancestorTx, 0, 4);
244
+ res = ctxArg(0, 4);
207
245
  break;
208
246
  case "Vin1CTXOtherGrandparentOutpoint":
209
- res = getVinCTXDataArgSMB(ancestorTx, 0, 5);
247
+ res = ctxArg(0, 5);
210
248
  break;
211
249
  case "Vin1CTXTxoType":
212
- res = getVinCTXDataArgSMB(ancestorTx, 0, 6);
250
+ res = ctxArg(0, 6);
213
251
  break;
214
252
  case "Vin1CTXOutputIndexN":
215
- res = getVinCTXDataArgSMB(ancestorTx, 0, 7);
253
+ res = ctxArg(0, 7);
216
254
  break;
217
255
  case "Vin1CTXParentOutpoint":
218
- res = getVinCTXDataArgSMB(ancestorTx, 0, 8);
256
+ res = ctxArg(0, 8);
219
257
  break;
220
258
  case "Vin1CTXGrandparentOutpoint":
221
- res = getVinCTXDataArgSMB(ancestorTx, 0, 9);
222
- break;
223
- case "Vin1CTXIssuerPubKey":
224
- res = getVinCTXDataArgSMB(ancestorTx, 0, 10);
259
+ res = ctxArg(0, 9);
225
260
  break;
226
261
  case "Vin1CTXFooter":
227
- res = getVinCTXPieceSMB(ancestorTx, 0, 2);
262
+ res = getVinCTXPieceSMB(ancestorTx, 0, 2, A2C);
228
263
  break;
229
264
  case "Vin1NSequence":
230
265
  res = vinSequence(ancestorTx, 0);
@@ -292,55 +327,59 @@ export const ancestorPiece = (name, tx) => {
292
327
  break;
293
328
  case "Vin2CTXHeader":
294
329
  if (hasTwoTokenInputs)
295
- res = getVinCTXPieceSMB(ancestorTx, 1, 0);
330
+ res = getVinCTXPieceSMB(ancestorTx, 1, 0, A2C);
331
+ break;
332
+ case "Vin2CTXLmg":
333
+ if (hasTwoTokenInputs)
334
+ res = getVinCTXDataArgSMB(ancestorTx, 1, 0, A2C);
335
+ break;
336
+ case "Vin2CTXMintData":
337
+ if (hasTwoTokenInputs)
338
+ res = getVinCTXDataArgSMB(ancestorTx, 1, 1, A2C);
296
339
  break;
297
340
  case "Vin2CTXBalance":
298
341
  if (hasTwoTokenInputs)
299
- res = getVinCTXDataArgSMB(ancestorTx, 1, 0);
342
+ res = ctxArg(1, 0);
300
343
  break;
301
344
  case "Vin2CTXBalanceCommit":
302
345
  if (hasTwoTokenInputs)
303
- res = getVinCTXDataArgSMB(ancestorTx, 1, 1);
346
+ res = ctxArg(1, 1);
304
347
  break;
305
348
  case "Vin2CTXPubKeyHash":
306
349
  if (hasTwoTokenInputs)
307
- res = getVinCTXDataArgSMB(ancestorTx, 1, 2);
350
+ res = ctxArg(1, 2);
308
351
  break;
309
352
  case "Vin2CTXPubKeyHashCommit":
310
353
  if (hasTwoTokenInputs)
311
- res = getVinCTXDataArgSMB(ancestorTx, 1, 3);
354
+ res = ctxArg(1, 3);
312
355
  break;
313
356
  case "Vin2CTXPubKeyHashCommit2":
314
357
  if (hasTwoTokenInputs)
315
- res = getVinCTXDataArgSMB(ancestorTx, 1, 4);
358
+ res = ctxArg(1, 4);
316
359
  break;
317
360
  case "Vin2CTXOtherGrandparentOutpoint":
318
361
  if (hasTwoTokenInputs)
319
- res = getVinCTXDataArgSMB(ancestorTx, 1, 5);
362
+ res = ctxArg(1, 5);
320
363
  break;
321
364
  case "Vin2CTXTxoType":
322
365
  if (hasTwoTokenInputs)
323
- res = getVinCTXDataArgSMB(ancestorTx, 1, 6);
366
+ res = ctxArg(1, 6);
324
367
  break;
325
368
  case "Vin2CTXOutputIndexN":
326
369
  if (hasTwoTokenInputs)
327
- res = getVinCTXDataArgSMB(ancestorTx, 1, 7);
370
+ res = ctxArg(1, 7);
328
371
  break;
329
372
  case "Vin2CTXParentOutpoint":
330
373
  if (hasTwoTokenInputs)
331
- res = getVinCTXDataArgSMB(ancestorTx, 1, 8);
374
+ res = ctxArg(1, 8);
332
375
  break;
333
376
  case "Vin2CTXGrandparentOutpoint":
334
377
  if (hasTwoTokenInputs)
335
- res = getVinCTXDataArgSMB(ancestorTx, 1, 9);
336
- break;
337
- case "Vin2CTXIssuerPubKey":
338
- if (hasTwoTokenInputs)
339
- res = getVinCTXDataArgSMB(ancestorTx, 1, 10);
378
+ res = ctxArg(1, 9);
340
379
  break;
341
380
  case "Vin2CTXFooter":
342
381
  if (hasTwoTokenInputs)
343
- res = getVinCTXPieceSMB(ancestorTx, 1, 2);
382
+ res = getVinCTXPieceSMB(ancestorTx, 1, 2, A2C);
344
383
  break;
345
384
  case "Vin2NSequence":
346
385
  if (hasTwoTokenInputs)
@@ -360,83 +399,38 @@ export const ancestorPiece = (name, tx) => {
360
399
  res = vinSequence(ancestorTx, fundVinIdx);
361
400
  break;
362
401
  // ---- Vout1 (first token output, always present) ----
363
- case "Vout1Balance":
402
+ case "Vout1Lmg":
364
403
  res = voutChunk(ancestorTx, 0, 0);
404
+ break; // OpenBolt: the rebuilt output's LMG
405
+ case "Vout1Balance":
406
+ res = voutChunk(ancestorTx, 0, 0 + L);
365
407
  break;
366
408
  case "Vout1BalanceCommit":
367
- res = voutChunk(ancestorTx, 0, 1);
409
+ res = voutChunk(ancestorTx, 0, 1 + L);
368
410
  break;
369
411
  case "Vout1PubKeyHash":
370
- res = voutChunk(ancestorTx, 0, 2);
412
+ res = voutChunk(ancestorTx, 0, 2 + L);
371
413
  break;
372
414
  case "Vout1PubKeyHashCommit":
373
- res = voutChunk(ancestorTx, 0, 3);
415
+ res = voutChunk(ancestorTx, 0, 3 + L);
374
416
  break;
375
417
  case "Vout1PubKeyHashCommit2":
376
- res = voutChunk(ancestorTx, 0, 4);
418
+ res = voutChunk(ancestorTx, 0, 4 + L);
377
419
  break;
378
420
  case "Vout1OtherGrandparentOutpoint":
379
- res = voutChunk(ancestorTx, 0, 5);
421
+ res = voutChunk(ancestorTx, 0, 5 + L);
380
422
  break;
381
423
  case "Vout1TxoType":
382
- res = voutChunk(ancestorTx, 0, 6);
424
+ res = voutChunk(ancestorTx, 0, 6 + L);
383
425
  break;
384
426
  case "Vout1OutputIndexN":
385
- res = voutChunk(ancestorTx, 0, 7);
427
+ res = voutChunk(ancestorTx, 0, 7 + L);
386
428
  break;
387
429
  case "Vout1ParentOutpoint":
388
- res = voutChunk(ancestorTx, 0, 8);
430
+ res = voutChunk(ancestorTx, 0, 8 + L);
389
431
  break;
390
432
  case "Vout1GrandparentOutpoint":
391
- res = voutChunk(ancestorTx, 0, 9);
392
- break;
393
- case "Vout1IssuerPubKey":
394
- res = voutChunk(ancestorTx, 0, 10);
395
- break;
396
- // ---- Vout2 (second token output, only splitSettle) ----
397
- case "Vout2Balance":
398
- if (hasTwoBolts)
399
- res = voutChunk(ancestorTx, 1, 0);
400
- break;
401
- case "Vout2BalanceCommit":
402
- if (hasTwoBolts)
403
- res = voutChunk(ancestorTx, 1, 1);
404
- break;
405
- case "Vout2PubKeyHash":
406
- if (hasTwoBolts)
407
- res = voutChunk(ancestorTx, 1, 2);
408
- break;
409
- case "Vout2PubKeyHashCommit":
410
- if (hasTwoBolts)
411
- res = voutChunk(ancestorTx, 1, 3);
412
- break;
413
- case "Vout2PubKeyHashCommit2":
414
- if (hasTwoBolts)
415
- res = voutChunk(ancestorTx, 1, 4);
416
- break;
417
- case "Vout2OtherGrandparentOutpoint":
418
- if (hasTwoBolts)
419
- res = voutChunk(ancestorTx, 1, 5);
420
- break;
421
- case "Vout2TxoType":
422
- if (hasTwoBolts)
423
- res = voutChunk(ancestorTx, 1, 6);
424
- break;
425
- case "Vout2OutputIndexN":
426
- if (hasTwoBolts)
427
- res = voutChunk(ancestorTx, 1, 7);
428
- break;
429
- case "Vout2ParentOutpoint":
430
- if (hasTwoBolts)
431
- res = voutChunk(ancestorTx, 1, 8);
432
- break;
433
- case "Vout2GrandparentOutpoint":
434
- if (hasTwoBolts)
435
- res = voutChunk(ancestorTx, 1, 9);
436
- break;
437
- case "Vout2IssuerPubKey":
438
- if (hasTwoBolts)
439
- res = voutChunk(ancestorTx, 1, 10);
433
+ res = voutChunk(ancestorTx, 0, 9 + L);
440
434
  break;
441
435
  // ---- Bolt (pay2Bolt) outputs ----
442
436
  case "ProofPubKeyHash1":
@@ -463,10 +457,10 @@ export const ancestorPiece = (name, tx) => {
463
457
  }
464
458
  return res;
465
459
  };
466
- // 89 ancestorA + 89 ancestorB = 178 empty chunks (no leading miscData) for melt.
467
- export const createEmptyFungibleAncestorChunksSMB = () => {
460
+ // 2 x pieces empty chunks (SMB 150, FixedBolt 154, OpenBolt 160; no leading miscData) for melt.
461
+ export const createEmptyFungibleAncestorChunksSMB = (layout = SIMPLE_MULTI_LAYOUT) => {
468
462
  const emptyChunks = [];
469
- for (let i = 0; i < SKIP_SMB; i++) {
463
+ for (let i = 0; i < skipOf(layout); i++) {
470
464
  emptyChunks.push(...scriptChunksFromBin([]));
471
465
  }
472
466
  return emptyChunks;
@@ -0,0 +1,11 @@
1
+ import { Transaction } from "@bsv/sdk";
2
+ /** True when the hex string / bytes begin with a BEEF magic (V1, V2 or Atomic). */
3
+ export declare function isBeef(x: string | Uint8Array | number[]): boolean;
4
+ /** Serialise `tx` and every attached source tx (with merkle paths where known) as Atomic BEEF over BEEF V2. */
5
+ export declare function toAtomicBeef(tx: Transaction): number[];
6
+ /**
7
+ * Parse BEEF V2 (plain or Atomic) into its subject transaction, with every ancestor wired in through
8
+ * `sourceTransaction` (and `merklePath` on proven ones). Throws on BEEF V1, on a BEEF that is not self-contained
9
+ * (a tx neither proven by a BUMP nor having all its inputs in the BEEF, or txid-only entries), or on no subject.
10
+ */
11
+ export declare function fromBeef(input: string | Uint8Array | number[]): Transaction;