b017 0.0.0-b
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/LICENSE.txt +56 -0
- package/README.md +206 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +15 -0
- package/dist/lib/boltLib.d.ts +49 -0
- package/dist/lib/boltLib.js +177 -0
- package/dist/lib/multi/multiBoltLib.d.ts +4 -0
- package/dist/lib/multi/multiBoltLib.js +473 -0
- package/dist/lib/scanner/fingerprints.d.ts +25 -0
- package/dist/lib/scanner/fingerprints.js +95 -0
- package/dist/lib/scanner/verifyEvents.d.ts +37 -0
- package/dist/lib/scanner/verifyEvents.js +294 -0
- package/dist/lib/single/singleAncestor.d.ts +8 -0
- package/dist/lib/single/singleAncestor.js +72 -0
- package/dist/lib/single/singleSpend.d.ts +31 -0
- package/dist/lib/single/singleSpend.js +110 -0
- package/dist/tokens/BOLT.d.ts +17 -0
- package/dist/tokens/BOLT.js +9 -0
- package/dist/tokens/MultiBOLT.d.ts +44 -0
- package/dist/tokens/MultiBOLT.js +465 -0
- package/dist/tokens/templates/MinSimple.sx.template.d.ts +23 -0
- package/dist/tokens/templates/MinSimple.sx.template.js +57 -0
- package/dist/tokens/templates/MinSimpleBalance.sx.template.d.ts +24 -0
- package/dist/tokens/templates/MinSimpleBalance.sx.template.js +59 -0
- package/dist/tokens/templates/MinSimpleDiscount.sx.template.d.ts +23 -0
- package/dist/tokens/templates/MinSimpleDiscount.sx.template.js +58 -0
- package/dist/tokens/templates/SimpleMulti.sx.template.d.ts +19 -0
- package/dist/tokens/templates/SimpleMulti.sx.template.js +214 -0
- package/dist/tokens/templates/pay2Proof.d.ts +8 -0
- package/dist/tokens/templates/pay2Proof.js +59 -0
- package/package.json +58 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to **b017** are documented here. The format is based on
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project aims to follow
|
|
5
|
+
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
6
|
+
|
|
7
|
+
## [Unreleased]
|
|
8
|
+
|
|
9
|
+
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for planned work.
|
|
10
|
+
|
|
11
|
+
## [0.0.0-b] — 2026-06-23
|
|
12
|
+
|
|
13
|
+
First public beta. The library is functional and fully tested; the API may still change
|
|
14
|
+
before `0.1.0`.
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- `SimpleMultiBOLT` fungible token class — mint / transfer / split / merge / melt, each
|
|
18
|
+
producing a real, script-valid Bitcoin transaction verified by the `@bsv/sdk` Spend engine.
|
|
19
|
+
- NFT token templates: `MinSimple`, `MinSimpleDiscount`, `MinSimpleBalance`, plus the
|
|
20
|
+
`pay2Proof` UTXO template.
|
|
21
|
+
- Off-chain scanner: `recognizeType` / `REGISTRY` strict fingerprinting, and
|
|
22
|
+
`verifyEvent` / `verifyEvents` for validating BOLT transactional events — one event
|
|
23
|
+
(mint, commit→settle pair, or melt) or a whole batch (issuer-pinned, every commit
|
|
24
|
+
paired with its settle).
|
|
25
|
+
- Pre-compiled `.sx` contracts embedded in the templates — **no sx compiler at runtime**.
|
|
26
|
+
- `@bsv/sdk` as the single peer dependency (no `@elas_co/ts` runtime dependency).
|
|
27
|
+
|
|
28
|
+
### Packaging
|
|
29
|
+
- Build now cleans `dist/` before `tsc` so the published tarball contains no stale artifacts.
|
|
30
|
+
- Added `repository`, `bugs`, `homepage`, and `keywords` metadata.
|
|
31
|
+
|
|
32
|
+
[Unreleased]: https://github.com/BOLT-Association/b017
|
|
33
|
+
[0.0.0-b]: https://github.com/BOLT-Association/b017/releases/tag/v0.0.0-b
|
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
Open BSV License Version 5 – granted by BSV Association, Grafenauweg 6, 6300
|
|
2
|
+
Zug, Switzerland (CHE-427.008.338) ("Licensor"), to you as a user (henceforth
|
|
3
|
+
"You", "User" or "Licensee").
|
|
4
|
+
|
|
5
|
+
For the purposes of this license, the definitions below have the following
|
|
6
|
+
meanings:
|
|
7
|
+
|
|
8
|
+
"Bitcoin Protocol" means the protocol implementation, cryptographic rules,
|
|
9
|
+
network protocols, and consensus mechanisms in the Bitcoin White Paper as
|
|
10
|
+
described here https://protocol.bsvblockchain.org.
|
|
11
|
+
|
|
12
|
+
"Bitcoin White Paper" means the paper entitled 'Bitcoin: A Peer-to-Peer
|
|
13
|
+
Electronic Cash System' published by 'Satoshi Nakamoto' in October 2008.
|
|
14
|
+
|
|
15
|
+
"BSV Blockchains" means:
|
|
16
|
+
(a) the Bitcoin blockchain containing block height #556767 with the hash
|
|
17
|
+
"000000000000000001d956714215d96ffc00e0afda4cd0a96c96f8d802b1662b" and
|
|
18
|
+
that contains the longest honest persistent chain of blocks which has been
|
|
19
|
+
produced in a manner which is consistent with the rules set forth in the
|
|
20
|
+
Network Access Rules; and
|
|
21
|
+
(b) the test blockchains that contain the longest honest persistent chains of
|
|
22
|
+
blocks which has been produced in a manner which is consistent with the
|
|
23
|
+
rules set forth in the Network Access Rules.
|
|
24
|
+
|
|
25
|
+
"Network Access Rules" or "Rules" means the set of rules regulating the
|
|
26
|
+
relationship between BSV Association and the nodes on BSV based on the Bitcoin
|
|
27
|
+
Protocol rules and those set out in the Bitcoin White Paper, and available here
|
|
28
|
+
https://bsvblockchain.org/network-access-rules.
|
|
29
|
+
|
|
30
|
+
"Software" means the software the subject of this licence, including any/all
|
|
31
|
+
intellectual property rights therein and associated documentation files.
|
|
32
|
+
|
|
33
|
+
BSV Association grants permission, free of charge and on a non-exclusive and
|
|
34
|
+
revocable basis, to any person obtaining a copy of the Software to deal in the
|
|
35
|
+
Software without restriction, including without limitation the rights to use,
|
|
36
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
|
37
|
+
Software, and to permit persons to whom the Software is furnished to do so,
|
|
38
|
+
subject to and conditioned upon the following conditions:
|
|
39
|
+
|
|
40
|
+
1 - The text "© BSV Association," and this license shall be included in all
|
|
41
|
+
copies or substantial portions of the Software.
|
|
42
|
+
2 - The Software, and any software that is derived from the Software or parts
|
|
43
|
+
thereof, must only be used on the BSV Blockchains.
|
|
44
|
+
|
|
45
|
+
For the avoidance of doubt, this license is granted subject to and conditioned
|
|
46
|
+
upon your compliance with these terms only. In the event of non-compliance, the
|
|
47
|
+
license shall extinguish and you can be enjoined from violating BSV's
|
|
48
|
+
intellectual property rights (incl. damages and similar related claims).
|
|
49
|
+
|
|
50
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
51
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES REGARDING ENTITLEMENT,
|
|
52
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
|
|
53
|
+
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS THEREOF BE LIABLE FOR ANY CLAIM,
|
|
54
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
55
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
56
|
+
DEALINGS IN THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# b017; Bicoin Original Layer-1 Token Protocol
|
|
2
|
+
|
|
3
|
+
[](https://github.com/BOLT-Association/b017/actions/workflows/ci.yml)
|
|
4
|
+
[](https://codecov.io/gh/BOLT-Association/b017)
|
|
5
|
+
[](https://www.npmjs.com/package/b017)
|
|
6
|
+
[](https://www.typescriptlang.org/)
|
|
7
|
+
|
|
8
|
+
> **Status: `0.0.0-b` (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 **Bicoin 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>
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { SimpleMultiBOLT } from "./tokens/MultiBOLT.js";
|
|
2
|
+
export type { VerifierType } from "./tokens/MultiBOLT.js";
|
|
3
|
+
export { default as SimpleMultiTemplate } from "./tokens/templates/SimpleMulti.sx.template.js";
|
|
4
|
+
export { BOLT } from "./tokens/BOLT.js";
|
|
5
|
+
export { verifyTx, buildOutpoint } from "./lib/boltLib.js";
|
|
6
|
+
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";
|
|
9
|
+
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";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// b017 — optimised BOLT layer-1 token templates + off-chain scanner.
|
|
2
|
+
// Pre-compiled contract (no sx compiler at runtime); only @bsv/sdk.
|
|
3
|
+
export { SimpleMultiBOLT } from "./tokens/MultiBOLT.js";
|
|
4
|
+
export { default as SimpleMultiTemplate } from "./tokens/templates/SimpleMulti.sx.template.js";
|
|
5
|
+
export { BOLT } from "./tokens/BOLT.js";
|
|
6
|
+
export { verifyTx, buildOutpoint } from "./lib/boltLib.js";
|
|
7
|
+
// Token LOCK templates (mint/build the contract output for each type).
|
|
8
|
+
export { default as MinSimpleTemplate } from "./tokens/templates/MinSimple.sx.template.js";
|
|
9
|
+
export { default as MinSimpleDiscountTemplate } from "./tokens/templates/MinSimpleDiscount.sx.template.js";
|
|
10
|
+
export { default as MinSimpleBalanceTemplate } from "./tokens/templates/MinSimpleBalance.sx.template.js";
|
|
11
|
+
export { default as Pay2ProofTemplate } from "./tokens/templates/pay2Proof.js";
|
|
12
|
+
// Token recognition — the scanner's fingerprint primitive.
|
|
13
|
+
export { REGISTRY, recognizeType, recognizeP2P, issuerPubKeyOf, sha256Hex } from "./lib/scanner/fingerprints.js";
|
|
14
|
+
// The shared off-chain BOLT event validator (the scanner): a batch verifier + the per-event checker.
|
|
15
|
+
export { verifyEvents, verifyEvent } from "./lib/scanner/verifyEvents.js";
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Script, Spend, Transaction, PrivateKey } from "@bsv/sdk";
|
|
2
|
+
export declare const verifyTx: (tx: Transaction, skipOutputCheck?: boolean) => {
|
|
3
|
+
valid: boolean;
|
|
4
|
+
scriptExecutions: {
|
|
5
|
+
spend: Spend;
|
|
6
|
+
valid: boolean;
|
|
7
|
+
}[];
|
|
8
|
+
};
|
|
9
|
+
export declare const buildOutpoint: (tx: Transaction, outputIndex: number) => number[];
|
|
10
|
+
export declare const buildChangeOutput: (tx: Transaction, outputIndex: number) => number[];
|
|
11
|
+
export declare const createSignature: (privateKey: PrivateKey, preimage: number[], signatureScope: number) => {
|
|
12
|
+
sigForScript: number[];
|
|
13
|
+
pubkeyForScript: number[];
|
|
14
|
+
};
|
|
15
|
+
export declare const splitCtx: (ctx: number[], unlockBytesLen?: number) => {
|
|
16
|
+
ctxHeader: number[];
|
|
17
|
+
ctxCodeUnlockScriptCode: number[];
|
|
18
|
+
ctxCodeLen: number[];
|
|
19
|
+
ctxFooter: number[];
|
|
20
|
+
ctxCodeLockScriptCode: number[];
|
|
21
|
+
ctxCodeLockLen: number[];
|
|
22
|
+
};
|
|
23
|
+
/** 4-byte little-endian. */
|
|
24
|
+
export declare const le32: (n: number) => number[];
|
|
25
|
+
/** 8-byte little-endian. */
|
|
26
|
+
export declare const le64: (n: number) => number[];
|
|
27
|
+
/** bin -> Script chunks (one pushdata; OP_0 for empty). */
|
|
28
|
+
export declare const scriptChunksFromBin: (data: number[]) => any[];
|
|
29
|
+
/** Data of a script's chunk `i` (or []). */
|
|
30
|
+
export declare const scriptChunk: (s: Script, i: number) => number[];
|
|
31
|
+
/** tx version as 4-byte LE. */
|
|
32
|
+
export declare const txVersion: (tx: Transaction) => number[];
|
|
33
|
+
/** tx lockTime as 4-byte LE. */
|
|
34
|
+
export declare const txLockTime: (tx: Transaction) => number[];
|
|
35
|
+
/** The 36-byte outpoint input `vin` spends — from the attached source tx, else the sourceTXID
|
|
36
|
+
* (reversed) fallback; [] if neither is available. */
|
|
37
|
+
export declare const spentOutpoint: (tx: Transaction, vin: number) => number[];
|
|
38
|
+
/** Data of input `vin`'s unlocking-script chunk `chunkIdx` (or []). */
|
|
39
|
+
export declare const vinChunk: (tx: Transaction, vin: number, chunkIdx: number) => number[];
|
|
40
|
+
/** Input `vin`'s 4-byte LE nSequence (or []). */
|
|
41
|
+
export declare const vinSequence: (tx: Transaction, vin: number) => number[];
|
|
42
|
+
/** Input `vin`'s full unlocking-script bytes (or []). */
|
|
43
|
+
export declare const vinScript: (tx: Transaction, vin: number) => number[];
|
|
44
|
+
/** Data of output `vout`'s locking-script chunk `chunkIdx` (or []). */
|
|
45
|
+
export declare const voutChunk: (tx: Transaction, vout: number, chunkIdx: number) => number[];
|
|
46
|
+
/** Output `idx`'s 8-byte LE value (or []). */
|
|
47
|
+
export declare const outputValue: (tx: Transaction, idx: number) => number[];
|
|
48
|
+
/** Output `idx`'s locking-script bytes (or []). */
|
|
49
|
+
export declare const outputScript: (tx: Transaction, idx: number) => number[];
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
// boltLib.ts — layout-agnostic helpers shared by both token streams:
|
|
2
|
+
// verifyTx (bsv Spend), buildOutpoint, buildChangeOutput, createSignature, splitCtx,
|
|
3
|
+
// and the tx-field primitives (le32/le64, spentOutpoint, vin*/vout*, …).
|
|
4
|
+
import { Script, Spend, Utils, TransactionSignature, Hash } from "@bsv/sdk";
|
|
5
|
+
const { Reader, Writer } = Utils;
|
|
6
|
+
// Verify every input of a tx with the @bsv/sdk Spend engine.
|
|
7
|
+
export const verifyTx = (tx, skipOutputCheck = false) => {
|
|
8
|
+
let inputTotal = 0;
|
|
9
|
+
const txid = tx.id("hex");
|
|
10
|
+
const scriptExecutions = [];
|
|
11
|
+
for (let i = 0; i < tx.inputs.length; i++) {
|
|
12
|
+
const input = tx.inputs[i];
|
|
13
|
+
if (typeof input.sourceTransaction !== "object") {
|
|
14
|
+
throw new Error(`Verification failed: input ${i} of ${txid} is missing its source transaction.`);
|
|
15
|
+
}
|
|
16
|
+
if (typeof input.unlockingScript !== "object") {
|
|
17
|
+
throw new Error(`Verification failed: input ${i} of ${txid} is missing its unlocking script.`);
|
|
18
|
+
}
|
|
19
|
+
const sourceOutput = input.sourceTransaction.outputs[input.sourceOutputIndex];
|
|
20
|
+
inputTotal += sourceOutput.satoshis || 0;
|
|
21
|
+
const sourceTxid = input.sourceTransaction.id("hex");
|
|
22
|
+
const otherInputs = tx.inputs.filter((_, idx) => idx !== i);
|
|
23
|
+
if (typeof input.sourceTXID === "undefined")
|
|
24
|
+
input.sourceTXID = sourceTxid;
|
|
25
|
+
const spend = new Spend({
|
|
26
|
+
sourceTXID: input.sourceTXID,
|
|
27
|
+
sourceOutputIndex: input.sourceOutputIndex,
|
|
28
|
+
lockingScript: sourceOutput.lockingScript,
|
|
29
|
+
sourceSatoshis: sourceOutput.satoshis || 0,
|
|
30
|
+
transactionVersion: tx.version,
|
|
31
|
+
otherInputs,
|
|
32
|
+
unlockingScript: input.unlockingScript,
|
|
33
|
+
inputSequence: input.sequence || 0xffffffff,
|
|
34
|
+
inputIndex: i,
|
|
35
|
+
outputs: tx.outputs,
|
|
36
|
+
lockTime: tx.lockTime,
|
|
37
|
+
});
|
|
38
|
+
const valid = spend.validate();
|
|
39
|
+
scriptExecutions.push({ spend, valid });
|
|
40
|
+
if (!valid)
|
|
41
|
+
return { valid: false, scriptExecutions };
|
|
42
|
+
}
|
|
43
|
+
let outputTotal = 0;
|
|
44
|
+
for (const out of tx.outputs) {
|
|
45
|
+
if (typeof out.satoshis !== "number")
|
|
46
|
+
throw new Error("Every output must have a defined amount during verification.");
|
|
47
|
+
outputTotal += out.satoshis;
|
|
48
|
+
}
|
|
49
|
+
if (!skipOutputCheck && outputTotal > inputTotal)
|
|
50
|
+
throw new Error("Output total greater than input total");
|
|
51
|
+
return { valid: true, scriptExecutions };
|
|
52
|
+
};
|
|
53
|
+
// 36-byte outpoint (txid LE + 4-byte vout).
|
|
54
|
+
export const buildOutpoint = (tx, outputIndex) => {
|
|
55
|
+
const writer = new Utils.Writer();
|
|
56
|
+
writer.write(tx.hash());
|
|
57
|
+
writer.writeUInt32LE(outputIndex);
|
|
58
|
+
return writer.toArray();
|
|
59
|
+
};
|
|
60
|
+
// Serialised change output: 8-byte value + varint scriptLen + script.
|
|
61
|
+
export const buildChangeOutput = (tx, outputIndex) => {
|
|
62
|
+
const writer = new Utils.Writer();
|
|
63
|
+
const output = tx.outputs[outputIndex];
|
|
64
|
+
if (!output)
|
|
65
|
+
return [];
|
|
66
|
+
writer.writeUInt64LE(output.satoshis);
|
|
67
|
+
const scriptBin = output.lockingScript.toBinary();
|
|
68
|
+
writer.writeVarIntNum(scriptBin.length);
|
|
69
|
+
writer.write(scriptBin);
|
|
70
|
+
return writer.toArray();
|
|
71
|
+
};
|
|
72
|
+
// Sign a preimage (signs sha256(preimage); the engine double-hashes) -> checksig-format sig + pubkey.
|
|
73
|
+
export const createSignature = (privateKey, preimage, signatureScope) => {
|
|
74
|
+
const rawSignature = privateKey.sign(Hash.sha256(preimage));
|
|
75
|
+
const sig = new TransactionSignature(rawSignature.r, rawSignature.s, signatureScope);
|
|
76
|
+
const sigForScript = sig.toChecksigFormat();
|
|
77
|
+
const pubkeyForScript = privateKey.toPublicKey().encode(true);
|
|
78
|
+
return { sigForScript, pubkeyForScript };
|
|
79
|
+
};
|
|
80
|
+
// Split a BIP143 preimage into header(104) + scriptCodeLen + unlockScriptCode + lockScriptCode +
|
|
81
|
+
// footer(52) + lockLen. unlockBytesLen = bytes of unlock-script-code prefix (2 for SimpleMultiBolt).
|
|
82
|
+
export const splitCtx = (ctx, unlockBytesLen = 0) => {
|
|
83
|
+
const ctxHeader = ctx.slice(0, 104);
|
|
84
|
+
let offset = 104;
|
|
85
|
+
let reader = new Reader(ctx, offset);
|
|
86
|
+
const firstByte = reader.readUInt8();
|
|
87
|
+
let scriptLenSize = 1;
|
|
88
|
+
if (firstByte === 0xfd)
|
|
89
|
+
scriptLenSize = 3;
|
|
90
|
+
else if (firstByte === 0xfe)
|
|
91
|
+
scriptLenSize = 5;
|
|
92
|
+
/* v8 ignore next -- 0xff (>4GB scriptCode) is unreachable for any real BIP143 preimage */
|
|
93
|
+
else if (firstByte === 0xff)
|
|
94
|
+
scriptLenSize = 9;
|
|
95
|
+
const ctxCodeLen = ctx.slice(offset, offset + scriptLenSize);
|
|
96
|
+
offset += scriptLenSize;
|
|
97
|
+
let actualScriptLen = firstByte;
|
|
98
|
+
reader = new Reader(ctx, 104 + 1);
|
|
99
|
+
if (firstByte === 0xfd)
|
|
100
|
+
actualScriptLen = reader.readUInt16LE();
|
|
101
|
+
else if (firstByte === 0xfe)
|
|
102
|
+
actualScriptLen = reader.readUInt32LE();
|
|
103
|
+
/* v8 ignore next -- 0xff (>4GB scriptCode) is unreachable for any real BIP143 preimage */
|
|
104
|
+
else if (firstByte === 0xff)
|
|
105
|
+
actualScriptLen = Number(reader.readUInt64LEBn());
|
|
106
|
+
const ctxCode = ctx.slice(offset, offset + actualScriptLen);
|
|
107
|
+
offset += actualScriptLen;
|
|
108
|
+
const ctxCodeUnlockScriptCode = ctxCode.slice(0, unlockBytesLen);
|
|
109
|
+
const ctxCodeLockScriptCode = ctxCode.slice(unlockBytesLen);
|
|
110
|
+
const ctxFooter = ctx.slice(offset, offset + 52);
|
|
111
|
+
const writer = new Writer();
|
|
112
|
+
const ctxCodeLockLen = writer.writeVarIntNum(ctxCodeLockScriptCode.length).toArray();
|
|
113
|
+
return { ctxHeader, ctxCodeUnlockScriptCode, ctxCodeLen, ctxFooter, ctxCodeLockScriptCode, ctxCodeLockLen };
|
|
114
|
+
};
|
|
115
|
+
// ---- layout-agnostic tx-field primitives (one vocabulary, shared by both token streams) ----
|
|
116
|
+
// These replace the duplicated "mirrors" block in multiBoltLib + the inline le32/le64/chunkData/
|
|
117
|
+
// outpointOfInput in the nft helpers. Byte-faithful to those originals.
|
|
118
|
+
/** 4-byte little-endian. */
|
|
119
|
+
export const le32 = (n) => { const w = new Writer(); w.writeUInt32LE(n); return w.toArray(); };
|
|
120
|
+
/** 8-byte little-endian. */
|
|
121
|
+
export const le64 = (n) => { const w = new Writer(); w.writeUInt64LE(n); return w.toArray(); };
|
|
122
|
+
/** bin -> Script chunks (one pushdata; OP_0 for empty). */
|
|
123
|
+
export const scriptChunksFromBin = (data) => new Script().writeBin(data).chunks;
|
|
124
|
+
/** Data of a script's chunk `i` (or []). */
|
|
125
|
+
export const scriptChunk = (s, i) => s.chunks[i]?.data ?? [];
|
|
126
|
+
/** tx version as 4-byte LE. */
|
|
127
|
+
export const txVersion = (tx) => le32(tx.version);
|
|
128
|
+
/** tx lockTime as 4-byte LE. */
|
|
129
|
+
export const txLockTime = (tx) => le32(tx.lockTime);
|
|
130
|
+
/** The 36-byte outpoint input `vin` spends — from the attached source tx, else the sourceTXID
|
|
131
|
+
* (reversed) fallback; [] if neither is available. */
|
|
132
|
+
export const spentOutpoint = (tx, vin) => {
|
|
133
|
+
const input = tx.inputs[vin];
|
|
134
|
+
if (!input)
|
|
135
|
+
return [];
|
|
136
|
+
const txid = input.sourceTransaction?.hash() ||
|
|
137
|
+
Utils.toArray(input.sourceTXID || "", "hex").reverse();
|
|
138
|
+
if (!txid || txid.length === 0)
|
|
139
|
+
return [];
|
|
140
|
+
const w = new Writer();
|
|
141
|
+
w.write(txid);
|
|
142
|
+
w.writeUInt32LE(input.sourceOutputIndex);
|
|
143
|
+
return w.toArray();
|
|
144
|
+
};
|
|
145
|
+
/** Data of input `vin`'s unlocking-script chunk `chunkIdx` (or []). */
|
|
146
|
+
export const vinChunk = (tx, vin, chunkIdx) => {
|
|
147
|
+
const w = new Writer();
|
|
148
|
+
w.write(tx.inputs[vin]?.unlockingScript?.chunks?.[chunkIdx]?.data || []);
|
|
149
|
+
return w.toArray();
|
|
150
|
+
};
|
|
151
|
+
/** Input `vin`'s 4-byte LE nSequence (or []). */
|
|
152
|
+
export const vinSequence = (tx, vin) => {
|
|
153
|
+
const input = tx.inputs[vin];
|
|
154
|
+
if (!input)
|
|
155
|
+
return [];
|
|
156
|
+
return le32((input.sequence ?? 0xffffffff));
|
|
157
|
+
};
|
|
158
|
+
/** Input `vin`'s full unlocking-script bytes (or []). */
|
|
159
|
+
export const vinScript = (tx, vin) => tx.inputs[vin]?.unlockingScript?.toBinary() || [];
|
|
160
|
+
/** Data of output `vout`'s locking-script chunk `chunkIdx` (or []). */
|
|
161
|
+
export const voutChunk = (tx, vout, chunkIdx) => scriptChunk(tx.outputs[vout].lockingScript, chunkIdx);
|
|
162
|
+
/** Output `idx`'s 8-byte LE value (or []). */
|
|
163
|
+
export const outputValue = (tx, idx) => {
|
|
164
|
+
const output = tx.outputs[idx];
|
|
165
|
+
if (!output)
|
|
166
|
+
return [];
|
|
167
|
+
return le64(output.satoshis || 0);
|
|
168
|
+
};
|
|
169
|
+
/** Output `idx`'s locking-script bytes (or []). */
|
|
170
|
+
export const outputScript = (tx, idx) => {
|
|
171
|
+
const output = tx.outputs[idx];
|
|
172
|
+
if (!output)
|
|
173
|
+
return [];
|
|
174
|
+
const w = new Writer();
|
|
175
|
+
w.write(output.lockingScript.toBinary());
|
|
176
|
+
return w.toArray();
|
|
177
|
+
};
|