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.
Files changed (45) hide show
  1. package/CHANGELOG.md +568 -39
  2. package/LICENSE.txt +56 -56
  3. package/README.md +310 -206
  4. package/dist/index.d.ts +15 -7
  5. package/dist/index.js +14 -5
  6. package/dist/lib/boltLib.d.ts +29 -3
  7. package/dist/lib/boltLib.js +60 -12
  8. package/dist/lib/genesis.d.ts +20 -0
  9. package/dist/lib/genesis.js +45 -0
  10. package/dist/lib/multi/multiBoltLib.d.ts +22 -2
  11. package/dist/lib/multi/multiBoltLib.js +114 -129
  12. package/dist/lib/scanner/beef.d.ts +11 -0
  13. package/dist/lib/scanner/beef.js +63 -0
  14. package/dist/lib/scanner/fingerprints.d.ts +12 -2
  15. package/dist/lib/scanner/fingerprints.js +45 -12
  16. package/dist/lib/scanner/verifyEvents.d.ts +84 -6
  17. package/dist/lib/scanner/verifyEvents.js +520 -45
  18. package/dist/lib/single/singleAncestor.d.ts +27 -3
  19. package/dist/lib/single/singleAncestor.js +49 -18
  20. package/dist/lib/single/singleSpend.d.ts +12 -3
  21. package/dist/lib/single/singleSpend.js +48 -16
  22. package/dist/tokens/BOLT.d.ts +6 -5
  23. package/dist/tokens/GenesisMultiBOLT.d.ts +29 -0
  24. package/dist/tokens/GenesisMultiBOLT.js +48 -0
  25. package/dist/tokens/MultiBOLT.d.ts +17 -12
  26. package/dist/tokens/MultiBOLT.js +82 -74
  27. package/dist/tokens/templates/AuthBolt.sx.template.d.ts +35 -0
  28. package/dist/tokens/templates/AuthBolt.sx.template.js +82 -0
  29. package/dist/tokens/templates/FixedMulti.sx.template.d.ts +13 -0
  30. package/dist/tokens/templates/FixedMulti.sx.template.js +23 -0
  31. package/dist/tokens/templates/MinSimple.sx.template.d.ts +10 -1
  32. package/dist/tokens/templates/MinSimple.sx.template.js +15 -1
  33. package/dist/tokens/templates/OpenMulti.sx.template.d.ts +13 -0
  34. package/dist/tokens/templates/OpenMulti.sx.template.js +23 -0
  35. package/dist/tokens/templates/SerialBolt.sx.template.d.ts +23 -0
  36. package/dist/tokens/templates/SerialBolt.sx.template.js +61 -0
  37. package/dist/tokens/templates/SimpleMulti.sx.template.d.ts +12 -6
  38. package/dist/tokens/templates/SimpleMulti.sx.template.js +33 -25
  39. package/dist/tokens/templates/pay2Proof.d.ts +2 -1
  40. package/dist/tokens/templates/pay2Proof.js +1 -1
  41. package/package.json +64 -58
  42. package/dist/tokens/templates/MinSimpleBalance.sx.template.d.ts +0 -24
  43. package/dist/tokens/templates/MinSimpleBalance.sx.template.js +0 -59
  44. package/dist/tokens/templates/MinSimpleDiscount.sx.template.d.ts +0 -23
  45. package/dist/tokens/templates/MinSimpleDiscount.sx.template.js +0 -58
package/README.md CHANGED
@@ -1,206 +1,310 @@
1
- # b017; Bitcoin Original Layer-1 Token Protocol
2
-
3
- [![CI](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml)
4
- [![codecov](https://codecov.io/gh/BOLT-Association/b017/branch/main/graph/badge.svg)](https://codecov.io/gh/BOLT-Association/b017)
5
- [![npm version](https://img.shields.io/npm/v/b017.svg?logo=npm)](https://www.npmjs.com/package/b017)
6
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
7
-
8
- > **Status: `0.0.0-b1` (beta).** Considered Live-Network-Testing Ready (Production next). The API is working and fully tested
9
- > (126/126 unit tests, **99% statement / 98% function / 95% branch coverage**) but may still change before `0.1.0`. See
10
- > [`docs/ROADMAP.md`](docs/ROADMAP.md) for what's next.
11
-
12
- Standalone TypeScript library for the **Bitcoin Original Layer-1 Token** protocol on BSV — a fungible & optimised
13
- **SimpleMultiBOLT** (16-byte balance (x2 Bitcoin's base layer limit); mint / transfer / split / merge / melt), a family of
14
- minimal **NFT** templates, and an off-chain **scanner** that recognises and verifies
15
- **transactional events**. The only runtime dependency is a peer `@bsv/sdk`.
16
-
17
- Every protocol action is a **transactional event**: a transfer / split / merge is a **commit → settle
18
- pair** of txs, while a mint (genesis) and a melt (terminal) are single-tx events. Because events
19
- share this shape, they can be collected into a **batch**, transmitted together, and parsed & validated for
20
- authenticity & provenance by a multistep inspection.
21
-
22
- **Why these tokens can't be counterfeited:** the token state (issuer, lineage, owner, balance)
23
- is bound into a self-validating Bitcoin Script covenant via a dual hash-commitment, so forging
24
- a token would require breaking SHA-256 or ECDSA. See [`docs/unforgeability.md`](docs/unforgeability.md)
25
- for the argument and the forgery tests that demonstrate it, and
26
- [`docs/formal-proof.md`](docs/formal-proof.md) for the rigorous treatment (4 theorems, 7 lemmas,
27
- full attack-vector analysis).
28
-
29
- ## Install / build
30
-
31
- ```
32
- npm install
33
- npm run build # clean + tsc -> dist/ (JS + .d.ts)
34
- npm test # vitest (126 tests)
35
- npm run test:coverage # vitest + v8 coverage -> coverage/ (text + HTML report)
36
- ```
37
-
38
- `@bsv/sdk` is a **peer dependency** — your application provides the single shared instance.
39
-
40
- ## Usage — the fungible token
41
-
42
- ```ts
43
- import { SimpleMultiBOLT } from "b017";
44
- import { PrivateKey } from "@bsv/sdk";
45
-
46
- const issuer = PrivateKey.fromRandom();
47
-
48
- // mint(privKey, fundingTx, mintData, balance16) — balance is 16 LE bytes
49
- const token = await new SimpleMultiBOLT().mint(issuer, fundingTx, "", balance16);
50
-
51
- // transfer = commit + settle to a new owner key
52
- await token.transfer(recipientKey);
53
-
54
- // split into two tokens (amount16 = the second piece's balance, 16 LE bytes).
55
- // fundingSource is { tx, vout, key } — a UTXO the operation can spend for fees.
56
- const [main, piece] = await token.split(keyA, keyB, amount16, fundingSource);
57
-
58
- // merge `piece` back into `main` under a new owner key
59
- const merged = await main.merge(piece, keyC, fundingSource);
60
-
61
- // melt — spend the token output away (no token survives)
62
- await merged.melt();
63
- ```
64
-
65
- Every operation builds a real, script-valid Bitcoin transaction, verified by the `@bsv/sdk`
66
- Spend engine before it is returned. **Broadcasting is the caller's responsibility** — the
67
- library never touches the network. The signed `Transaction` is available as `token.tx`.
68
-
69
- ## Usage — recognising & verifying events (the scanner)
70
-
71
- ```ts
72
- import {
73
- recognizeType, // (lockingScript, expected?) -> TokenType | null
74
- verifyEvent, // validate ONE event (a mint, a commit→settle pair, or a melt)
75
- verifyEvents, // validate a BATCH of events end to end
76
- } from "b017";
77
-
78
- const type = recognizeType(tx.outputs[0].lockingScript); // "SimpleMultiBOLT" | "MinSimpleBOLT" | ... | null
79
-
80
- // Inspect a batch of transactional events for authenticity. Recognises the type, pins the issuer
81
- // across the whole batch, fingerprints every interface, then pairs the events: every commit must
82
- // be matched by a settle that links back via parentOutpoint, and vice-versa.
83
- const r = verifyEvents(txs, { trustedIssuerPubKey });
84
- // -> { ok, type, issuerPubKeyHex, events: [{ kind: "transfer" | "split" | ..., txids }] }
85
- ```
86
-
87
- Recognition is strict: a script matches only if **both** the leading data-push layout **and**
88
- the sha256 of the static contract code match a registered type, so a tampered contract body or
89
- a non-token script is rejected. An event is well-formed only if its txs pair up — a lone mint or
90
- melt is a valid single-tx event, but an orphan settle or an unsettled commit is rejected.
91
-
92
- A commit and its settle are bound **two** independent ways: the **token lineage** (the settle's
93
- token `parentOutpoint` references the commit's token output — the binding the scanner asserts), and,
94
- in general, a **funding chain** (the settle's funding input spends the commit's **change** output, so
95
- the pair is chained at the satoshi level too). The funding chain is a construction property — a
96
- caller can fund the settle from elsewhere — so the scanner does not require it.
97
-
98
- ## What's inside
99
-
100
- The tree is organised by role: `tokens/` (token classes + their contract templates), `lib/` (the
101
- reusable engine — shared primitives plus the **single**-token, **multi**-token, and **scanner**
102
- sub-libraries).
103
-
104
- | Path | Role |
105
- | --- | --- |
106
- | `src/tokens/MultiBOLT.ts` | `SimpleMultiBOLT` — the fungible token class (mint/transfer/split/merge/melt). |
107
- | `src/tokens/BOLT.ts` | `BOLT` — the abstract token base class. |
108
- | `src/tokens/templates/SimpleMulti.sx.template.ts` | Runtime lock/unlock/melt assembler for the fungible contract (compiled ASM suffix embedded). |
109
- | `src/tokens/templates/MinSimple*.sx.template.ts` | Single-token (NFT) lock templates: `MinSimple`, `MinSimpleDiscount`, `MinSimpleBalance`. |
110
- | `src/tokens/templates/pay2Proof.ts` | The `pay2Proof` UTXO template (the b017 marker proof output). |
111
- | `src/lib/boltLib.ts` | Layout-agnostic primitives (`verifyTx`, `buildOutpoint`, `splitCtx`, …) shared by both streams. |
112
- | `src/lib/single/` | Single-token (NFT) engine: `singleSpend` (unlock assembler) + `singleAncestor` (back-reach reconstruction). |
113
- | `src/lib/multi/multiBoltLib.ts` | Fungible-token engine: ancestor reconstruction for `SimpleMultiBOLT`. |
114
- | `src/lib/scanner/fingerprints.ts` | Per-type recognition (`recognizeType`, golden `recognizeP2P`) + the type `REGISTRY`. |
115
- | `src/lib/scanner/verifyEvents.ts` | Off-chain event validator: batch verifier + per-event checker (`verifyEvents`, `verifyEvent`). |
116
-
117
- > Naming note: the `SimpleMultiBOLT` **class** currently lives in `tokens/MultiBOLT.ts`.
118
- > Resolving that file/class name mismatch is tracked in the ROADMAP.
119
-
120
- The full public API is the named exports of [`src/index.ts`](src/index.ts).
121
-
122
- ## Testing & coverage
123
-
124
- The whole codebase is unit-tested with [Vitest](https://vitest.dev). The `test/` tree mirrors `src/`
125
- by concern (`test/tokens`, `test/templates`, `test/lib`, `test/lib`-level `scanner/`), with shared
126
- fixtures in `test/fixtures` and helpers in `test/helpers`.
127
-
128
- ```
129
- npm test # 126 tests across 18 files
130
- npm run test:coverage # the same suite + a v8 coverage report (text to stdout, HTML in coverage/)
131
- ```
132
-
133
- Latest run — **every source module is covered**, all above 98% statements:
134
-
135
- | Metric | Coverage |
136
- | --- | --- |
137
- | Statements | **99.1%** (1737/1752) |
138
- | Functions | **98.0%** (96/98) |
139
- | Lines | **99.1%** |
140
- | Branches | **95.1%** (645/678) |
141
-
142
- The handful of uncovered branches are fail-safe guards (e.g. a `0xff` >4 GB script-length prefix, or a
143
- type/issuer check an upstream fingerprint already guarantees), annotated `v8 ignore` with the reason inline.
144
-
145
- What the suite verifies: each contract template is byte-faithful to its sx-compiled artifact and
146
- spends under the `@bsv/sdk` Spend engine; the scanner's accept/reject decisions match the on-chain
147
- contract over genuine lineages and every counterfeit class (including **strict golden p2Proof
148
- fingerprinting** on commit proof outputs and settle proof inputs); and the library **fails closed**
149
- on malformed input (bad hex, non-arrays, tampered markers) rather than throwing.
150
-
151
- ## Why Teranode + BOLT + Emergent Automation is the killer stablecoin platform
152
-
153
- A stablecoin is only as good as the three layers underneath it: where it **settles**, how its
154
- **integrity** is proven, and who can **operate** it. Most platforms nail one and compromise the other
155
- two. This stack is the first to get all three right at once — because each layer removes the exact
156
- bottleneck the next one needs gone.
157
-
158
- **1. Teranode — unbounded settlement, fixed micro-fees.** Teranode is BSV's horizontally-scaling
159
- node: throughput grows with hardware instead of hitting a protocol ceiling, so the base layer
160
- absorbs millions of transactions per second at sub-cent, *non-auctioned* fees. A stablecoin meant to
161
- be spent — not just held — needs settlement that never congests and never surprises you with a gas
162
- spike. There is no block-space auction to front-run, no L2 to bridge into, no rollup withdrawal
163
- delay. Final settlement *is* the base layer.
164
-
165
- **2. BOLT — the asset that proves itself.** A BOLT token is a real Bitcoin UTXO whose entire validity
166
- (issuer, lineage, owner, balance) is bound into a self-validating Script covenant via a dual
167
- hash-commitment. Forging one means breaking SHA-256 or ECDSA — not out-voting a validator set or
168
- finding a contract bug. This is the decisive difference from the two incumbent designs:
169
-
170
- - **vs. account-based stablecoins (centralised ledgers):** no issuer database to trust, freeze, or
171
- reconcile. The coin carries its own proof; anyone can verify provenance from the chain.
172
- - **vs. smart-contract stablecoins (global-state chains):** no shared global contract to congest, no
173
- re-entrancy/upgrade-key risk, no gas war. Each token validates **independently and in parallel** —
174
- which is exactly what lets Teranode's parallelism actually scale. Validation is *local and
175
- SPV-friendly*: this library's off-chain **scanner** (`verifyEvents`) reaches the same accept/reject
176
- verdict as the on-chain contract, with **strict golden p2Proof fingerprinting** on every commit
177
- proof output and settle proof input — so a holder verifies a payment with a light client, not a
178
- full chain replay. The 16-byte balance field carries denominations up to 2× Bitcoin's base limit,
179
- enough for any fiat unit at any scale.
180
-
181
- **3. Emergent Automation — an economy that runs itself.** Because a BOLT token is a pure, stateless
182
- UTXO with deterministic, self-contained validation and a single peer dependency (`@bsv/sdk`), it is
183
- the ideal instrument for autonomous, machine-to-machine commerce. Software agents can mint, pay,
184
- split, merge, and **verify** stablecoin value at machine speed with no custodian, no indexer, and no
185
- human in the loop — every transfer is a self-proving *event* (a commit→settle pair) that another
186
- agent can validate locally before acting on it. Provenance becomes a function call, not a trust
187
- relationship.
188
-
189
- **The combination is the point.** Settlement that never congests (Teranode) + an asset that proves
190
- its own integrity without a trusted third party or a global-state chain (BOLT) + value that
191
- autonomous agents can move and verify without intermediaries (Emergent Automation). A stablecoin
192
- needs cheap unbounded settlement, trustless verifiable integrity, and programmable automation
193
- *simultaneously* — and this is the only stack where all three reinforce each other instead of
194
- trading off. That is what makes it not just *a* stablecoin platform, but the killer one.
195
-
196
- ## License
197
-
198
- Open BSV License Version 5 — see [`LICENSE.txt`](LICENSE.txt).
199
-
200
- <p align="center">
201
- <picture>
202
- <source media="(prefers-color-scheme: light)" srcset="docs/assets/bolt-logo-light.png">
203
- <source media="(prefers-color-scheme: dark)" srcset="docs/assets/bolt-logo.png">
204
- <img src="docs/assets/bolt-logo-light.png" alt="Bolt" width="420">
205
- </picture>
206
- </p>
1
+ # b017; Bitcoin Original Layer-1 Token Protocol
2
+
3
+ [![CI](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml)
4
+ [![coverage](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/BOLT-Association/b017/badges/coverage.json)](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml)
5
+ [![npm version](https://img.shields.io/npm/v/b017.svg?logo=npm)](https://www.npmjs.com/package/b017)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.7-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
7
+
8
+ > **Status: `0.2.0`.** Considered Live-Network-Testing Ready (Production next). The API is working and fully tested
9
+ > (795/795 unit tests, **100% statement / 100% function / 100% branch coverage**) but may still change before `1.0.0`. See
10
+ > [`docs/ROADMAP.md`](docs/ROADMAP.md) for what's next.
11
+
12
+ Standalone TypeScript library for the **Bitcoin Original Layer-1 Token** protocol on BSV — a fungible & optimised
13
+ **SimpleMultiBOLT** (16-byte balance (x2 Bitcoin's base layer limit); mint / transfer / split / merge / melt), a minimal
14
+ identity **NFT** (`MinSimpleBOLT`, zero-funding), its credential variant `AuthBOLT` (an arbitrary data field `authOrMiscData` of up to 75 bytes),
15
+ the **genesis family** that stores each token's own asset outpoint (`FixedBOLT`: one genesis per asset; `OpenBOLT`: one
16
+ issuer, many mints; `SerialBOLT`: an NFT serial), and an off-chain **scanner** that recognises and verifies
17
+ **transactional events**. The only runtime dependency is a peer `@bsv/sdk`.
18
+
19
+ Every protocol action is a **transactional event**: a transfer / split / merge is a **commit → settle
20
+ pair** of txs, while a mint (genesis) and a melt (terminal) are single-tx events. Because events
21
+ share this shape, they can be collected into a **batch**, transmitted together, and parsed & validated for
22
+ authenticity & provenance by a multistep inspection.
23
+
24
+ **Why these tokens can't be counterfeited:** the token state (issuer, lineage, owner, balance)
25
+ is bound into a self-validating Bitcoin Script covenant via a dual hash-commitment, so forging
26
+ a token would require breaking SHA-256 or ECDSA. See [`docs/unforgeability.md`](docs/unforgeability.md)
27
+ for the argument and the forgery tests, [`docs/formal-proof.md`](docs/formal-proof.md) for the
28
+ rigorous treatment (4 theorems, 7 lemmas, full attack-vector analysis), and
29
+ [`lean/README.md`](lean/README.md) for the **machine-checked** version: Theorems 1–5 proved in Lean 4
30
+ of the protocol model, and, for every shipped script, a proof that each token is built by the script
31
+ from the one before it and that a genesis moves only under the issuer's key. The script proofs hold per
32
+ input, under listed assumptions and today's BSV rules, and a chain of real spends is proved a valid run,
33
+ so the run-level theorems hold of real tokens. That file states exactly what is proved and what is still
34
+ trusted.
35
+ [`docs/issuer-guard.md`](docs/issuer-guard.md) decodes the issuer guard of each family: the NFT-only
36
+ `is2ndTx` flag, and the broader zero-grandparent rule the fungible family carries instead.
37
+
38
+ This is **third-party per-token unforgeability**: each unit is internally well-formed and traces
39
+ to an issuer-signed mint. It is *not* a claim about **supply-honesty** (an issuer can mint many
40
+ independent genesis tokens — reserve/cap trust is an issuer matter) or **network-level security**
41
+ (reorg resistance inherits honest-majority hash power). See [`formal-proof.md`](docs/formal-proof.md)
42
+ §1.6 for the exact boundary.
43
+
44
+ ## Install / build
45
+
46
+ ```
47
+ npm install
48
+ npm run build # clean + tsc -> dist/ (JS + .d.ts)
49
+ npm test # vitest (795 tests)
50
+ npm run test:coverage # vitest + v8 coverage -> coverage/ (text + HTML report)
51
+ npm run lean:vectors # regenerate the Lean proof's transaction vectors (lean/BoltProof/Bridge/Generated/)
52
+ ```
53
+
54
+ `@bsv/sdk` is a **peer dependency** — your application provides the single shared instance.
55
+
56
+ ## Usage — the fungible token
57
+
58
+ ```ts
59
+ import { SimpleMultiBOLT } from "b017";
60
+ import { PrivateKey } from "@bsv/sdk";
61
+
62
+ const issuer = PrivateKey.fromRandom();
63
+
64
+ // mint(privKey, fundingTx, mintData, balance16) — balance is 16 LE bytes
65
+ const token = await new SimpleMultiBOLT().mint(issuer, fundingTx, "", balance16);
66
+
67
+ // transfer = commit + settle to a new owner key
68
+ await token.transfer(recipientKey);
69
+
70
+ // split into two tokens (amount16 = the second piece's balance, 16 LE bytes).
71
+ // fundingSource is { tx, vout, key } — a UTXO the operation can spend for fees.
72
+ const [main, piece] = await token.split(keyA, keyB, amount16, fundingSource);
73
+
74
+ // merge `piece` back into `main` under a new owner key
75
+ const merged = await main.merge(piece, keyC, fundingSource);
76
+
77
+ // melt — spend the token output away (no token survives)
78
+ await merged.melt();
79
+ ```
80
+
81
+ Every operation builds a real, script-valid Bitcoin transaction, verified by the `@bsv/sdk`
82
+ Spend engine before it is returned. **Broadcasting is the caller's responsibility** — the
83
+ library never touches the network. The signed `Transaction` is available as `token.tx`.
84
+
85
+ ## Usage — recognising & verifying events (the scanner)
86
+
87
+ ```ts
88
+ import {
89
+ recognizeType, // (lockingScript, expected?) -> TokenType | null
90
+ recognizeToken, // (lockingScript, expected?) -> { type, phase? } | null
91
+ verifyEvent, // validate ONE event (a commit→settle pair, or a melt) - same verdict as verifyEvents
92
+ verifyEvents, // validate a BATCH of events end to end (offline)
93
+ verifyAndBroadcast, // verifyEvents + your broadcast of the batch's anchor (settle N-1 / the mint)
94
+ } from "b017";
95
+
96
+ const type = recognizeType(tx.outputs[0].lockingScript); // "SimpleMultiBOLT" | "MinSimpleBOLT" | ... | null
97
+ // genesis family: also the phase - "mint" (null asset outpoint, any mintData) or "postMint" (empty mintData)
98
+ const { type: t, phase } = recognizeToken(tx.outputs[0].lockingScript) ?? {};
99
+
100
+ // Inspect a batch of transactional events for authenticity. Recognises the type, pins the issuer
101
+ // across the whole batch, fingerprints every interface, then pairs the events: every commit must
102
+ // be matched by a settle that links back via parentOutpoint, and vice-versa.
103
+ const r = verifyEvents(txs, { trustedIssuerPubKey });
104
+ // -> { ok, type, issuerPubKeyHex, events: [{ kind: "transfer" | "split" | ..., txids }] }
105
+ ```
106
+
107
+ Recognition is strict: a script matches only if **both** the leading data-push layout **and**
108
+ the sha256 of the static contract code match a registered type, so a tampered contract body or
109
+ a non-token script is rejected. An event is well-formed only if its txs pair up - a melt is a
110
+ valid single-tx event (standing on the settle it spends, its anchor), but an orphan settle or an unsettled commit is
111
+ rejected, by `verifyEvent` as well as `verifyEvents`. A **mint** is accepted only
112
+ with a commit in the same event/batch that spends it; a lone mint returns `{ ok: false, unauthenticated: true }`
113
+ (see "Receiving a token off-chain" below). The scanner also **executes** every input whose source tx is supplied (the
114
+ covenant and the signatures, on the `@bsv/sdk` Spend engine), because structure alone cannot tell a forged commit
115
+ from a real one and off-chain txs have not been validated by a node; a failure returns `ok: false` with
116
+ `script execution failed: tx <id> input <n>: ...`. **Every input's source tx must be supplied** (attached as
117
+ `sourceTransaction`, or another tx in the batch, or inside a BEEF); an input whose source is missing is refused
118
+ (`source tx <id> of tx <id> input <n> was not supplied`). Send the package as **BEEF**: each event tx may be a
119
+ Transaction, raw hex, or Atomic BEEF over BEEF V2 (hex / bytes), whose subject is the tx; `toAtomicBeef(tx)` /
120
+ `fromBeef(bytes)` / `isBeef(x)` are exported. BEEF V1 (BRC-62) and a BEEF that is not self-contained (an unproven tx
121
+ that does not have all its inputs in the BEEF) are refused. The result's `sources` lists the txs the event spends that
122
+ are not part of it, each with `proven` (it carries a BUMP). The scanner checks a BUMP against a block header only
123
+ for an **anchor**, and only when you supply your headers (`isKnownBlockRoot`, or a `chainTracker` to
124
+ `verifyAndBroadcast`). The BUMPs of the other `sources` are **not** checked: verify those with your `ChainTracker`
125
+ (`Beef.verify` / `merklePath.verify`).
126
+
127
+ A commit and its settle are bound **two** independent ways: the **token lineage** (the settle's
128
+ token `parentOutpoint` references the commit's token output — the binding the scanner asserts), and,
129
+ in general, a **funding chain** (the settle's funding input spends the commit's **change** output, so
130
+ the pair is chained at the satoshi level too). The funding chain is a construction property — a
131
+ caller can fund the settle from elsewhere — so the scanner does not require it.
132
+
133
+ ### Receiving a token off-chain (SPV): what must travel with it
134
+
135
+ Sending someone a **minted** token over SPV does not prove that the sender holds the issuer key. A mint is
136
+ just an output whose lock names an `issuerPubKey`; anyone can create one naming anybody's key (so
137
+ `verifyEvents` refuses a lone mint as `unauthenticated`). The issuer guard runs when the
138
+ genesis token is first **spent** (and again at the first settle, in both families; see
139
+ [`docs/issuer-guard.md`](docs/issuer-guard.md)), so the proof is the first **commit**:
140
+
141
+ - **Ownership of a minted token:** the mint must come with a **commit tx spending it**, signed by the issuer
142
+ key. This holds whether or not the commit is funded (an unfunded commit is SPV-only and never mined, but it
143
+ still executes the covenant, which demands `issuerPubKey == the signer` at genesis). `verifyEvents` runs that
144
+ covenant, so a commit forged by a stranger is refused on execution.
145
+ - **A token carrying `authOrMiscData` (`AuthBOLT`):** the value is created in a commit but authenticated only
146
+ by the **settle**, which rebuilds its grandparent commit and binds the value to that commit's txid. The commit's
147
+ own signature does **not** cover it. So the **signed commit and settle travel together as the data package**;
148
+ a commit alone, or a settle without its commit, does not authenticate the data.
149
+ - A later hop to a new holder repeats the pattern: commit + settle (and the p2pb proof input a back-reaching
150
+ settle spends), unfunded or funded, are what the recipient verifies.
151
+ - **The anchor travels too, and is broadcast.** The anchor is the token tx the package stands on: the settle before
152
+ its first commit (settle N-1), or the mint at genesis. So a package is `[mint, c1, s1]` or `[sN-1, cN, sN]`.
153
+ `verifyEvents` validates the anchor like an event tx (fingerprint, issuer, structure, script execution) and names
154
+ it in `anchors`, but it is offline and its execution reaches the anchor's own inputs only. Use
155
+ `verifyAndBroadcast(txs, broadcastAnchor)`: it runs `verifyEvents`, then your broadcaster sends each anchor and
156
+ reports `accepted`, `already-seen` or `rejected`. The anchor must be a tx the network has seen and will therefore
157
+ mine (or has already mined): that is what shows the history behind it is real. A rejected anchor, a throwing
158
+ broadcaster or an unknown status is `ok: false`. The events standing on the anchor need not be broadcast: they can
159
+ stay off chain, and be funded and broadcast only when the receiver, the sender or both require it.
160
+ - **An unfunded anchor needs an SPV proof.** An anchor with no funding input pays no fee, so the network has no
161
+ reason to mine it and seeing it proves nothing. Such an anchor can still be mined (a friendly miner), so it is
162
+ accepted only once it has been: it must carry a merkle path into a block header you know. Pass your headers as
163
+ `isKnownBlockRoot: (merkleRoot, height) => boolean`, or hand `verifyAndBroadcast` a `chainTracker` (the
164
+ `@bsv/sdk` ChainTracker shape). Without a verified proof the batch is refused (`unfunded anchor <id>: ...`), by
165
+ `verifyEvents`, `verifyEvent` and `verifyAndBroadcast` alike, and nothing is broadcast. Unfunded **events** on a
166
+ funded anchor are unaffected.
167
+ - **A header-proven anchor is taken as mined.** Any anchor (funded or not) whose merkle path proves it into a header
168
+ you know was validated by consensus: the scanner does not re-execute its inputs and does not need its sources. That
169
+ is what lets a mined anchor travel as BEEF, which stops at proven txs. Your header lookup is the trust root here:
170
+ answer `true` only for real block headers. A merkle path with no known header changes nothing (the anchor is
171
+ executed like any other, and its sources must be supplied). Only anchors get this; event txs are always executed.
172
+ - **Value conservation is checked.** An **anchor** whose outputs exceed its inputs is refused (`anchor <id> creates
173
+ value ...`): no node accepts that. An **event** tx that does so is not refused, only reported in
174
+ `offChainOnly: [{ txid, inputSats, outputSats }]`: a commit / settle that is never broadcast (an `AuthBOLT` event
175
+ certifying auth data) is valid off chain, it just cannot be broadcast as built. Pass `requireBroadcastable: true`
176
+ to refuse such a batch instead.
177
+ - **`SimpleMultiBOLT` requires funding and change.** Zero-funding hops are for the NFT types (`MinSimpleBOLT`,
178
+ `AuthBOLT`) only; a MultiBOLT settle never has to rebuild an unfunded commit.
179
+ - **Send it as BEEF** (Atomic BEEF over BEEF V2, `toAtomicBeef(tx)`): each tx travels with the txs it spends, back to
180
+ txs a block has proven (BUMP). The recipient needs every source to execute the scripts, so a bare tx is refused.
181
+
182
+ ## What's inside
183
+
184
+ The tree is organised by role: `tokens/` (token classes + their contract templates), `lib/` (the
185
+ reusable engine — shared primitives plus the **single**-token, **multi**-token, and **scanner**
186
+ sub-libraries).
187
+
188
+ | Path | Role |
189
+ | --- | --- |
190
+ | `src/tokens/MultiBOLT.ts` | `SimpleMultiBOLT` — the fungible token class (mint/transfer/split/merge/melt). |
191
+ | `src/tokens/GenesisMultiBOLT.ts` | `FixedBOLT` (one genesis per asset) and `OpenBOLT` (many mints, re-rooted merges): the fungible genesis family, every `SimpleMultiBOLT` operation plus `mintData` and the merge rules. |
192
+ | `src/tokens/BOLT.ts` | `BOLT` — the abstract token base class. |
193
+ | `src/tokens/templates/SimpleMulti.sx.template.ts` | Runtime lock/unlock/melt assembler for the fungible contract (compiled ASM suffix embedded). |
194
+ | `src/tokens/templates/MinSimple.sx.template.ts` | Single-token (NFT) lock / unlock / melt template: `MinSimpleBOLT` (identity; a commit or settle may carry no funding input and change is optional, so p2p / SPV hops never need to be mined). |
195
+ | `src/tokens/templates/AuthBolt.sx.template.ts` | `AuthBOLT`: carries an arbitrary data field `authOrMiscData` (<= 75 B, a direct push) created in a commit and authenticated by the next settle. Same lock layout as `MinSimpleBOLT`; told apart by its suffix fingerprint. Lock / unlock / melt. |
196
+ | `src/tokens/templates/FixedMulti.sx.template.ts`, `OpenMulti.sx.template.ts` | The genesis-family fungible templates: SimpleMulti's layout behind two leading pushes (the asset outpoint, `mintData`). |
197
+ | `src/tokens/templates/SerialBolt.sx.template.ts` | `SerialBOLT`: the NFT carrying its own mint outpoint and `mintData`; zero-funding. Lock / unlock / melt. |
198
+ | `src/lib/genesis.ts` | The two leading pushes of the genesis family (`genesisFieldFor`, `mintDataFor`). |
199
+ | `src/tokens/templates/pay2Proof.ts` | The `pay2Proof` UTXO template (the b017 marker proof output). |
200
+ | `src/lib/boltLib.ts` | Layout-agnostic primitives (`verifyTx`, `buildOutpoint`, `splitCtx`, …) shared by both streams. |
201
+ | `src/lib/single/` | Single-token (NFT) engine: `singleSpend` (unlock assembler) + `singleAncestor` (back-reach reconstruction). |
202
+ | `src/lib/multi/multiBoltLib.ts` | Fungible-token engine: ancestor reconstruction per `MultiLayout` (`SimpleMultiBOLT`, `FixedBOLT`, `OpenBOLT`). |
203
+ | `src/lib/scanner/fingerprints.ts` | Per-type recognition (`recognizeType`, `recognizeToken` with the genesis-family phase, golden `recognizeP2P`) + the type `REGISTRY`. |
204
+ | `src/lib/scanner/verifyEvents.ts` | Off-chain event validator: batch verifier, per-event checker, and the anchor broadcast wrapper (`verifyEvents`, `verifyEvent`, `verifyAndBroadcast`). |
205
+ | `src/lib/scanner/beef.ts` | The off-chain data package: Atomic BEEF over BEEF V2 (`toAtomicBeef`, `fromBeef`, `isBeef`). |
206
+
207
+ > Naming note: the `SimpleMultiBOLT` **class** currently lives in `tokens/MultiBOLT.ts`.
208
+ > Resolving that file/class name mismatch is tracked in the ROADMAP.
209
+
210
+ The full public API is the named exports of [`src/index.ts`](src/index.ts).
211
+
212
+ ## Testing & coverage
213
+
214
+ The whole codebase is unit-tested with [Vitest](https://vitest.dev). The `test/` tree mirrors `src/`
215
+ by concern (`test/tokens`, `test/templates`, `test/lib`, `test/scanner`), with shared
216
+ fixtures in `test/fixtures` and helpers in `test/helpers`.
217
+
218
+ ```
219
+ npm test # 795 tests across 43 files
220
+ npm run test:coverage # the same suite + a v8 coverage report (text to stdout, HTML in coverage/)
221
+ ```
222
+
223
+ Latest run — **every source module is fully covered**: 100% on every metric, enforced by the coverage thresholds. The
224
+ 21 `v8 ignore` markers sit only on defensive TypeScript guards, each stating why it cannot fire:
225
+
226
+ | Metric | Coverage |
227
+ | --- | --- |
228
+ | Statements | **100.0%** (2305/2305) |
229
+ | Functions | **100.0%** (168/168) |
230
+ | Lines | **100.0%** |
231
+ | Branches | **100.0%** (1153/1153) |
232
+
233
+ Fail-safe guards that cannot fire (e.g. a `0xff` >4 GB script-length prefix, or a type/issuer check an
234
+ upstream fingerprint already guarantees) are annotated `v8 ignore` with the reason inline; so are the checks
235
+ behind `@bsv/sdk`'s `Spend.validate()` (it throws rather than returning `false`) and the guards a missing
236
+ unlocking script can never reach (`tx.id()` fails first). Every other branch has a test.
237
+
238
+ What the suite verifies: each contract template is byte-faithful to its sx-compiled artifact and
239
+ spends under the `@bsv/sdk` Spend engine; the scanner's accept/reject decisions match the on-chain
240
+ contract over genuine lineages and every counterfeit class (including **strict golden p2Proof
241
+ fingerprinting** on commit proof outputs and settle proof inputs); and the library **fails closed**
242
+ on malformed input (bad hex, non-arrays, tampered markers) rather than throwing.
243
+
244
+ ## Why Teranode + BOLT + Emergent Automation is the killer stablecoin platform
245
+
246
+ A stablecoin is only as good as the three layers underneath it: where it **settles**, how its
247
+ **integrity** is proven, and who can **operate** it. Most platforms nail one and compromise the other
248
+ two. This stack is the first to get all three right at once — because each layer removes the exact
249
+ bottleneck the next one needs gone.
250
+
251
+ **1. Teranode — unbounded settlement, fixed micro-fees.** Teranode is BSV's horizontally-scaling
252
+ node: throughput grows with hardware instead of hitting a protocol ceiling, so the base layer
253
+ absorbs millions of transactions per second at sub-cent, *non-auctioned* fees. A stablecoin meant to
254
+ be spent — not just held — needs settlement that never congests and never surprises you with a gas
255
+ spike. There is no block-space auction to front-run, no L2 to bridge into, no rollup withdrawal
256
+ delay. Final settlement *is* the base layer.
257
+
258
+ **2. BOLT — the asset that proves itself.** A BOLT token is a real Bitcoin UTXO whose entire validity
259
+ (issuer, lineage, owner, balance) is bound into a self-validating Script covenant via a dual
260
+ hash-commitment. Forging one means breaking SHA-256 or ECDSA — not out-voting a validator set or
261
+ finding a contract bug. This is the decisive difference from the two incumbent designs:
262
+
263
+ - **vs. account-based stablecoins (centralised ledgers):** no issuer database to trust, freeze, or
264
+ reconcile. The coin carries its own proof; anyone can verify provenance from the chain.
265
+ - **vs. smart-contract stablecoins (global-state chains):** no shared global contract to congest, no
266
+ re-entrancy/upgrade-key risk, no gas war. Each token validates **independently and in parallel** —
267
+ which is exactly what lets Teranode's parallelism actually scale. Validation is *local and
268
+ SPV-friendly*: this library's off-chain **scanner** (`verifyEvents`) reaches the same accept/reject
269
+ verdict as the on-chain contract, with **strict golden p2Proof fingerprinting** on every commit
270
+ proof output and settle proof input — so a holder verifies a payment with a light client, not a
271
+ full chain replay. The 16-byte balance field carries denominations up to 2× Bitcoin's base limit,
272
+ enough for any fiat unit at any scale.
273
+
274
+ **3. Emergent Automation — an economy that runs itself.** Because a BOLT token is a pure, stateless
275
+ UTXO with deterministic, self-contained validation and a single peer dependency (`@bsv/sdk`), it is
276
+ the ideal instrument for autonomous, machine-to-machine commerce. Software agents can mint, pay,
277
+ split, merge, and **verify** stablecoin value at machine speed with no custodian, no indexer, and no
278
+ human in the loop — every transfer is a self-proving *event* (a commit→settle pair) that another
279
+ agent can validate locally before acting on it. Provenance becomes a function call, not a trust
280
+ relationship.
281
+
282
+ **The combination is the point.** Settlement that never congests (Teranode) + an asset that proves
283
+ its own integrity without a trusted third party or a global-state chain (BOLT) + value that
284
+ autonomous agents can move and verify without intermediaries (Emergent Automation). A stablecoin
285
+ needs cheap unbounded settlement, trustless verifiable integrity, and programmable automation
286
+ *simultaneously* — and this is the only stack where all three reinforce each other instead of
287
+ trading off. That is what makes it not just *a* stablecoin platform, but the killer one.
288
+
289
+ **What is proven vs. assumed.** To be precise about the integrity layer: what the BOLT covenant
290
+ *proves* (see [`docs/formal-proof.md`](docs/formal-proof.md)) is **third-party per-token
291
+ unforgeability** — authenticity, ownership, per-genesis balance conservation, and state-machine
292
+ integrity — plus local, SPV-friendly verification of all of the above. Two things this layer does
293
+ *not* prove, and that a stablecoin still depends on, are **trust assumptions, not theorems**:
294
+ **issuer supply-honesty** (the protocol stops anyone from forging *a* token, but an issuer can
295
+ mint as many genesis tokens as it likes — matching the float to a reserve is an issuer/governance
296
+ matter) and **honest-majority settlement** (final settlement is only as immutable as the chain's
297
+ hash power). The stack is designed so those two assumptions are the *only* ones left standing —
298
+ but they are assumptions, and §1.6 of the proof says exactly where the proven part ends.
299
+
300
+ ## License
301
+
302
+ Open BSV License Version 5 — see [`LICENSE.txt`](LICENSE.txt).
303
+
304
+ <p align="center">
305
+ <picture>
306
+ <source media="(prefers-color-scheme: light)" srcset="docs/assets/bolt-logo-light.png">
307
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/bolt-logo.png">
308
+ <img src="docs/assets/bolt-logo-light.png" alt="Bolt" width="420">
309
+ </picture>
310
+ </p>
package/dist/index.d.ts CHANGED
@@ -1,13 +1,21 @@
1
1
  export { SimpleMultiBOLT } from "./tokens/MultiBOLT.js";
2
2
  export type { VerifierType } from "./tokens/MultiBOLT.js";
3
3
  export { default as SimpleMultiTemplate } from "./tokens/templates/SimpleMulti.sx.template.js";
4
+ export { FixedBOLT, OpenBOLT } from "./tokens/GenesisMultiBOLT.js";
5
+ export { default as FixedMultiTemplate } from "./tokens/templates/FixedMulti.sx.template.js";
6
+ export { default as OpenMultiTemplate } from "./tokens/templates/OpenMulti.sx.template.js";
7
+ export { default as SerialBoltTemplate } from "./tokens/templates/SerialBolt.sx.template.js";
8
+ export { genesisFieldFor, mintDataFor, outpointOf, MINT_DATA_MAX_BYTES } from "./lib/genesis.js";
9
+ export { SIMPLE_MULTI_LAYOUT, FIXED_BOLT_LAYOUT, OPEN_BOLT_LAYOUT } from "./lib/multi/multiBoltLib.js";
10
+ export type { MultiLayout } from "./lib/multi/multiBoltLib.js";
4
11
  export { BOLT } from "./tokens/BOLT.js";
5
- export { verifyTx, buildOutpoint } from "./lib/boltLib.js";
12
+ export { verifyTx, buildOutpoint, p2pkhUnlock, toSigner } from "./lib/boltLib.js";
13
+ export type { Signer, Recipient } from "./lib/boltLib.js";
6
14
  export { default as MinSimpleTemplate } from "./tokens/templates/MinSimple.sx.template.js";
7
- export { default as MinSimpleDiscountTemplate } from "./tokens/templates/MinSimpleDiscount.sx.template.js";
8
- export { default as MinSimpleBalanceTemplate } from "./tokens/templates/MinSimpleBalance.sx.template.js";
15
+ export { default as AuthBoltTemplate, AUTH_DATA_MAX_BYTES } from "./tokens/templates/AuthBolt.sx.template.js";
9
16
  export { default as Pay2ProofTemplate } from "./tokens/templates/pay2Proof.js";
10
- export { REGISTRY, recognizeType, recognizeP2P, issuerPubKeyOf, sha256Hex } from "./lib/scanner/fingerprints.js";
11
- export type { TokenType, TypeSpec } from "./lib/scanner/fingerprints.js";
12
- export { verifyEvents, verifyEvent } from "./lib/scanner/verifyEvents.js";
13
- export type { ScanResult, ScanOpts, EventResult, EventKind } from "./lib/scanner/verifyEvents.js";
17
+ export { REGISTRY, recognizeType, recognizeToken, recognizeP2P, issuerPubKeyOf, sha256Hex } from "./lib/scanner/fingerprints.js";
18
+ export type { TokenType, TypeSpec, TokenPhase } from "./lib/scanner/fingerprints.js";
19
+ export { verifyEvents, verifyEvent, verifyAndBroadcast } from "./lib/scanner/verifyEvents.js";
20
+ export type { ScanResult, ScanOpts, EventResult, EventKind, SourceTx, TxInput, AnchorRef, AnchorStatus, AnchorBroadcastResult, AnchorBroadcaster, HeaderSource, OffChainOnlyTx, } from "./lib/scanner/verifyEvents.js";
21
+ export { toAtomicBeef, fromBeef, isBeef } from "./lib/scanner/beef.js";