b017 0.0.0-b1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +568 -39
- package/LICENSE.txt +56 -56
- package/README.md +310 -206
- package/dist/index.d.ts +15 -7
- package/dist/index.js +14 -5
- package/dist/lib/boltLib.d.ts +29 -3
- package/dist/lib/boltLib.js +60 -12
- package/dist/lib/genesis.d.ts +20 -0
- package/dist/lib/genesis.js +45 -0
- package/dist/lib/multi/multiBoltLib.d.ts +22 -2
- package/dist/lib/multi/multiBoltLib.js +114 -129
- package/dist/lib/scanner/beef.d.ts +11 -0
- package/dist/lib/scanner/beef.js +63 -0
- package/dist/lib/scanner/fingerprints.d.ts +12 -2
- package/dist/lib/scanner/fingerprints.js +45 -12
- package/dist/lib/scanner/verifyEvents.d.ts +84 -6
- package/dist/lib/scanner/verifyEvents.js +520 -45
- package/dist/lib/single/singleAncestor.d.ts +27 -3
- package/dist/lib/single/singleAncestor.js +49 -18
- package/dist/lib/single/singleSpend.d.ts +12 -3
- package/dist/lib/single/singleSpend.js +48 -16
- package/dist/tokens/BOLT.d.ts +6 -5
- package/dist/tokens/GenesisMultiBOLT.d.ts +29 -0
- package/dist/tokens/GenesisMultiBOLT.js +48 -0
- package/dist/tokens/MultiBOLT.d.ts +17 -12
- package/dist/tokens/MultiBOLT.js +82 -74
- package/dist/tokens/templates/AuthBolt.sx.template.d.ts +35 -0
- package/dist/tokens/templates/AuthBolt.sx.template.js +82 -0
- package/dist/tokens/templates/FixedMulti.sx.template.d.ts +13 -0
- package/dist/tokens/templates/FixedMulti.sx.template.js +23 -0
- package/dist/tokens/templates/MinSimple.sx.template.d.ts +10 -1
- package/dist/tokens/templates/MinSimple.sx.template.js +15 -1
- package/dist/tokens/templates/OpenMulti.sx.template.d.ts +13 -0
- package/dist/tokens/templates/OpenMulti.sx.template.js +23 -0
- package/dist/tokens/templates/SerialBolt.sx.template.d.ts +23 -0
- package/dist/tokens/templates/SerialBolt.sx.template.js +61 -0
- package/dist/tokens/templates/SimpleMulti.sx.template.d.ts +12 -6
- package/dist/tokens/templates/SimpleMulti.sx.template.js +33 -25
- package/dist/tokens/templates/pay2Proof.d.ts +2 -1
- package/dist/tokens/templates/pay2Proof.js +1 -1
- package/package.json +64 -58
- package/dist/tokens/templates/MinSimpleBalance.sx.template.d.ts +0 -24
- package/dist/tokens/templates/MinSimpleBalance.sx.template.js +0 -59
- package/dist/tokens/templates/MinSimpleDiscount.sx.template.d.ts +0 -23
- package/dist/tokens/templates/MinSimpleDiscount.sx.template.js +0 -58
|
@@ -9,11 +9,40 @@
|
|
|
9
9
|
// byte, fingerprint EVERY interface (strict golden recognition for all token
|
|
10
10
|
// inputs/outputs — including split's 2 token outputs and merge's 2 token
|
|
11
11
|
// inputs; loose shape for the p2p proof / change / funding), and check the
|
|
12
|
-
// commit<->settle linkage.
|
|
12
|
+
// commit<->settle linkage. Its VERDICT comes from the same scan as verifyEvents (so a
|
|
13
|
+
// lone commit, an orphan settle or a forged history behind the event is refused), and
|
|
14
|
+
// the txs must hold exactly one action (its anchor and its mint may ride along).
|
|
13
15
|
// verifyEvents(txs) — validate a BATCH of events: recognise the type, pin the issuer across the
|
|
14
16
|
// whole batch, fingerprint every tx's arrangement, then pair the events —
|
|
15
17
|
// every commit must be matched by a settle (and vice-versa) via parentOutpoint.
|
|
16
|
-
// A lone
|
|
18
|
+
// A lone melt is a valid single-tx event. A MINT is not: a mint only NAMES an issuerPubKey
|
|
19
|
+
// (anyone can mint an output naming anybody's key), and the issuer guard runs when the
|
|
20
|
+
// genesis is first SPENT, so a mint is accepted only with a COMMIT in the same event/batch
|
|
21
|
+
// that spends it. Otherwise the verdict is `unauthenticated: true` (not a signature failure).
|
|
22
|
+
// The scanner also EXECUTES every input whose source tx is supplied (the covenants, the
|
|
23
|
+
// signatures): structure alone cannot tell a forged commit from a real one, and off-chain
|
|
24
|
+
// (SPV / zero-funding) txs have not been validated by any node. EVERY input's source tx must
|
|
25
|
+
// be supplied (attached, in the batch, or inside a BEEF - Atomic BEEF over V2, see beef.ts),
|
|
26
|
+
// else the verdict is a failure.
|
|
27
|
+
// THE ANCHOR: the token tx a batch stands on - the settle BEFORE the batch's first commit
|
|
28
|
+
// (settle N-1), or the mint when the batch starts at genesis. What travels p2p is
|
|
29
|
+
// [mint, c1, s1] or [sN-1, cN, sN]. The anchor is validated FIRST and like any event tx:
|
|
30
|
+
// structure, golden fingerprint, issuer, and script execution (so ITS sources must be
|
|
31
|
+
// supplied too). An anchor settle is the one settle allowed without its commit in the batch.
|
|
32
|
+
// An anchor only attached as a `sourceTransaction` (or inside a BEEF) is pulled into the batch.
|
|
33
|
+
// The result names the anchors; the CALLER broadcasts them (verifyAndBroadcast), so the
|
|
34
|
+
// network is seen to accept (or already know) the tx the batch is built on. Local execution
|
|
35
|
+
// reaches the anchor's own inputs only; the ancestry behind it is what the broadcast proves.
|
|
36
|
+
// An anchor must be a tx the network has seen and will therefore mine. An UNFUNDED anchor
|
|
37
|
+
// pays no fee, so being seen proves nothing: it is refused unless it carries a merkle path
|
|
38
|
+
// into a block header the caller knows (ScanOpts.isKnownBlockRoot, or a chainTracker given
|
|
39
|
+
// to verifyAndBroadcast). The events standing on the anchor may be unfunded and stay off chain.
|
|
40
|
+
// A HEADER-PROVEN anchor (funded or not) is not re-executed and needs no sources of its own:
|
|
41
|
+
// consensus validated it, and a BEEF stops at proven txs. So an anchor is one of: proven
|
|
42
|
+
// by its merkle tree into a known chain header, or seen on the network (broadcast), or mined.
|
|
43
|
+
// VALUE CONSERVATION is checked: an ANCHOR whose outputs exceed its inputs is refused; an EVENT
|
|
44
|
+
// tx that does so is only reported (`offChainOnly`), since a commit / settle that is never
|
|
45
|
+
// broadcast is still valid off chain. `requireBroadcastable` turns the report into a refusal.
|
|
17
46
|
//
|
|
18
47
|
// NOTE — a commit and its settle are bound TWO independent ways:
|
|
19
48
|
// (1) TOKEN LINEAGE — the settle's token parentOutpoint references the commit's token output.
|
|
@@ -25,20 +54,28 @@
|
|
|
25
54
|
//
|
|
26
55
|
// Strict = golden byte fingerprint (recognizeType: leading-push layout + sha256(static code)).
|
|
27
56
|
// 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";
|
|
57
|
+
import { OP, Spend, Transaction, Utils } from "@bsv/sdk";
|
|
58
|
+
import { recognizeType, recognizeP2P, issuerPubKeyOf, REGISTRY } from "./fingerprints.js";
|
|
59
|
+
import { genesisFieldFor } from "../genesis.js";
|
|
60
|
+
import { fromBeef, isBeef } from "./beef.js";
|
|
30
61
|
const FIELDS = {
|
|
31
62
|
MinSimpleBOLT: { pubKeyHash: 0, commitment: 1, txoType: 2, parent: 3, grandparent: 4 },
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
63
|
+
AuthBOLT: { pubKeyHash: 0, commitment: 1, txoType: 2, parent: 3, grandparent: 4 },
|
|
64
|
+
SimpleMultiBOLT: { pubKeyHash: 2, commitment: 3, txoType: 6, parent: 7, grandparent: 8 },
|
|
65
|
+
// the genesis family: two leading pushes (genesis / LMG field, mintData) before the base fields
|
|
66
|
+
FixedBOLT: { pubKeyHash: 4, commitment: 5, txoType: 8, parent: 9, grandparent: 10 },
|
|
67
|
+
OpenBOLT: { pubKeyHash: 4, commitment: 5, txoType: 8, parent: 9, grandparent: 10 },
|
|
68
|
+
SerialBOLT: { pubKeyHash: 2, commitment: 3, txoType: 4, parent: 5, grandparent: 6 },
|
|
35
69
|
};
|
|
36
|
-
const field = (lock, type, f) =>
|
|
70
|
+
const field = (lock, type, f) =>
|
|
71
|
+
/* v8 ignore next -- field() is only called on a lock recognizeType accepted, so the field chunk exists and carries data */
|
|
72
|
+
lock.chunks[FIELDS[type][f]]?.data ?? [];
|
|
37
73
|
const fieldHex = (lock, type, f) => Utils.toHex(field(lock, type, f));
|
|
38
74
|
// A 36-byte outpoint is txid (32, internal byte order) + vout (4, LE). The display txid is reversed.
|
|
39
75
|
// A short/empty buffer (a tampered or absent field) yields a txid that cannot match any real tx, so
|
|
40
76
|
// the linkage check fails closed rather than throwing.
|
|
41
77
|
function parseOutpoint(op) {
|
|
78
|
+
/* v8 ignore next -- parseOutpoint is only fed field(), which always returns an array */
|
|
42
79
|
const bytes = Array.isArray(op) ? op : [];
|
|
43
80
|
const txidHex = Utils.toHex([...bytes.slice(0, 32)].reverse());
|
|
44
81
|
const v = new Uint8Array(4);
|
|
@@ -50,17 +87,48 @@ function parseOutpoint(op) {
|
|
|
50
87
|
* into an `ok: false` result so a malformed batch never escapes as an exception. */
|
|
51
88
|
class ParseError extends Error {
|
|
52
89
|
}
|
|
90
|
+
/** The first line of whatever was thrown (an Error's message, else the value itself). */
|
|
91
|
+
const errText = (e) => String(e?.message ?? e).split(String.fromCharCode(10))[0];
|
|
92
|
+
/** The scanner never throws. A Transaction OBJECT handed in by the caller can still be broken in ways parsing
|
|
93
|
+
* cannot be (an input with no source reference or no unlocking script, an output with no locking script), and
|
|
94
|
+
* the SDK throws when such a tx is serialised. Anything a verifier body throws becomes a refusal. */
|
|
95
|
+
const failClosed = (run) => {
|
|
96
|
+
try {
|
|
97
|
+
return run();
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
return { ok: false, reason: `unverifiable input: ${errText(e)}` };
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
/** Parse one event tx. Throws ParseError and nothing else, so the entry points can report `e.message` as is. */
|
|
53
104
|
const toTx = (t) => {
|
|
54
|
-
if (
|
|
105
|
+
if (t instanceof Transaction)
|
|
55
106
|
return t;
|
|
107
|
+
if (typeof t !== "string" && !(t instanceof Uint8Array) && !Array.isArray(t))
|
|
108
|
+
throw new ParseError("not a transaction: expected a Transaction, raw tx hex, or BEEF hex / bytes");
|
|
109
|
+
if (isBeef(t)) {
|
|
110
|
+
try {
|
|
111
|
+
return fromBeef(t);
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
throw new ParseError(`invalid BEEF: ${errText(e)}`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
56
117
|
try {
|
|
57
|
-
return Transaction.fromHex(t);
|
|
118
|
+
return typeof t === "string" ? Transaction.fromHex(t) : Transaction.fromBinary(Array.from(t));
|
|
58
119
|
}
|
|
59
120
|
catch (e) {
|
|
60
|
-
throw new ParseError(`malformed transaction hex: ${e
|
|
121
|
+
throw new ParseError(`malformed transaction hex: ${errText(e)}`);
|
|
61
122
|
}
|
|
62
123
|
};
|
|
63
124
|
const optHex = (b) => b == null ? undefined : typeof b === "string" ? b.toLowerCase() : Utils.toHex(b);
|
|
125
|
+
/** The tx an input spends: its attached source, else the tx of the batch its outpoint names. */
|
|
126
|
+
const sourceOf = (input, byId) =>
|
|
127
|
+
/* v8 ignore next -- an input with neither a txid nor an attached source cannot be serialised: byId is built from tx.id() first, which throws, and failClosed turns that into a refusal */
|
|
128
|
+
input.sourceTransaction ?? (input.sourceTXID ? byId.get(input.sourceTXID) : undefined);
|
|
129
|
+
/** The txid an input spends: the outpoint's, else the attached source's. */
|
|
130
|
+
/* v8 ignore next -- same as sourceOf: by the time this runs every input has a txid or an attached source */
|
|
131
|
+
const spentTxid = (input) => input.sourceTXID ?? input.sourceTransaction?.id("hex");
|
|
64
132
|
/** Classify an output's locking script. token = strict golden fingerprint; p2p = the b017 marker
|
|
65
133
|
* proof output; p2pkh = a plain pay-to-pubkey-hash (change); else "other". */
|
|
66
134
|
function classifyOut(lock, type) {
|
|
@@ -68,6 +136,7 @@ function classifyOut(lock, type) {
|
|
|
68
136
|
return "token";
|
|
69
137
|
if (recognizeP2P(lock))
|
|
70
138
|
return "p2p"; // golden p2Proof fingerprint (b017 marker + static skeleton)
|
|
139
|
+
/* v8 ignore next -- an output with no locking script cannot be serialised (tx.id() throws first, failClosed refuses) */
|
|
71
140
|
const c = lock?.chunks ?? [];
|
|
72
141
|
if (c.length === 5 && c[0].op === OP.OP_DUP && c[1].op === OP.OP_HASH160 && c[2].data?.length === 20 &&
|
|
73
142
|
c[3].op === OP.OP_EQUALVERIFY && c[4].op === OP.OP_CHECKSIG)
|
|
@@ -77,8 +146,7 @@ function classifyOut(lock, type) {
|
|
|
77
146
|
/** Classify an input by fingerprinting the output it spends (via the attached source tx, else a
|
|
78
147
|
* source tx supplied in the batch); "external" when the source is outside the supplied set. */
|
|
79
148
|
function classifyIn(input, type, byId) {
|
|
80
|
-
const
|
|
81
|
-
const spent = src?.outputs?.[input.sourceOutputIndex]?.lockingScript;
|
|
149
|
+
const spent = sourceOf(input, byId)?.outputs?.[input.sourceOutputIndex]?.lockingScript;
|
|
82
150
|
if (!spent)
|
|
83
151
|
return "external"; // source not in the supplied set (or out-of-range vout)
|
|
84
152
|
return classifyOut(spent, type);
|
|
@@ -105,17 +173,210 @@ function categorise(tx, type, byId) {
|
|
|
105
173
|
return { shape: { kind: "melt", tokenIn: 1, tokenOut: 0, proofOut: 0 }, tokenOutIdx: -1 };
|
|
106
174
|
return null;
|
|
107
175
|
}
|
|
176
|
+
/**
|
|
177
|
+
* Genesis family: the asset field (lock push 0) of every token output must follow from its in-batch parent token
|
|
178
|
+
* (genesisFieldFor: null on the mint, the mint outpoint at the genesis spend, OpenBOLT's re-root at a merge commit,
|
|
179
|
+
* else copied); FixedBOLT also requires every token input of a tx to carry the output's genesis (one asset per
|
|
180
|
+
* merge). An output whose parent token is not in the batch is pinned by its own spends later in the batch.
|
|
181
|
+
*/
|
|
182
|
+
function genesisLineageFailure(txs, type, byId) {
|
|
183
|
+
if (!REGISTRY[type].genesis)
|
|
184
|
+
return null;
|
|
185
|
+
const parentIdx = FIELDS[type].parent;
|
|
186
|
+
const head = (lock) => Utils.toHex(lock.chunks[0].data); // a recognised genesis token's 36-byte field
|
|
187
|
+
for (const tx of txs) {
|
|
188
|
+
const tokenIns = tx.inputs
|
|
189
|
+
.map((inp) => ({ src: sourceOf(inp, byId), vout: inp.sourceOutputIndex }))
|
|
190
|
+
.filter((x) => x.src && recognizeType(x.src.outputs[x.vout]?.lockingScript, type));
|
|
191
|
+
if (!tokenIns.length)
|
|
192
|
+
continue; // a mint (its null field is enforced by the mint spec)
|
|
193
|
+
const vin0 = tokenIns[0];
|
|
194
|
+
tx.outputs.forEach((o, v) => {
|
|
195
|
+
if (!recognizeType(o.lockingScript, type))
|
|
196
|
+
return;
|
|
197
|
+
const reroot = type === "OpenBOLT" && fieldHex(o.lockingScript, type, "txoType") === "25";
|
|
198
|
+
const want = Utils.toHex(genesisFieldFor({ prevTx: vin0.src, prevVoutIdx: vin0.vout, parentIdx, reroot }));
|
|
199
|
+
if (head(o.lockingScript) !== want)
|
|
200
|
+
throw new Error(`tx ${tx.id("hex").slice(0, 8)} vout ${v}: ${type} asset field does not follow its lineage`);
|
|
201
|
+
if (type === "FixedBOLT")
|
|
202
|
+
for (const t of tokenIns.slice(1))
|
|
203
|
+
if (head(t.src.outputs[t.vout].lockingScript) !== head(o.lockingScript))
|
|
204
|
+
throw new Error(`tx ${tx.id("hex").slice(0, 8)}: FixedBOLT merge of different genesis outpoints (different assets)`);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
const lineageFailure = (txs, type, byId) => {
|
|
210
|
+
try {
|
|
211
|
+
return genesisLineageFailure(txs, type, byId);
|
|
212
|
+
}
|
|
213
|
+
catch (e) {
|
|
214
|
+
return String(e.message);
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
/** The first MINT in `txs` that no COMMIT in `txs` spends, or null. A mint is just an output naming an issuerPubKey;
|
|
218
|
+
* the issuer guard only runs when the genesis token is first SPENT, so a mint is authenticated only by a commit that
|
|
219
|
+
* spends its token output (funded or not). */
|
|
220
|
+
function unauthenticatedMint(txs, type, byId) {
|
|
221
|
+
const cats = txs.map((tx) => ({ tx, cat: categorise(tx, type, byId) }));
|
|
222
|
+
const commits = cats.filter((c) => c.cat?.shape.kind === "commit").map((c) => c.tx);
|
|
223
|
+
for (const { tx, cat } of cats) {
|
|
224
|
+
if (cat?.shape.kind !== "mint")
|
|
225
|
+
continue;
|
|
226
|
+
const txid = tx.id("hex");
|
|
227
|
+
const spent = commits.some((c) => c.inputs.some((i) => spentTxid(i) === txid && i.sourceOutputIndex === cat.tokenOutIdx));
|
|
228
|
+
if (!spent)
|
|
229
|
+
return tx;
|
|
230
|
+
}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* EXECUTE every input of every tx (event txs and anchors) on the @bsv/sdk Spend engine. The structural checks say a
|
|
235
|
+
* tx HAS the right shape; only execution shows its scripts are VALID. That matters for off-chain (SPV /
|
|
236
|
+
* zero-funding) packages, which no node has validated: a forged commit (signed by a stranger, refused by the
|
|
237
|
+
* covenant's issuer guard) is structurally perfect. requireSources runs first and refuses any input whose source tx
|
|
238
|
+
* was not supplied, so no input is skipped here. Returns the first failure.
|
|
239
|
+
*/
|
|
240
|
+
function executeInputs(txs, byId) {
|
|
241
|
+
const outpointRef = (i) => ({
|
|
242
|
+
sourceTXID: spentTxid(i),
|
|
243
|
+
sourceOutputIndex: i.sourceOutputIndex,
|
|
244
|
+
sequence: (i.sequence ?? 0xffffffff),
|
|
245
|
+
});
|
|
246
|
+
for (const tx of txs) {
|
|
247
|
+
const id = tx.id("hex").slice(0, 8);
|
|
248
|
+
for (let vin = 0; vin < tx.inputs.length; vin++) {
|
|
249
|
+
const input = tx.inputs[vin];
|
|
250
|
+
const out = sourceOf(input, byId)?.outputs?.[input.sourceOutputIndex];
|
|
251
|
+
/* v8 ignore next 2 -- requireSources runs before executeInputs and refuses a missing source; if that order ever changes this fails closed instead of skipping the input */
|
|
252
|
+
if (!out)
|
|
253
|
+
return `script execution failed: tx ${id} input ${vin}: its source tx was not supplied`;
|
|
254
|
+
let failure;
|
|
255
|
+
try {
|
|
256
|
+
/* v8 ignore next -- an input with no unlocking script cannot be serialised (tx.id() throws first, failClosed refuses) */
|
|
257
|
+
if (!input.unlockingScript)
|
|
258
|
+
failure = "no unlocking script";
|
|
259
|
+
else if (!new Spend({
|
|
260
|
+
sourceTXID: outpointRef(input).sourceTXID,
|
|
261
|
+
sourceOutputIndex: input.sourceOutputIndex,
|
|
262
|
+
lockingScript: out.lockingScript,
|
|
263
|
+
/* v8 ignore next -- a source output of a parsed or signed tx always has its satoshis */
|
|
264
|
+
sourceSatoshis: out.satoshis ?? 0,
|
|
265
|
+
transactionVersion: tx.version,
|
|
266
|
+
otherInputs: tx.inputs.filter((_, k) => k !== vin).map(outpointRef),
|
|
267
|
+
unlockingScript: input.unlockingScript,
|
|
268
|
+
inputSequence: input.sequence ?? 0xffffffff,
|
|
269
|
+
inputIndex: vin,
|
|
270
|
+
outputs: tx.outputs,
|
|
271
|
+
lockTime: tx.lockTime,
|
|
272
|
+
}).validate()
|
|
273
|
+
/* v8 ignore next -- Spend.validate() throws on a failing script; it never returns false */
|
|
274
|
+
)
|
|
275
|
+
failure = "the script evaluated false";
|
|
276
|
+
}
|
|
277
|
+
catch (e) {
|
|
278
|
+
failure = errText(e);
|
|
279
|
+
}
|
|
280
|
+
if (failure)
|
|
281
|
+
return `script execution failed: tx ${id} input ${vin}: ${failure}`;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Every input of every event tx must have its source tx SUPPLIED (attached, or another event tx): without it the
|
|
288
|
+
* input's script cannot be executed, so the event cannot be authenticated. Returns the first missing source as a
|
|
289
|
+
* failure reason, else the non-event source txs (with whether each carries a BUMP).
|
|
290
|
+
*/
|
|
291
|
+
function requireSources(txs, byId) {
|
|
292
|
+
const sources = new Map();
|
|
293
|
+
for (const tx of txs) {
|
|
294
|
+
const id = tx.id("hex").slice(0, 8);
|
|
295
|
+
for (let vin = 0; vin < tx.inputs.length; vin++) {
|
|
296
|
+
const input = tx.inputs[vin];
|
|
297
|
+
const src = sourceOf(input, byId);
|
|
298
|
+
if (!src || !src.outputs?.[input.sourceOutputIndex])
|
|
299
|
+
/* v8 ignore next -- every input has a txid by now (see sourceOf); the "?" only guards the message */
|
|
300
|
+
return { failure: `source tx ${String(input.sourceTXID ?? "?").slice(0, 8)} of tx ${id} input ${vin} was not supplied (send the package as BEEF)`, sources: [] };
|
|
301
|
+
const sid = src.id("hex");
|
|
302
|
+
// An attached source must BE the tx the input names: the outpoint is what the signature commits to.
|
|
303
|
+
if (input.sourceTXID && input.sourceTXID !== sid)
|
|
304
|
+
return { failure: `attached source ${sid.slice(0, 8)} of tx ${id} input ${vin} is not the tx its outpoint names (${String(input.sourceTXID).slice(0, 8)})`, sources: [] };
|
|
305
|
+
if (!byId.has(sid) && !sources.has(sid))
|
|
306
|
+
sources.set(sid, { txid: sid, proven: !!src.merklePath });
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return { sources: [...sources.values()] };
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Is `tx` HEADER-PROVEN: does it carry a merkle path that proves it into a block header the caller knows? If so
|
|
313
|
+
* consensus has already validated it. `why` says what is missing when it is not.
|
|
314
|
+
*/
|
|
315
|
+
function headerProof(tx, opts) {
|
|
316
|
+
const path = tx.merklePath;
|
|
317
|
+
if (!path)
|
|
318
|
+
return { proven: false, why: "it is accepted only with an SPV proof (a merkle path) to a known block header" };
|
|
319
|
+
if (typeof opts.isKnownBlockRoot !== "function")
|
|
320
|
+
return { proven: false, why: "it carries a merkle path, but no block headers were supplied to check it against (isKnownBlockRoot)" };
|
|
321
|
+
let root;
|
|
322
|
+
try {
|
|
323
|
+
root = path.computeRoot(tx.id("hex"));
|
|
324
|
+
}
|
|
325
|
+
catch (e) {
|
|
326
|
+
return { proven: false, why: `its merkle path does not prove it (${errText(e)})` };
|
|
327
|
+
}
|
|
328
|
+
let known = false;
|
|
329
|
+
try {
|
|
330
|
+
known = opts.isKnownBlockRoot(root, path.blockHeight) === true;
|
|
331
|
+
}
|
|
332
|
+
catch { /* a throwing header lookup is not a known header */ }
|
|
333
|
+
return known ? { proven: true, why: "" } : { proven: false, why: `its merkle root is not a known block header at height ${path.blockHeight}` };
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* An anchor is proven into a known block header, or it is a tx the network has seen and will therefore mine. An
|
|
337
|
+
* UNFUNDED anchor (no funding input) gives the network no reason to mine it, so being seen proves nothing. It can
|
|
338
|
+
* still be mined (a friendly miner), so it is accepted only once it has been, i.e. when it is header-proven.
|
|
339
|
+
* Called for anchors that are NOT header-proven; returns the refusal reason, if any.
|
|
340
|
+
*/
|
|
341
|
+
function anchorNotMinable(tx, type, byId, why) {
|
|
342
|
+
const id = tx.id("hex").slice(0, 8);
|
|
343
|
+
// An anchor whose outputs exceed its inputs CREATES value: no node accepts that, funded or not.
|
|
344
|
+
const { inputSats, outputSats } = valueOf(tx, byId);
|
|
345
|
+
if (outputSats > inputSats)
|
|
346
|
+
return `anchor ${id} creates value (inputs ${inputSats} sat, outputs ${outputSats} sat): the network will never accept it; ${why}`;
|
|
347
|
+
const funded = tx.inputs.some((i) => {
|
|
348
|
+
const cls = classifyIn(i, type, byId);
|
|
349
|
+
return cls === "p2pkh" || cls === "external";
|
|
350
|
+
});
|
|
351
|
+
if (!funded)
|
|
352
|
+
return `unfunded anchor ${id}: ${tx.merklePath ? "" : "it pays no fee, so the network will not mine it on sight; "}${why}`;
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
/** The satoshis a tx spends and creates (its sources must be supplied: requireSources has run). */
|
|
356
|
+
function valueOf(tx, byId) {
|
|
357
|
+
let inputSats = 0;
|
|
358
|
+
for (const input of tx.inputs) {
|
|
359
|
+
/* v8 ignore next -- requireSources has run, so every source and its output exist, and a parsed or signed output has satoshis */
|
|
360
|
+
inputSats += sourceOf(input, byId)?.outputs?.[input.sourceOutputIndex]?.satoshis ?? 0;
|
|
361
|
+
}
|
|
362
|
+
let outputSats = 0;
|
|
363
|
+
/* v8 ignore next -- an output of a parsed or signed tx always has its satoshis */
|
|
364
|
+
for (const out of tx.outputs)
|
|
365
|
+
outputSats += out.satoshis ?? 0;
|
|
366
|
+
return { inputSats, outputSats };
|
|
367
|
+
}
|
|
368
|
+
const unauthenticatedReason = (tx) => `unauthenticated mint ${tx.id("hex").slice(0, 8)}: no commit in the event spends it, so nothing shows the sender holds the issuer key`;
|
|
108
369
|
const actionKind = (txoTypeHex) => txoTypeHex === "23" ? "split" : txoTypeHex === "25" ? "merge" : "transfer";
|
|
109
370
|
/** Fingerprint every interface of a token tx and check it matches its action's golden shape:
|
|
110
371
|
* the leading token in/out are strictly recognised; the p2p proof outputs are exact in count;
|
|
111
372
|
* trailing change (p2pkh) + funding/proof inputs are loose; nothing may be "other". */
|
|
112
|
-
function checkArrangement(tx, type, shape, byId) {
|
|
373
|
+
function checkArrangement(tx, type, shape, byId, outputsOnly = false) {
|
|
113
374
|
const id = tx.id("hex").slice(0, 8);
|
|
114
375
|
const outs = tx.outputs.map((o) => classifyOut(o.lockingScript, type));
|
|
115
376
|
const ins = tx.inputs.map((i) => classifyIn(i, type, byId));
|
|
116
377
|
if (outs.includes("other"))
|
|
117
378
|
return `uninspected output in ${id} [${outs}]`;
|
|
118
|
-
if (ins.includes("other"))
|
|
379
|
+
if (!outputsOnly && ins.includes("other"))
|
|
119
380
|
return `uninspected input in ${id} [${ins}]`;
|
|
120
381
|
// outputs: [token × tokenOut] then [p2p × proofOut] then [p2pkh change × rest]
|
|
121
382
|
for (let k = 0; k < shape.tokenOut; k++)
|
|
@@ -127,6 +388,9 @@ function checkArrangement(tx, type, shape, byId) {
|
|
|
127
388
|
for (let k = shape.tokenOut + shape.proofOut; k < outs.length; k++)
|
|
128
389
|
if (outs[k] !== "p2pkh")
|
|
129
390
|
return `${shape.kind} ${id}: change p2pkh @${k} (got ${outs[k]}) [${outs}]`;
|
|
391
|
+
// A header-proven anchor: consensus validated its inputs, and their sources need not be supplied.
|
|
392
|
+
if (outputsOnly)
|
|
393
|
+
return null;
|
|
130
394
|
// inputs: [token × tokenIn] then [p2p proof × any (settle only, contiguous)] then [funding: external | p2pkh].
|
|
131
395
|
// A p2Proof input (consuming a commit's proof output) is STRICTLY fingerprinted (classifyIn ->
|
|
132
396
|
// recognizeP2P) and is only legitimate on a settle, immediately after the token input(s); a proof
|
|
@@ -153,9 +417,10 @@ function eventType(txs, byId, expected) {
|
|
|
153
417
|
}
|
|
154
418
|
for (const tx of txs)
|
|
155
419
|
for (const inp of tx.inputs) {
|
|
156
|
-
const s =
|
|
420
|
+
const s = sourceOf(inp, byId);
|
|
157
421
|
if (s) {
|
|
158
|
-
const
|
|
422
|
+
const lock = s.outputs?.[inp.sourceOutputIndex]?.lockingScript; // an out-of-range vout is not a token
|
|
423
|
+
const t = lock ? recognizeType(lock, expected) : undefined;
|
|
159
424
|
if (t)
|
|
160
425
|
return t;
|
|
161
426
|
}
|
|
@@ -163,11 +428,16 @@ function eventType(txs, byId, expected) {
|
|
|
163
428
|
return undefined;
|
|
164
429
|
}
|
|
165
430
|
/**
|
|
166
|
-
* Verify ONE token event
|
|
167
|
-
* token's txoType action, fingerprints EVERY interface against the action's
|
|
168
|
-
*
|
|
431
|
+
* Verify ONE token event - a commit->settle pair or a melt (a mint is accepted only with the commit that spends
|
|
432
|
+
* it). Categorises each tx by its token's txoType action, fingerprints EVERY interface against the action's
|
|
433
|
+
* golden shape, checks the settle links back to the commit, then takes its verdict from the same scan as
|
|
434
|
+
* verifyEvents: the anchor step, pairing, sources and script execution all apply, and `anchors` names what the
|
|
435
|
+
* caller must broadcast. A lone commit or a lone settle is NOT an event.
|
|
169
436
|
*/
|
|
170
437
|
export function verifyEvent(eventTxs, opts = {}) {
|
|
438
|
+
return failClosed(() => verifyOneEvent(eventTxs, opts));
|
|
439
|
+
}
|
|
440
|
+
function verifyOneEvent(eventTxs, opts) {
|
|
171
441
|
if (!Array.isArray(eventTxs))
|
|
172
442
|
return { ok: false, reason: "event must be an array of transactions" };
|
|
173
443
|
let txs;
|
|
@@ -175,7 +445,7 @@ export function verifyEvent(eventTxs, opts = {}) {
|
|
|
175
445
|
txs = eventTxs.map(toTx);
|
|
176
446
|
}
|
|
177
447
|
catch (e) {
|
|
178
|
-
return { ok: false, reason: e
|
|
448
|
+
return { ok: false, reason: e.message }; // toTx throws ParseError only
|
|
179
449
|
}
|
|
180
450
|
if (txs.length === 0)
|
|
181
451
|
return { ok: false, reason: "empty event" };
|
|
@@ -194,27 +464,112 @@ export function verifyEvent(eventTxs, opts = {}) {
|
|
|
194
464
|
if (reason)
|
|
195
465
|
return { ok: false, reason, type, kind: cat.shape.kind };
|
|
196
466
|
}
|
|
467
|
+
const stray = unauthenticatedMint(txs, type, byId);
|
|
468
|
+
if (stray)
|
|
469
|
+
return { ok: false, reason: unauthenticatedReason(stray), type, kind: "mint", unauthenticated: true };
|
|
470
|
+
const need = requireSources(txs, byId);
|
|
471
|
+
if (need.failure)
|
|
472
|
+
return { ok: false, reason: need.failure, type };
|
|
473
|
+
// The event's commit must be settled by a settle of the event (an ANCHOR settle may ride along; it links elsewhere).
|
|
197
474
|
const commitTx = txs.find((t) => categorise(t, type, byId)?.shape.kind === "commit");
|
|
198
|
-
const
|
|
199
|
-
if (commitTx &&
|
|
475
|
+
const settleTxs = txs.filter((t) => categorise(t, type, byId)?.shape.kind === "settle");
|
|
476
|
+
if (commitTx && settleTxs.length > 0) {
|
|
200
477
|
const cIdx = commitTx.outputs.findIndex((o) => recognizeType(o.lockingScript, type));
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
478
|
+
const linked = settleTxs.some((settleTx) => {
|
|
479
|
+
const sIdx = settleTx.outputs.findIndex((o) => recognizeType(o.lockingScript, type));
|
|
480
|
+
const p = parseOutpoint(field(settleTx.outputs[sIdx].lockingScript, type, "parent"));
|
|
481
|
+
return p.txidHex === commitTx.id("hex") && p.vout === cIdx;
|
|
482
|
+
});
|
|
483
|
+
if (!linked)
|
|
204
484
|
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
485
|
}
|
|
207
|
-
|
|
208
|
-
|
|
486
|
+
// The verdict itself comes from the SAME scan as verifyEvents (anchor step, pairing, sources, script execution), so
|
|
487
|
+
// the two entry points cannot disagree: a lone commit, an orphan settle or a forged history behind the event is
|
|
488
|
+
// refused here exactly as it is there. On top of that, an event is exactly ONE action (a mint riding with the
|
|
489
|
+
// commit that authenticates it is not counted).
|
|
490
|
+
const r = scan(txs, opts);
|
|
491
|
+
if (!r.ok)
|
|
492
|
+
return {
|
|
493
|
+
ok: false, reason: r.reason, type,
|
|
494
|
+
...(r.unauthenticated ? { unauthenticated: true } : {}), ...(r.offChainOnly ? { offChainOnly: r.offChainOnly } : {}),
|
|
495
|
+
};
|
|
496
|
+
const actions = r.events.filter((e) => e.kind !== "mint");
|
|
497
|
+
if (actions.length !== 1)
|
|
498
|
+
return { ok: false, reason: `expected exactly one event, got ${actions.length} (use verifyEvents for a batch)`, type };
|
|
499
|
+
return {
|
|
500
|
+
ok: true, type, kind: actions[0].kind, sources: r.sources, anchors: r.anchors,
|
|
501
|
+
...(r.offChainOnly ? { offChainOnly: r.offChainOnly } : {}),
|
|
502
|
+
};
|
|
209
503
|
}
|
|
210
504
|
/**
|
|
211
505
|
* Verify a BATCH of transactional events end to end. The multistep inspection: recognise the type,
|
|
212
506
|
* pin the issuer across every token output in the batch, fingerprint every tx's interface
|
|
213
507
|
* arrangement, then pair the events — every commit (txoType 21/23/25) must be matched by a settle
|
|
214
508
|
* that links back via parentOutpoint, and every settle must link to a commit in the batch. A lone
|
|
215
|
-
*
|
|
509
|
+
* melt (terminal) is a valid single-tx event; a MINT must be spent by a commit in the batch, else the
|
|
510
|
+
* result is `unauthenticated: true` (a mint alone does not prove the sender holds the issuer key).
|
|
511
|
+
* The batch's ANCHORS (settle N-1 / the mint) are validated with it and named in `anchors`; this function is offline,
|
|
512
|
+
* so the caller still has to broadcast them (verifyAndBroadcast does both).
|
|
216
513
|
*/
|
|
217
514
|
export function verifyEvents(txsIn, opts = {}) {
|
|
515
|
+
return scan(txsIn, opts);
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* verifyEvents, then BROADCAST every anchor through the caller's broadcaster. The batch is accepted only when the
|
|
519
|
+
* offline verdict is ok AND the network accepted (or had already seen) each anchor: that shows the tx the batch
|
|
520
|
+
* stands on exists and that a node accepted its scripts and its ancestry. Nothing is broadcast when the offline
|
|
521
|
+
* verdict fails. A rejected anchor, a throwing broadcaster or an unknown status all fail closed.
|
|
522
|
+
*/
|
|
523
|
+
export async function verifyAndBroadcast(txsIn, broadcastAnchor, opts = {}) {
|
|
524
|
+
if (typeof broadcastAnchor !== "function")
|
|
525
|
+
return { ok: false, reason: "an anchor broadcaster is required" };
|
|
526
|
+
const anchorTxs = [];
|
|
527
|
+
// With an async chainTracker (and no sync isKnownBlockRoot): a first pass collects the merkle roots the anchors
|
|
528
|
+
// offer, the tracker answers for each, and the real scan then runs against those answers. Nothing is broadcast
|
|
529
|
+
// before that.
|
|
530
|
+
let scanOpts = opts;
|
|
531
|
+
const tracker = opts.isKnownBlockRoot ? undefined : opts.chainTracker;
|
|
532
|
+
if (tracker) {
|
|
533
|
+
const offered = new Map();
|
|
534
|
+
scan(txsIn, { ...opts, isKnownBlockRoot: (root, height) => { offered.set(`${height}:${root}`, { root, height }); return false; } });
|
|
535
|
+
const known = new Set();
|
|
536
|
+
for (const [key, { root, height }] of offered) {
|
|
537
|
+
try {
|
|
538
|
+
if ((await tracker.isValidRootForHeight(root, height)) === true)
|
|
539
|
+
known.add(key);
|
|
540
|
+
}
|
|
541
|
+
catch { /* a failing tracker is not a known header */ }
|
|
542
|
+
}
|
|
543
|
+
scanOpts = { ...opts, isKnownBlockRoot: (root, height) => known.has(`${height}:${root}`) };
|
|
544
|
+
}
|
|
545
|
+
const result = scan(txsIn, scanOpts, anchorTxs);
|
|
546
|
+
if (!result.ok)
|
|
547
|
+
return result;
|
|
548
|
+
const anchors = [];
|
|
549
|
+
for (let k = 0; k < anchorTxs.length; k++) {
|
|
550
|
+
const ref = result.anchors[k];
|
|
551
|
+
let sent;
|
|
552
|
+
try {
|
|
553
|
+
sent = await broadcastAnchor(anchorTxs[k]);
|
|
554
|
+
}
|
|
555
|
+
catch (e) {
|
|
556
|
+
sent = { status: "rejected", detail: `broadcast failed: ${errText(e)}` };
|
|
557
|
+
}
|
|
558
|
+
const known = sent?.status === "accepted" || sent?.status === "already-seen";
|
|
559
|
+
const detail = sent?.detail ?? (known || sent?.status === "rejected" ? undefined : `unknown broadcast status ${String(sent?.status)}`);
|
|
560
|
+
anchors.push({ ...ref, status: known ? sent.status : "rejected", ...(detail === undefined ? {} : { detail }) });
|
|
561
|
+
if (!known) {
|
|
562
|
+
const reason = `anchor ${ref.kind} ${ref.txid.slice(0, 8)} was not accepted by the network${detail ? `: ${detail}` : ""}`;
|
|
563
|
+
return { ok: false, reason, type: result.type, issuerPubKeyHex: result.issuerPubKeyHex, anchors };
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
return { ...result, anchors };
|
|
567
|
+
}
|
|
568
|
+
/** The offline scan behind verifyEvents. `anchorTxsOut` receives the anchor Transactions, in `anchors` order. */
|
|
569
|
+
function scan(txsIn, opts, anchorTxsOut) {
|
|
570
|
+
return failClosed(() => scanBatch(txsIn, opts, anchorTxsOut));
|
|
571
|
+
}
|
|
572
|
+
function scanBatch(txsIn, opts, anchorTxsOut) {
|
|
218
573
|
if (!Array.isArray(txsIn))
|
|
219
574
|
return { ok: false, reason: "batch must be an array of transactions" };
|
|
220
575
|
let txs;
|
|
@@ -222,23 +577,61 @@ export function verifyEvents(txsIn, opts = {}) {
|
|
|
222
577
|
txs = txsIn.map(toTx);
|
|
223
578
|
}
|
|
224
579
|
catch (e) {
|
|
225
|
-
return { ok: false, reason: e
|
|
580
|
+
return { ok: false, reason: e.message }; // toTx throws ParseError only
|
|
226
581
|
}
|
|
227
582
|
if (txs.length === 0)
|
|
228
583
|
return { ok: false, reason: "empty batch" };
|
|
229
584
|
const byId = new Map(txs.map((t) => [t.id("hex"), t]));
|
|
230
|
-
const
|
|
585
|
+
const tokensOf = (list) => {
|
|
586
|
+
const found = [];
|
|
587
|
+
for (const tx of list) {
|
|
588
|
+
const txid = tx.id("hex");
|
|
589
|
+
tx.outputs.forEach((o, vout) => {
|
|
590
|
+
const type = recognizeType(o.lockingScript, opts.expectedType);
|
|
591
|
+
if (type)
|
|
592
|
+
found.push({ txid, vout, type, lock: o.lockingScript });
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
return found;
|
|
596
|
+
};
|
|
597
|
+
let tokens = tokensOf(txs);
|
|
598
|
+
// A batch of melts only has no token OUTPUT: read the type off the token a melt spends (its attached anchor).
|
|
599
|
+
let type = tokens[0]?.type;
|
|
231
600
|
for (const tx of txs) {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
601
|
+
if (type)
|
|
602
|
+
break;
|
|
603
|
+
for (const input of tx.inputs) {
|
|
604
|
+
const lock = input.sourceTransaction?.outputs?.[input.sourceOutputIndex]?.lockingScript;
|
|
605
|
+
type = (lock && recognizeType(lock, opts.expectedType)) || undefined;
|
|
235
606
|
if (type)
|
|
236
|
-
|
|
237
|
-
}
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
238
609
|
}
|
|
239
|
-
if (
|
|
610
|
+
if (!type)
|
|
240
611
|
return { ok: false, reason: "no BOLT token output recognised" };
|
|
241
|
-
|
|
612
|
+
// THE ANCHOR STEP. The anchor is the settle N-1 (or the mint) whose token output is SPENT BY a commit or a melt of
|
|
613
|
+
// the batch. The anchor itself is never a melt: a melt has no token output. When it was supplied only as an
|
|
614
|
+
// attached source (or inside a BEEF), pull it INTO the batch so it gets every check an event tx gets: golden
|
|
615
|
+
// fingerprint, issuer pin, arrangement, sources, script execution.
|
|
616
|
+
const promoted = new Set();
|
|
617
|
+
for (const tx of [...txs]) {
|
|
618
|
+
const kind = categorise(tx, type, byId)?.shape.kind;
|
|
619
|
+
if (kind !== "commit" && kind !== "melt")
|
|
620
|
+
continue;
|
|
621
|
+
for (const input of tx.inputs) {
|
|
622
|
+
const src = input.sourceTransaction;
|
|
623
|
+
if (!src || classifyIn(input, type, byId) !== "token")
|
|
624
|
+
continue;
|
|
625
|
+
const sid = src.id("hex");
|
|
626
|
+
if (byId.has(sid))
|
|
627
|
+
continue;
|
|
628
|
+
byId.set(sid, src);
|
|
629
|
+
promoted.add(sid);
|
|
630
|
+
txs.unshift(src);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
if (promoted.size > 0)
|
|
634
|
+
tokens = tokensOf(txs);
|
|
242
635
|
if (tokens.some((t) => t.type !== type))
|
|
243
636
|
return { ok: false, reason: "mixed token types in batch" };
|
|
244
637
|
/* v8 ignore next 2 -- recognizeType() already filtered by expectedType, so this is unreachable; kept as defense-in-depth */
|
|
@@ -260,6 +653,9 @@ export function verifyEvents(txsIn, opts = {}) {
|
|
|
260
653
|
for (const { tx, cat } of cats)
|
|
261
654
|
if (!cat)
|
|
262
655
|
return { ok: false, reason: `tx ${tx.id("hex").slice(0, 8)} is not a BOLT token tx`, type };
|
|
656
|
+
const lineage = lineageFailure(txs, type, byId);
|
|
657
|
+
if (lineage)
|
|
658
|
+
return { ok: false, reason: lineage, type, issuerPubKeyHex };
|
|
263
659
|
// Pair the events: every settle links back to a commit in the batch, and every commit is settled.
|
|
264
660
|
// (Checked before the per-interface arrangement so a structurally-incomplete batch reports the
|
|
265
661
|
// missing-pair reason, not an orphaned-input one.)
|
|
@@ -267,12 +663,37 @@ export function verifyEvents(txsIn, opts = {}) {
|
|
|
267
663
|
const commits = cats.filter((c) => c.cat.shape.kind === "commit");
|
|
268
664
|
const settled = new Set();
|
|
269
665
|
const events = [];
|
|
666
|
+
const anchors = [];
|
|
667
|
+
const anchorTxs = [];
|
|
668
|
+
const addAnchor = (tx, kind) => {
|
|
669
|
+
anchors.push({ txid: tx.id("hex"), kind });
|
|
670
|
+
anchorTxs.push(tx);
|
|
671
|
+
};
|
|
672
|
+
// A token output of `t` is spent by a commit / melt of the batch: `t` is what that spend stands on.
|
|
673
|
+
const spentAsToken = (t) => {
|
|
674
|
+
const id = t.id("hex");
|
|
675
|
+
return cats.some((c) => (c.cat.shape.kind === "commit" || c.cat.shape.kind === "melt") &&
|
|
676
|
+
c.tx.inputs.some((i) => {
|
|
677
|
+
const lock = t.outputs[i.sourceOutputIndex]?.lockingScript;
|
|
678
|
+
return spentTxid(i) === id && !!lock && !!recognizeType(lock, type);
|
|
679
|
+
}));
|
|
680
|
+
};
|
|
681
|
+
// An anchor must be a SETTLED token (or a mint): a token still in a commit state is not something to build on.
|
|
682
|
+
for (const { tx, cat } of cats)
|
|
683
|
+
if (promoted.has(tx.id("hex")) && cat.shape.kind !== "settle" && cat.shape.kind !== "mint")
|
|
684
|
+
return { ok: false, reason: `anchor ${tx.id("hex").slice(0, 8)} is not a settled token or a mint (it is a ${cat.shape.kind})`, type };
|
|
270
685
|
for (const s of cats.filter((c) => c.cat.shape.kind === "settle")) {
|
|
271
686
|
const sLock = s.tx.outputs[s.cat.tokenOutIdx].lockingScript;
|
|
272
687
|
const p = parseOutpoint(field(sLock, type, "parent"));
|
|
273
688
|
const commit = commits.find((c) => c.tx.id("hex") === p.txidHex && c.cat.tokenOutIdx === p.vout);
|
|
274
|
-
if (!commit)
|
|
689
|
+
if (!commit) {
|
|
690
|
+
// The one settle allowed without its commit: the ANCHOR (settle N-1), which a commit / melt of the batch spends.
|
|
691
|
+
if (spentAsToken(s.tx)) {
|
|
692
|
+
addAnchor(s.tx, "settle");
|
|
693
|
+
continue;
|
|
694
|
+
}
|
|
275
695
|
return { ok: false, reason: `settle ${s.tx.id("hex").slice(0, 8)} links to no commit in the batch (orphan settle)`, type };
|
|
696
|
+
}
|
|
276
697
|
settled.add(key(commit.tx.id("hex"), commit.cat.tokenOutIdx));
|
|
277
698
|
const cLock = commit.tx.outputs[commit.cat.tokenOutIdx].lockingScript;
|
|
278
699
|
events.push({ kind: actionKind(fieldHex(cLock, type, "txoType")), txids: [commit.tx.id("hex"), s.tx.id("hex")] });
|
|
@@ -280,15 +701,69 @@ export function verifyEvents(txsIn, opts = {}) {
|
|
|
280
701
|
for (const c of commits)
|
|
281
702
|
if (!settled.has(key(c.tx.id("hex"), c.cat.tokenOutIdx)))
|
|
282
703
|
return { ok: false, reason: `commit ${c.tx.id("hex").slice(0, 8)} has no settle in the batch (unsettled commit)`, type };
|
|
704
|
+
// Which anchors are HEADER-PROVEN (a merkle path into a known block header)? Consensus validated those, so their
|
|
705
|
+
// inputs are not re-examined and their sources need not be supplied. Every anchor is asked, up front.
|
|
706
|
+
const proofs = new Map();
|
|
707
|
+
for (const { tx, cat } of cats)
|
|
708
|
+
if (cat.shape.kind === "mint" || anchorTxs.includes(tx))
|
|
709
|
+
proofs.set(tx, headerProof(tx, opts));
|
|
710
|
+
const headerProven = (tx) => proofs.get(tx)?.proven === true;
|
|
711
|
+
const toExecute = txs.filter((tx) => !headerProven(tx));
|
|
283
712
|
// Per-interface arrangement: categorise + fingerprint every tx.
|
|
284
713
|
for (const { tx, cat } of cats) {
|
|
285
|
-
const reason = checkArrangement(tx, type, cat.shape, byId);
|
|
714
|
+
const reason = checkArrangement(tx, type, cat.shape, byId, headerProven(tx));
|
|
286
715
|
if (reason)
|
|
287
716
|
return { ok: false, reason, type };
|
|
288
717
|
}
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
718
|
+
// Every mint must be spent by a commit in the batch (a mint alone does not authenticate the issuer key).
|
|
719
|
+
const stray = unauthenticatedMint(txs, type, byId);
|
|
720
|
+
if (stray)
|
|
721
|
+
return { ok: false, reason: unauthenticatedReason(stray), type, issuerPubKeyHex, unauthenticated: true };
|
|
722
|
+
// Every input's source tx must be supplied (so its script can be executed), else the batch cannot be authenticated.
|
|
723
|
+
const need = requireSources(toExecute, byId);
|
|
724
|
+
if (need.failure)
|
|
725
|
+
return { ok: false, reason: need.failure, type, issuerPubKeyHex };
|
|
726
|
+
// Standalone single-tx events (genesis mints - each already shown to be spent by a commit - and terminal melts).
|
|
727
|
+
// A mint is also an ANCHOR (the batch starts at genesis); one pulled in from a source is an anchor but not an event.
|
|
728
|
+
for (const { tx, cat } of cats) {
|
|
729
|
+
if (cat.shape.kind === "mint")
|
|
730
|
+
addAnchor(tx, "mint");
|
|
731
|
+
if ((cat.shape.kind === "mint" || cat.shape.kind === "melt") && !promoted.has(tx.id("hex")))
|
|
292
732
|
events.push({ kind: cat.shape.kind, txids: [tx.id("hex")] });
|
|
293
|
-
|
|
733
|
+
}
|
|
734
|
+
// Execute every supplied input: structure alone does not show the scripts (signatures, covenants) are valid.
|
|
735
|
+
const failure = executeInputs(toExecute, byId);
|
|
736
|
+
if (failure)
|
|
737
|
+
return { ok: false, reason: failure, type, issuerPubKeyHex };
|
|
738
|
+
// An anchor that is not header-proven must be one the network will mine on sight (see anchorNotMinable).
|
|
739
|
+
for (const anchor of anchorTxs) {
|
|
740
|
+
if (headerProven(anchor))
|
|
741
|
+
continue;
|
|
742
|
+
const refused = anchorNotMinable(anchor, type, byId, proofs.get(anchor).why);
|
|
743
|
+
if (refused)
|
|
744
|
+
return { ok: false, reason: refused, type, issuerPubKeyHex };
|
|
745
|
+
}
|
|
746
|
+
// VALUE CONSERVATION for the event txs: checked and REPORTED, refused only on request. A tx whose outputs exceed
|
|
747
|
+
// its inputs executes fine off chain (a never-broadcast commit / settle certifying auth data) but no node would
|
|
748
|
+
// accept it as built. (Anchors were checked above; a header-proven anchor was validated by consensus.)
|
|
749
|
+
const offChainOnly = [];
|
|
750
|
+
for (const tx of toExecute) {
|
|
751
|
+
if (anchorTxs.includes(tx))
|
|
752
|
+
continue;
|
|
753
|
+
const { inputSats, outputSats } = valueOf(tx, byId);
|
|
754
|
+
if (outputSats > inputSats)
|
|
755
|
+
offChainOnly.push({ txid: tx.id("hex"), inputSats, outputSats });
|
|
756
|
+
}
|
|
757
|
+
if (opts.requireBroadcastable && offChainOnly.length > 0) {
|
|
758
|
+
const t = offChainOnly[0];
|
|
759
|
+
return {
|
|
760
|
+
ok: false, type, issuerPubKeyHex, offChainOnly,
|
|
761
|
+
reason: `tx ${t.txid.slice(0, 8)} creates value (inputs ${t.inputSats} sat, outputs ${t.outputSats} sat): it cannot be broadcast as built`,
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
anchorTxsOut?.push(...anchorTxs);
|
|
765
|
+
return {
|
|
766
|
+
ok: true, type, issuerPubKeyHex, events, sources: need.sources, anchors,
|
|
767
|
+
...(offChainOnly.length > 0 ? { offChainOnly } : {}),
|
|
768
|
+
};
|
|
294
769
|
}
|