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