@bsv/create-dpp-app 0.0.0-stage → 0.1.0-beta.1
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/LICENSE +203 -0
- package/README.md +73 -2
- package/dist/index.js +97 -0
- package/package.json +53 -4
- package/template/Dockerfile +35 -0
- package/template/README.md +134 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +53 -0
- package/template/_github/workflows/ci.yml +23 -0
- package/template/_gitignore +8 -0
- package/template/_prettierrc +6 -0
- package/template/apps/api/API.md +49 -0
- package/template/apps/api/package.json +34 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/claims.ts +85 -0
- package/template/apps/api/src/cli.ts +42 -0
- package/template/apps/api/src/config.ts +66 -0
- package/template/apps/api/src/custody.ts +186 -0
- package/template/apps/api/src/dev-index.ts +71 -0
- package/template/apps/api/src/env.ts +14 -0
- package/template/apps/api/src/identifiers.ts +57 -0
- package/template/apps/api/src/index-client.ts +136 -0
- package/template/apps/api/src/main.ts +50 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +121 -0
- package/template/apps/api/src/profiles.ts +100 -0
- package/template/apps/api/src/reader.ts +96 -0
- package/template/apps/api/src/server.ts +420 -0
- package/template/apps/api/src/store.ts +249 -0
- package/template/apps/api/src/wallet.ts +346 -0
- package/template/apps/api/src/worker.ts +106 -0
- package/template/apps/api/src/writer.ts +351 -0
- package/template/apps/api/test/config.test.ts +15 -0
- package/template/apps/api/test/external-index.test.ts +31 -0
- package/template/apps/api/test/lifecycle.test.ts +136 -0
- package/template/apps/api/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +9 -0
- package/template/apps/web/components.json +21 -0
- package/template/apps/web/index.html +12 -0
- package/template/apps/web/package.json +33 -0
- package/template/apps/web/src/app.tsx +51 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- package/template/apps/web/src/components/layout.tsx +118 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +48 -0
- package/template/apps/web/src/components/reading.tsx +157 -0
- package/template/apps/web/src/components/ui/alert.tsx +65 -0
- package/template/apps/web/src/components/ui/badge.tsx +47 -0
- package/template/apps/web/src/components/ui/button.tsx +63 -0
- package/template/apps/web/src/components/ui/card.tsx +91 -0
- package/template/apps/web/src/components/ui/dialog.tsx +156 -0
- package/template/apps/web/src/components/ui/input.tsx +20 -0
- package/template/apps/web/src/components/ui/label.tsx +21 -0
- package/template/apps/web/src/components/ui/select.tsx +189 -0
- package/template/apps/web/src/components/ui/separator.tsx +25 -0
- package/template/apps/web/src/components/ui/table.tsx +115 -0
- package/template/apps/web/src/components/ui/tabs.tsx +90 -0
- package/template/apps/web/src/components/ui/textarea.tsx +17 -0
- package/template/apps/web/src/index.css +81 -0
- package/template/apps/web/src/lib/api.ts +286 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- package/template/apps/web/src/lib/format.ts +64 -0
- package/template/apps/web/src/lib/session.tsx +92 -0
- package/template/apps/web/src/lib/use-load.ts +46 -0
- package/template/apps/web/src/main.tsx +18 -0
- package/template/apps/web/src/pages/accept.tsx +108 -0
- package/template/apps/web/src/pages/brand.tsx +94 -0
- package/template/apps/web/src/pages/brands.tsx +104 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +114 -0
- package/template/apps/web/src/pages/operations.tsx +150 -0
- package/template/apps/web/src/pages/passport.tsx +568 -0
- package/template/apps/web/src/pages/public-passport.tsx +24 -0
- package/template/apps/web/src/pages/sign-in.tsx +93 -0
- package/template/apps/web/src/pages/verify.tsx +30 -0
- package/template/apps/web/src/pages/wallet.tsx +141 -0
- package/template/apps/web/tsconfig.json +29 -0
- package/template/apps/web/vite.config.ts +15 -0
- package/template/deploy/compose.yml +26 -0
- package/template/package.json +42 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
// The application's records and its journal. The journal is the single
|
|
2
|
+
// source of truth for every write: each state is recorded before it is acted
|
|
3
|
+
// on, with the index's answer, the network's answer and the proof, so a retry
|
|
4
|
+
// continues an operation instead of building a second transaction. The
|
|
5
|
+
// worker loop reads the same records to find what is still owed.
|
|
6
|
+
//
|
|
7
|
+
// Two implementations: MongoDB for a running platform, memory for tests.
|
|
8
|
+
import type { Collection, Db } from 'mongodb'
|
|
9
|
+
import type { ManagedAcceptanceRecord, SignedLifecycleClaim } from '@bsv/dpp-protocol'
|
|
10
|
+
|
|
11
|
+
export type IndexAnswer = 'pending' | 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable' | 'not-asked'
|
|
12
|
+
export type NetworkAnswer = 'pending' | 'accepted' | 'refused' | 'unanswered' | 'not-sent' | 'dry-run'
|
|
13
|
+
|
|
14
|
+
export interface StateEntry {
|
|
15
|
+
op: 'ISSUE' | 'UPDATE' | 'TRANSFER' | 'RETIRE'
|
|
16
|
+
txid: string
|
|
17
|
+
outputIndex: number
|
|
18
|
+
/** The transaction as hex, and the BEEF the index and a reader take, base64. */
|
|
19
|
+
rawTx: string
|
|
20
|
+
beef: string
|
|
21
|
+
timestamp: string
|
|
22
|
+
actor: string
|
|
23
|
+
controllerKey: string
|
|
24
|
+
payloadPublic: string
|
|
25
|
+
/** The owner tier the state commits to: only the hash goes on chain; the ciphertext lives here, nowhere else. */
|
|
26
|
+
ownerTier?: { hash: string; ciphertext: string }
|
|
27
|
+
index: IndexAnswer
|
|
28
|
+
refusal?: string
|
|
29
|
+
network: NetworkAnswer
|
|
30
|
+
proof?: { merklePath: string; blockHeight: number }
|
|
31
|
+
proofPushed?: boolean
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface PassportRecord {
|
|
35
|
+
passportId: string
|
|
36
|
+
brandId: string
|
|
37
|
+
profile: string
|
|
38
|
+
createdAt: string
|
|
39
|
+
status: 'active' | 'retired'
|
|
40
|
+
/** Who controls the passport now: the party name the platform derives the controller key for. */
|
|
41
|
+
holder: { party: string; controllerKey: string }
|
|
42
|
+
states: StateEntry[]
|
|
43
|
+
/** Every acceptance record the platform signed for this passport, kept for its life: a reader needs it to check a transfer. */
|
|
44
|
+
acceptanceRecords: ManagedAcceptanceRecord[]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface OfferRecord {
|
|
48
|
+
requestId: string
|
|
49
|
+
passportId: string
|
|
50
|
+
brandId: string
|
|
51
|
+
mechanism: 'claim-code' | 'named-recipient'
|
|
52
|
+
/** SHA-256 of the claim code, hex; the code itself is shown once and never stored. */
|
|
53
|
+
claimCodeHash?: string
|
|
54
|
+
recipientIdentityKey?: string
|
|
55
|
+
terms: Record<string, unknown>
|
|
56
|
+
termsDigest: string
|
|
57
|
+
holderIdentityKey: string
|
|
58
|
+
expectedPredecessor: { txid: string; outputIndex: number }
|
|
59
|
+
createdAt: string
|
|
60
|
+
expiresAt: string
|
|
61
|
+
status: 'open' | 'accepted' | 'transferred' | 'declined' | 'withdrawn' | 'expired'
|
|
62
|
+
record?: ManagedAcceptanceRecord
|
|
63
|
+
transferTxid?: string
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ClaimRecord {
|
|
67
|
+
id: string
|
|
68
|
+
passportId: string
|
|
69
|
+
issuer: string
|
|
70
|
+
issuedBy: string
|
|
71
|
+
claim: SignedLifecycleClaim
|
|
72
|
+
registry?: { url: string; status: number; accepted: boolean; attestationId?: string; detail?: string }
|
|
73
|
+
createdAt: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface BrandRecord {
|
|
77
|
+
id: string
|
|
78
|
+
name: string
|
|
79
|
+
identityKey: string
|
|
80
|
+
did: string
|
|
81
|
+
createdAt: string
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface SpendRecord {
|
|
85
|
+
txid: string
|
|
86
|
+
satoshis: number
|
|
87
|
+
at: string
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export interface Store {
|
|
91
|
+
getPassport(passportId: string): Promise<PassportRecord | undefined>
|
|
92
|
+
listPassports(filter?: { brandId?: string }): Promise<PassportRecord[]>
|
|
93
|
+
savePassport(record: PassportRecord): Promise<void>
|
|
94
|
+
/** Only for a passport whose genesis was never written: a journal with states is never deleted. */
|
|
95
|
+
deletePassport(passportId: string): Promise<void>
|
|
96
|
+
getOffer(requestId: string): Promise<OfferRecord | undefined>
|
|
97
|
+
listOffers(filter?: { passportId?: string; brandId?: string; status?: OfferRecord['status'] }): Promise<OfferRecord[]>
|
|
98
|
+
saveOffer(record: OfferRecord): Promise<void>
|
|
99
|
+
listClaims(filter?: { passportId?: string }): Promise<ClaimRecord[]>
|
|
100
|
+
saveClaim(record: ClaimRecord): Promise<void>
|
|
101
|
+
getBrand(id: string): Promise<BrandRecord | undefined>
|
|
102
|
+
listBrands(ids?: string[]): Promise<BrandRecord[]>
|
|
103
|
+
saveBrand(record: BrandRecord): Promise<void>
|
|
104
|
+
recordSpend(spend: SpendRecord): Promise<void>
|
|
105
|
+
spentSince(at: string): Promise<number>
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T
|
|
109
|
+
|
|
110
|
+
export class MemoryStore implements Store {
|
|
111
|
+
private passports = new Map<string, PassportRecord>()
|
|
112
|
+
private offers = new Map<string, OfferRecord>()
|
|
113
|
+
private claims = new Map<string, ClaimRecord>()
|
|
114
|
+
private brands = new Map<string, BrandRecord>()
|
|
115
|
+
private spends: SpendRecord[] = []
|
|
116
|
+
|
|
117
|
+
async getPassport(passportId: string) {
|
|
118
|
+
const record = this.passports.get(passportId)
|
|
119
|
+
return record == null ? undefined : clone(record)
|
|
120
|
+
}
|
|
121
|
+
async listPassports(filter: { brandId?: string } = {}) {
|
|
122
|
+
return [...this.passports.values()].filter((p) => filter.brandId == null || p.brandId === filter.brandId).map(clone)
|
|
123
|
+
}
|
|
124
|
+
async savePassport(record: PassportRecord) {
|
|
125
|
+
this.passports.set(record.passportId, clone(record))
|
|
126
|
+
}
|
|
127
|
+
async deletePassport(passportId: string) {
|
|
128
|
+
this.passports.delete(passportId)
|
|
129
|
+
}
|
|
130
|
+
async getOffer(requestId: string) {
|
|
131
|
+
const record = this.offers.get(requestId)
|
|
132
|
+
return record == null ? undefined : clone(record)
|
|
133
|
+
}
|
|
134
|
+
async listOffers(filter: { passportId?: string; brandId?: string; status?: OfferRecord['status'] } = {}) {
|
|
135
|
+
return [...this.offers.values()]
|
|
136
|
+
.filter((o) => (filter.passportId == null || o.passportId === filter.passportId) && (filter.brandId == null || o.brandId === filter.brandId) && (filter.status == null || o.status === filter.status))
|
|
137
|
+
.map(clone)
|
|
138
|
+
}
|
|
139
|
+
async saveOffer(record: OfferRecord) {
|
|
140
|
+
this.offers.set(record.requestId, clone(record))
|
|
141
|
+
}
|
|
142
|
+
async listClaims(filter: { passportId?: string } = {}) {
|
|
143
|
+
return [...this.claims.values()].filter((c) => filter.passportId == null || c.passportId === filter.passportId).map(clone)
|
|
144
|
+
}
|
|
145
|
+
async saveClaim(record: ClaimRecord) {
|
|
146
|
+
this.claims.set(record.id, clone(record))
|
|
147
|
+
}
|
|
148
|
+
async getBrand(id: string) {
|
|
149
|
+
const record = this.brands.get(id)
|
|
150
|
+
return record == null ? undefined : clone(record)
|
|
151
|
+
}
|
|
152
|
+
async listBrands(ids?: string[]) {
|
|
153
|
+
return [...this.brands.values()].filter((b) => ids == null || ids.includes(b.id)).map(clone)
|
|
154
|
+
}
|
|
155
|
+
async saveBrand(record: BrandRecord) {
|
|
156
|
+
this.brands.set(record.id, clone(record))
|
|
157
|
+
}
|
|
158
|
+
async recordSpend(spend: SpendRecord) {
|
|
159
|
+
this.spends.push(clone(spend))
|
|
160
|
+
}
|
|
161
|
+
async spentSince(at: string) {
|
|
162
|
+
return this.spends.filter((s) => s.at >= at).reduce((sum, s) => sum + s.satoshis, 0)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export class MongoStore implements Store {
|
|
167
|
+
private passports: Collection<PassportRecord>
|
|
168
|
+
private offers: Collection<OfferRecord>
|
|
169
|
+
private claims: Collection<ClaimRecord>
|
|
170
|
+
private brands: Collection<BrandRecord>
|
|
171
|
+
private spends: Collection<SpendRecord>
|
|
172
|
+
|
|
173
|
+
constructor(db: Db) {
|
|
174
|
+
this.passports = db.collection<PassportRecord>('passports')
|
|
175
|
+
this.offers = db.collection<OfferRecord>('offers')
|
|
176
|
+
this.claims = db.collection<ClaimRecord>('claims')
|
|
177
|
+
this.brands = db.collection<BrandRecord>('brands')
|
|
178
|
+
this.spends = db.collection<SpendRecord>('spends')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async init(): Promise<void> {
|
|
182
|
+
await this.passports.createIndex({ passportId: 1 }, { unique: true })
|
|
183
|
+
await this.passports.createIndex({ brandId: 1 })
|
|
184
|
+
await this.offers.createIndex({ requestId: 1 }, { unique: true })
|
|
185
|
+
await this.offers.createIndex({ passportId: 1 })
|
|
186
|
+
await this.claims.createIndex({ id: 1 }, { unique: true })
|
|
187
|
+
await this.claims.createIndex({ passportId: 1 })
|
|
188
|
+
await this.brands.createIndex({ id: 1 }, { unique: true })
|
|
189
|
+
await this.spends.createIndex({ at: 1 })
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
private strip<T extends object>(doc: (T & { _id?: unknown }) | null): T | undefined {
|
|
193
|
+
if (doc == null) return undefined
|
|
194
|
+
const { _id: _ignored, ...rest } = doc
|
|
195
|
+
return rest as T
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async getPassport(passportId: string) {
|
|
199
|
+
return this.strip(await this.passports.findOne({ passportId }))
|
|
200
|
+
}
|
|
201
|
+
async listPassports(filter: { brandId?: string } = {}) {
|
|
202
|
+
const docs = await this.passports.find(filter.brandId == null ? {} : { brandId: filter.brandId }).sort({ createdAt: -1 }).toArray()
|
|
203
|
+
return docs.map((d) => this.strip(d)!)
|
|
204
|
+
}
|
|
205
|
+
async savePassport(record: PassportRecord) {
|
|
206
|
+
await this.passports.replaceOne({ passportId: record.passportId }, record, { upsert: true })
|
|
207
|
+
}
|
|
208
|
+
async deletePassport(passportId: string) {
|
|
209
|
+
await this.passports.deleteOne({ passportId, states: { $size: 0 } })
|
|
210
|
+
}
|
|
211
|
+
async getOffer(requestId: string) {
|
|
212
|
+
return this.strip(await this.offers.findOne({ requestId }))
|
|
213
|
+
}
|
|
214
|
+
async listOffers(filter: { passportId?: string; brandId?: string; status?: OfferRecord['status'] } = {}) {
|
|
215
|
+
const query: Record<string, unknown> = {}
|
|
216
|
+
if (filter.passportId != null) query.passportId = filter.passportId
|
|
217
|
+
if (filter.brandId != null) query.brandId = filter.brandId
|
|
218
|
+
if (filter.status != null) query.status = filter.status
|
|
219
|
+
const docs = await this.offers.find(query).sort({ createdAt: -1 }).toArray()
|
|
220
|
+
return docs.map((d) => this.strip(d)!)
|
|
221
|
+
}
|
|
222
|
+
async saveOffer(record: OfferRecord) {
|
|
223
|
+
await this.offers.replaceOne({ requestId: record.requestId }, record, { upsert: true })
|
|
224
|
+
}
|
|
225
|
+
async listClaims(filter: { passportId?: string } = {}) {
|
|
226
|
+
const docs = await this.claims.find(filter.passportId == null ? {} : { passportId: filter.passportId }).sort({ createdAt: -1 }).toArray()
|
|
227
|
+
return docs.map((d) => this.strip(d)!)
|
|
228
|
+
}
|
|
229
|
+
async saveClaim(record: ClaimRecord) {
|
|
230
|
+
await this.claims.replaceOne({ id: record.id }, record, { upsert: true })
|
|
231
|
+
}
|
|
232
|
+
async getBrand(id: string) {
|
|
233
|
+
return this.strip(await this.brands.findOne({ id }))
|
|
234
|
+
}
|
|
235
|
+
async listBrands(ids?: string[]) {
|
|
236
|
+
const docs = await this.brands.find(ids == null ? {} : { id: { $in: ids } }).sort({ createdAt: 1 }).toArray()
|
|
237
|
+
return docs.map((d) => this.strip(d)!)
|
|
238
|
+
}
|
|
239
|
+
async saveBrand(record: BrandRecord) {
|
|
240
|
+
await this.brands.replaceOne({ id: record.id }, record, { upsert: true })
|
|
241
|
+
}
|
|
242
|
+
async recordSpend(spend: SpendRecord) {
|
|
243
|
+
await this.spends.insertOne(spend)
|
|
244
|
+
}
|
|
245
|
+
async spentSince(at: string) {
|
|
246
|
+
const docs = await this.spends.find({ at: { $gte: at } }).toArray()
|
|
247
|
+
return docs.reduce((sum, s) => sum + s.satoshis, 0)
|
|
248
|
+
}
|
|
249
|
+
}
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
// The platform wallet: a BRC-100 wallet the API owns, which countersigns
|
|
2
|
+
// every state as publisher, holds the lock on every passport, builds, signs
|
|
3
|
+
// and sends the transactions, and obtains their merkle proofs. Live it is
|
|
4
|
+
// @bsv/wallet-toolbox on a SQLite file with a root key from the environment;
|
|
5
|
+
// in tests it is a ProtoWallet with a fixed key and made-up funding, which
|
|
6
|
+
// is what makes the first run need no money.
|
|
7
|
+
//
|
|
8
|
+
// Funding needs nothing from the person paying: the wallet derives a BRC-29
|
|
9
|
+
// receive key for a random prefix and suffix with the "anyone" sender, hands
|
|
10
|
+
// out its address, and takes the payment in with internalizeAction.
|
|
11
|
+
import { mkdirSync } from 'node:fs'
|
|
12
|
+
import { createRequire } from 'node:module'
|
|
13
|
+
import { dirname } from 'node:path'
|
|
14
|
+
import {
|
|
15
|
+
Beef,
|
|
16
|
+
LockingScript,
|
|
17
|
+
MerklePath,
|
|
18
|
+
P2PKH,
|
|
19
|
+
PrivateKey,
|
|
20
|
+
ProtoWallet,
|
|
21
|
+
PublicKey,
|
|
22
|
+
PushDrop,
|
|
23
|
+
Random,
|
|
24
|
+
Transaction,
|
|
25
|
+
UnlockingScript,
|
|
26
|
+
Utils,
|
|
27
|
+
type WalletInterface,
|
|
28
|
+
type WalletProtocol,
|
|
29
|
+
} from '@bsv/sdk'
|
|
30
|
+
import { OWNER_PROTOCOL_ID, type AcceptanceSigner, type DataSigner } from '@bsv/dpp-protocol'
|
|
31
|
+
import type { Network } from './config.js'
|
|
32
|
+
|
|
33
|
+
export interface Tip {
|
|
34
|
+
tx: Transaction
|
|
35
|
+
txid: string
|
|
36
|
+
outputIndex: number
|
|
37
|
+
beef: number[]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface Built {
|
|
41
|
+
tx: Transaction
|
|
42
|
+
txid: string
|
|
43
|
+
beef: number[]
|
|
44
|
+
/** The wallet's reference for an unsent action, needed to abort it; an issue that needed no signature has none. */
|
|
45
|
+
reference?: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The wallet side of a write: build a state's transaction unsent, send it
|
|
50
|
+
* and report only the network's answer, abort an unsent one, and read a
|
|
51
|
+
* mined transaction's merkle path. Its shape is the same live and in tests,
|
|
52
|
+
* so everything after the build is one code path.
|
|
53
|
+
*/
|
|
54
|
+
export interface WriterAdapter {
|
|
55
|
+
build(args: { lockingScript: LockingScript; tip?: Tip; passportId: string }): Promise<Built>
|
|
56
|
+
send(built: Built): Promise<'accepted' | 'refused' | 'unanswered'>
|
|
57
|
+
discard(built: Built): Promise<void>
|
|
58
|
+
merklePathFor(txid: string): Promise<MerklePath | undefined>
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The slice of the platform wallet the packages call: publisher signature and the lock key. */
|
|
62
|
+
export type PublisherWallet = DataSigner & {
|
|
63
|
+
getPublicKey: ProtoWallet['getPublicKey']
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface FundingAddress {
|
|
67
|
+
address: string
|
|
68
|
+
derivationPrefix: string
|
|
69
|
+
derivationSuffix: string
|
|
70
|
+
senderIdentityKey: string
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface PlatformWallet {
|
|
74
|
+
kind: 'toolbox' | 'test'
|
|
75
|
+
network: Network
|
|
76
|
+
identityKey: string
|
|
77
|
+
publisher: PublisherWallet
|
|
78
|
+
/** Signs acceptance records with the identity key itself, which no BRC-100 call provides. */
|
|
79
|
+
acceptanceSigner: AcceptanceSigner
|
|
80
|
+
adapter: WriterAdapter
|
|
81
|
+
fundingAddress(): Promise<FundingAddress>
|
|
82
|
+
/** Take in a payment made to a funding address, by its transaction id, once it is on the network. */
|
|
83
|
+
internalize(funding: FundingAddress, txid: string): Promise<{ satoshis: number }>
|
|
84
|
+
balance(): Promise<number>
|
|
85
|
+
close(): Promise<void>
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const BRC29_PROTOCOL: WalletProtocol = [2, '3241645161d8']
|
|
89
|
+
/** The "anyone" key: the sender of a payment that needs no key from the payer. */
|
|
90
|
+
export const ANYONE_IDENTITY_KEY = new PrivateKey(1).toPublicKey().toString()
|
|
91
|
+
|
|
92
|
+
function pathContains(path: MerklePath, txid: string): boolean {
|
|
93
|
+
try {
|
|
94
|
+
path.computeRoot(txid)
|
|
95
|
+
return true
|
|
96
|
+
} catch {
|
|
97
|
+
return false
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ------------------------------------------------------------- the toolbox wallet
|
|
102
|
+
|
|
103
|
+
export interface ToolboxWalletOptions {
|
|
104
|
+
network: Network
|
|
105
|
+
rootKeyHex: string
|
|
106
|
+
filePath: string
|
|
107
|
+
wocApiKey?: string
|
|
108
|
+
arcUrl?: string
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function openToolboxWallet(options: ToolboxWalletOptions): Promise<PlatformWallet> {
|
|
112
|
+
// CommonJS, loaded once here: the toolbox carries its own copy of the SDK,
|
|
113
|
+
// so its objects cross into this module as bytes and hex, never as instances.
|
|
114
|
+
const toolbox = await import('@bsv/wallet-toolbox')
|
|
115
|
+
const { Monitor, Services, Setup, StorageKnex, Wallet, WalletStorageManager } = toolbox
|
|
116
|
+
// The toolbox loads the SDK's CommonJS build; its key deriver must come from that same copy.
|
|
117
|
+
const sdkCjs = createRequire(import.meta.url)('@bsv/sdk') as typeof import('@bsv/sdk')
|
|
118
|
+
const chain = options.network
|
|
119
|
+
const rootKey = PrivateKey.fromHex(options.rootKeyHex)
|
|
120
|
+
const identityKey = rootKey.toPublicKey().toString()
|
|
121
|
+
|
|
122
|
+
mkdirSync(dirname(options.filePath), { recursive: true })
|
|
123
|
+
const knex = Setup.createSQLiteKnex(options.filePath)
|
|
124
|
+
const storage = new StorageKnex({
|
|
125
|
+
chain,
|
|
126
|
+
knex,
|
|
127
|
+
commissionSatoshis: 0,
|
|
128
|
+
commissionPubKeyHex: undefined,
|
|
129
|
+
feeModel: { model: 'sat/kb', value: 100 },
|
|
130
|
+
})
|
|
131
|
+
await storage.migrate('platform_wallet', Utils.toHex(Random(33)))
|
|
132
|
+
await storage.makeAvailable()
|
|
133
|
+
const manager = new WalletStorageManager(identityKey, storage)
|
|
134
|
+
await manager.makeAvailable()
|
|
135
|
+
|
|
136
|
+
const serviceOptions = Services.createDefaultOptions(chain)
|
|
137
|
+
if (options.wocApiKey != null) serviceOptions.whatsOnChainApiKey = options.wocApiKey
|
|
138
|
+
if (options.arcUrl != null) serviceOptions.arcUrl = options.arcUrl
|
|
139
|
+
const services = new Services(serviceOptions)
|
|
140
|
+
const monitor = new Monitor(Monitor.createDefaultWalletMonitorOptions(chain, manager, services))
|
|
141
|
+
const keyDeriver = new sdkCjs.CachedKeyDeriver(sdkCjs.PrivateKey.fromHex(options.rootKeyHex))
|
|
142
|
+
const wallet = new Wallet({ chain, keyDeriver: keyDeriver as unknown as ConstructorParameters<typeof Wallet>[0]['keyDeriver'], storage: manager, services, monitor })
|
|
143
|
+
await storage.findOrInsertUser(identityKey)
|
|
144
|
+
// The monitor asks a header source for proofs once a block is a minute old and attaches them to the wallet's transactions.
|
|
145
|
+
void monitor.startTasks()
|
|
146
|
+
|
|
147
|
+
const brc100 = wallet as unknown as WalletInterface
|
|
148
|
+
|
|
149
|
+
const adapter: WriterAdapter = {
|
|
150
|
+
async build({ lockingScript, tip, passportId }) {
|
|
151
|
+
const output = {
|
|
152
|
+
lockingScript: lockingScript.toHex(),
|
|
153
|
+
satoshis: 1,
|
|
154
|
+
outputDescription: 'dpp passport state',
|
|
155
|
+
basket: 'dpp',
|
|
156
|
+
customInstructions: JSON.stringify({ passportId }),
|
|
157
|
+
}
|
|
158
|
+
const actionOptions = { noSend: true, randomizeOutputs: false, acceptDelayedBroadcast: false }
|
|
159
|
+
if (tip == null) {
|
|
160
|
+
// The genesis needs no signature from this application: the wallet returns it signed, with no reference.
|
|
161
|
+
const created = await brc100.createAction({ description: 'dpp issue', outputs: [output], options: actionOptions })
|
|
162
|
+
if (created.tx == null || created.txid == null) {
|
|
163
|
+
if (created.signableTransaction?.reference != null) await brc100.abortAction({ reference: created.signableTransaction.reference }).catch(() => undefined)
|
|
164
|
+
throw new Error('the wallet did not return a signed transaction')
|
|
165
|
+
}
|
|
166
|
+
return { tx: Transaction.fromAtomicBEEF(created.tx), txid: created.txid, beef: Array.from(created.tx) }
|
|
167
|
+
}
|
|
168
|
+
// Every later state spends the tip, whose lock only this wallet can open.
|
|
169
|
+
const created = await brc100.createAction({
|
|
170
|
+
description: 'dpp state',
|
|
171
|
+
inputBEEF: tip.beef,
|
|
172
|
+
inputs: [{ outpoint: `${tip.txid}.${tip.outputIndex}`, unlockingScriptLength: 73, inputDescription: 'dpp passport tip' }],
|
|
173
|
+
outputs: [output],
|
|
174
|
+
options: actionOptions,
|
|
175
|
+
})
|
|
176
|
+
const signable = created.signableTransaction
|
|
177
|
+
if (signable == null) throw new Error('the wallet did not return a transaction to sign')
|
|
178
|
+
try {
|
|
179
|
+
const unsigned = Transaction.fromAtomicBEEF(signable.tx)
|
|
180
|
+
const at = unsigned.inputs.findIndex((input) => (input.sourceTXID ?? input.sourceTransaction?.id('hex')) === tip.txid && input.sourceOutputIndex === tip.outputIndex)
|
|
181
|
+
if (at === -1) throw new Error('the wallet built a transaction that does not spend the tip')
|
|
182
|
+
const unlockingScript = await new PushDrop(brc100).unlock(OWNER_PROTOCOL_ID, passportId, 'self').sign(unsigned, at)
|
|
183
|
+
const signed = await brc100.signAction({ reference: signable.reference, spends: { [at]: { unlockingScript: unlockingScript.toHex() } }, options: { noSend: true } })
|
|
184
|
+
if (signed.tx == null || signed.txid == null) throw new Error('the wallet did not return a signed transaction')
|
|
185
|
+
return { tx: Transaction.fromAtomicBEEF(signed.tx), txid: signed.txid, beef: Array.from(signed.tx), reference: signable.reference }
|
|
186
|
+
} catch (cause) {
|
|
187
|
+
// The action already holds the wallet's inputs: give them back before stopping.
|
|
188
|
+
await brc100.abortAction({ reference: signable.reference }).catch(() => undefined)
|
|
189
|
+
throw cause
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
async send(built) {
|
|
193
|
+
// Sections 4 and 5: a send-only action, reporting nothing but the network's answer.
|
|
194
|
+
let result
|
|
195
|
+
try {
|
|
196
|
+
result = await brc100.createAction({ description: 'dpp send', options: { sendWith: [built.txid], acceptDelayedBroadcast: false } })
|
|
197
|
+
} catch (cause) {
|
|
198
|
+
const reviews = ((cause as { reviewActionResults?: Array<{ txid: string; status: string }> })?.reviewActionResults ?? [])
|
|
199
|
+
return reviews.some((r) => r.txid === built.txid && r.status === 'invalidTx') ? 'refused' : 'unanswered'
|
|
200
|
+
}
|
|
201
|
+
const status = result.sendWithResults?.find((r) => r.txid === built.txid)?.status
|
|
202
|
+
if (status === 'unproven') return 'accepted'
|
|
203
|
+
if (status === 'failed') return 'refused'
|
|
204
|
+
return 'unanswered'
|
|
205
|
+
},
|
|
206
|
+
async discard(built) {
|
|
207
|
+
// An unsent action holds the wallet's inputs until it is sent or aborted; an issue without a reference is found by its txid.
|
|
208
|
+
await brc100.abortAction({ reference: built.reference ?? built.txid }).catch(() => undefined)
|
|
209
|
+
},
|
|
210
|
+
async merklePathFor(txid) {
|
|
211
|
+
// The wallet attaches the proof as part of being a wallet, but can list a transaction only while its output is unspent.
|
|
212
|
+
const outputs = await brc100.listOutputs({ basket: 'dpp', include: 'entire transactions', limit: 10000 })
|
|
213
|
+
if (outputs.BEEF != null) {
|
|
214
|
+
const beef = Beef.fromBinary(outputs.BEEF)
|
|
215
|
+
const held = beef.findTxid(txid)
|
|
216
|
+
const path = held?.bumpIndex == null ? held?.tx?.merklePath : beef.bumps[held.bumpIndex]
|
|
217
|
+
if (path != null && pathContains(path, txid)) return path
|
|
218
|
+
}
|
|
219
|
+
// Once spent, ask the services directly.
|
|
220
|
+
try {
|
|
221
|
+
const found = await services.getMerklePath(txid)
|
|
222
|
+
if (found.merklePath != null) {
|
|
223
|
+
const path = MerklePath.fromHex(found.merklePath.toHex())
|
|
224
|
+
if (pathContains(path, txid)) return path
|
|
225
|
+
}
|
|
226
|
+
} catch {
|
|
227
|
+
// No proof yet, or no header source: the worker asks again later.
|
|
228
|
+
}
|
|
229
|
+
return undefined
|
|
230
|
+
},
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
kind: 'toolbox',
|
|
235
|
+
network: chain,
|
|
236
|
+
identityKey,
|
|
237
|
+
publisher: brc100 as unknown as PublisherWallet,
|
|
238
|
+
acceptanceSigner: { sign: (preimage) => rootKey.sign(preimage).toDER() as number[] },
|
|
239
|
+
adapter,
|
|
240
|
+
async fundingAddress() {
|
|
241
|
+
const derivationPrefix = Utils.toBase64(Random(8))
|
|
242
|
+
const derivationSuffix = Utils.toBase64(Random(8))
|
|
243
|
+
const { publicKey } = await brc100.getPublicKey({ protocolID: BRC29_PROTOCOL, keyID: `${derivationPrefix} ${derivationSuffix}`, counterparty: ANYONE_IDENTITY_KEY, forSelf: true })
|
|
244
|
+
return { address: PublicKey.fromString(publicKey).toAddress(chain === 'test' ? 'testnet' : 'mainnet'), derivationPrefix, derivationSuffix, senderIdentityKey: ANYONE_IDENTITY_KEY }
|
|
245
|
+
},
|
|
246
|
+
async internalize(funding, txid) {
|
|
247
|
+
const beef = await services.getBeefForTxid(txid)
|
|
248
|
+
const tx = Transaction.fromHex(Utils.toHex(beef.findTxid(txid)?.tx?.toBinary() ?? []))
|
|
249
|
+
const wanted = new P2PKH().lock(funding.address).toHex()
|
|
250
|
+
const outputs = tx.outputs.map((o, outputIndex) => ({ o, outputIndex })).filter(({ o }) => o.lockingScript.toHex() === wanted)
|
|
251
|
+
if (outputs.length === 0) throw new Error(`${txid} pays nothing to ${funding.address}`)
|
|
252
|
+
await brc100.internalizeAction({
|
|
253
|
+
tx: beef.toBinaryAtomic(txid),
|
|
254
|
+
outputs: outputs.map(({ outputIndex }) => ({
|
|
255
|
+
outputIndex,
|
|
256
|
+
protocol: 'wallet payment',
|
|
257
|
+
paymentRemittance: { derivationPrefix: funding.derivationPrefix, derivationSuffix: funding.derivationSuffix, senderIdentityKey: funding.senderIdentityKey },
|
|
258
|
+
})),
|
|
259
|
+
description: 'Funding the platform wallet',
|
|
260
|
+
})
|
|
261
|
+
return { satoshis: outputs.reduce((sum, { o }) => sum + (o.satoshis ?? 0), 0) }
|
|
262
|
+
},
|
|
263
|
+
async balance() {
|
|
264
|
+
const { outputs } = await brc100.listOutputs({ basket: 'default', limit: 10000 })
|
|
265
|
+
return outputs.filter((o) => o.spendable).reduce((sum, o) => sum + o.satoshis, 0)
|
|
266
|
+
},
|
|
267
|
+
async close() {
|
|
268
|
+
monitor.stopTasks()
|
|
269
|
+
await wallet.destroy()
|
|
270
|
+
},
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---------------------------------------------------------------- the test wallet
|
|
275
|
+
|
|
276
|
+
const ANYONE_CAN_SPEND = new LockingScript([{ op: 0x51 }])
|
|
277
|
+
|
|
278
|
+
/** A funding output with a made-up proof, standing in for coins a wallet would hold. Anyone can spend it, which is why it is never used live. */
|
|
279
|
+
function syntheticFunding(): Transaction {
|
|
280
|
+
const tx = new Transaction()
|
|
281
|
+
tx.addOutput({ satoshis: 10_000, lockingScript: ANYONE_CAN_SPEND })
|
|
282
|
+
tx.merklePath = MerklePath.fromCoinbaseTxidAndHeight(tx.id('hex'), 800_000)
|
|
283
|
+
return tx
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/**
|
|
287
|
+
* A wallet for tests and dry runs: fixed keys, synthetic funding, transactions
|
|
288
|
+
* built here the way a wallet would fund them, and made-up proofs that only
|
|
289
|
+
* an index with its header checks off would take. Nothing is sent anywhere.
|
|
290
|
+
*/
|
|
291
|
+
export function openTestWallet(rootKeyHex = '11'.repeat(32), network: Network = 'main'): PlatformWallet {
|
|
292
|
+
const rootKey = PrivateKey.fromHex(rootKeyHex)
|
|
293
|
+
const wallet = new ProtoWallet(rootKey)
|
|
294
|
+
const identityKey = rootKey.toPublicKey().toString()
|
|
295
|
+
let proofHeight = 800_001
|
|
296
|
+
const proofs = new Map<string, MerklePath>()
|
|
297
|
+
let funded = 10_000
|
|
298
|
+
|
|
299
|
+
const adapter: WriterAdapter = {
|
|
300
|
+
async build({ lockingScript, tip, passportId }) {
|
|
301
|
+
const tx = new Transaction()
|
|
302
|
+
if (tip == null) {
|
|
303
|
+
tx.addInput({ sourceTransaction: syntheticFunding(), sourceOutputIndex: 0, unlockingScript: new UnlockingScript([]) })
|
|
304
|
+
tx.addOutput({ satoshis: 1, lockingScript })
|
|
305
|
+
tx.addOutput({ satoshis: 9_000, lockingScript: ANYONE_CAN_SPEND })
|
|
306
|
+
} else {
|
|
307
|
+
// The tip, then its change, the way a wallet funds the next state; the passport output stays first.
|
|
308
|
+
tx.addInput({ sourceTransaction: tip.tx, sourceOutputIndex: tip.outputIndex, unlockingScript: new UnlockingScript([]) })
|
|
309
|
+
tx.addInput({ sourceTransaction: tip.tx, sourceOutputIndex: 1, unlockingScript: new UnlockingScript([]) })
|
|
310
|
+
tx.addOutput({ satoshis: 1, lockingScript })
|
|
311
|
+
tx.addOutput({ satoshis: Math.max(1_000, (tip.tx.outputs[1]?.satoshis ?? 9_000) - 1_000), lockingScript: ANYONE_CAN_SPEND })
|
|
312
|
+
tx.inputs[0].unlockingScript = await new PushDrop(wallet as unknown as WalletInterface).unlock(OWNER_PROTOCOL_ID, passportId, 'self').sign(tx, 0)
|
|
313
|
+
}
|
|
314
|
+
return { tx, txid: tx.id('hex'), beef: tx.toAtomicBEEF(), reference: tip == null ? undefined : 'test-reference' }
|
|
315
|
+
},
|
|
316
|
+
async send(built) {
|
|
317
|
+
funded -= 200
|
|
318
|
+
proofs.set(built.txid, MerklePath.fromCoinbaseTxidAndHeight(built.txid, proofHeight++))
|
|
319
|
+
return 'accepted'
|
|
320
|
+
},
|
|
321
|
+
async discard() {},
|
|
322
|
+
async merklePathFor(txid) {
|
|
323
|
+
return proofs.get(txid)
|
|
324
|
+
},
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return {
|
|
328
|
+
kind: 'test',
|
|
329
|
+
network,
|
|
330
|
+
identityKey,
|
|
331
|
+
publisher: wallet,
|
|
332
|
+
acceptanceSigner: { sign: (preimage) => rootKey.sign(preimage).toDER() as number[] },
|
|
333
|
+
adapter,
|
|
334
|
+
async fundingAddress() {
|
|
335
|
+
return { address: rootKey.toPublicKey().toAddress(network === 'test' ? 'testnet' : 'mainnet'), derivationPrefix: 'test', derivationSuffix: 'test', senderIdentityKey: ANYONE_IDENTITY_KEY }
|
|
336
|
+
},
|
|
337
|
+
async internalize() {
|
|
338
|
+
funded += 10_000
|
|
339
|
+
return { satoshis: 10_000 }
|
|
340
|
+
},
|
|
341
|
+
async balance() {
|
|
342
|
+
return funded
|
|
343
|
+
},
|
|
344
|
+
async close() {},
|
|
345
|
+
}
|
|
346
|
+
}
|