@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.
Files changed (81) hide show
  1. package/LICENSE +203 -0
  2. package/README.md +73 -2
  3. package/dist/index.js +97 -0
  4. package/package.json +53 -4
  5. package/template/Dockerfile +35 -0
  6. package/template/README.md +134 -0
  7. package/template/_dockerignore +6 -0
  8. package/template/_env.example +53 -0
  9. package/template/_github/workflows/ci.yml +23 -0
  10. package/template/_gitignore +8 -0
  11. package/template/_prettierrc +6 -0
  12. package/template/apps/api/API.md +49 -0
  13. package/template/apps/api/package.json +34 -0
  14. package/template/apps/api/src/auth.ts +55 -0
  15. package/template/apps/api/src/claims.ts +85 -0
  16. package/template/apps/api/src/cli.ts +42 -0
  17. package/template/apps/api/src/config.ts +66 -0
  18. package/template/apps/api/src/custody.ts +186 -0
  19. package/template/apps/api/src/dev-index.ts +71 -0
  20. package/template/apps/api/src/env.ts +14 -0
  21. package/template/apps/api/src/identifiers.ts +57 -0
  22. package/template/apps/api/src/index-client.ts +136 -0
  23. package/template/apps/api/src/main.ts +50 -0
  24. package/template/apps/api/src/parties.ts +68 -0
  25. package/template/apps/api/src/platform.ts +121 -0
  26. package/template/apps/api/src/profiles.ts +100 -0
  27. package/template/apps/api/src/reader.ts +96 -0
  28. package/template/apps/api/src/server.ts +420 -0
  29. package/template/apps/api/src/store.ts +249 -0
  30. package/template/apps/api/src/wallet.ts +346 -0
  31. package/template/apps/api/src/worker.ts +106 -0
  32. package/template/apps/api/src/writer.ts +351 -0
  33. package/template/apps/api/test/config.test.ts +15 -0
  34. package/template/apps/api/test/external-index.test.ts +31 -0
  35. package/template/apps/api/test/lifecycle.test.ts +136 -0
  36. package/template/apps/api/tsconfig.json +9 -0
  37. package/template/apps/api/vitest.config.ts +9 -0
  38. package/template/apps/web/components.json +21 -0
  39. package/template/apps/web/index.html +12 -0
  40. package/template/apps/web/package.json +33 -0
  41. package/template/apps/web/src/app.tsx +51 -0
  42. package/template/apps/web/src/components/bits.tsx +188 -0
  43. package/template/apps/web/src/components/layout.tsx +118 -0
  44. package/template/apps/web/src/components/passport-form.tsx +244 -0
  45. package/template/apps/web/src/components/read-passport.tsx +48 -0
  46. package/template/apps/web/src/components/reading.tsx +157 -0
  47. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  48. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  49. package/template/apps/web/src/components/ui/button.tsx +63 -0
  50. package/template/apps/web/src/components/ui/card.tsx +91 -0
  51. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  52. package/template/apps/web/src/components/ui/input.tsx +20 -0
  53. package/template/apps/web/src/components/ui/label.tsx +21 -0
  54. package/template/apps/web/src/components/ui/select.tsx +189 -0
  55. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  56. package/template/apps/web/src/components/ui/table.tsx +115 -0
  57. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  58. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  59. package/template/apps/web/src/index.css +81 -0
  60. package/template/apps/web/src/lib/api.ts +286 -0
  61. package/template/apps/web/src/lib/auth.ts +10 -0
  62. package/template/apps/web/src/lib/format.ts +64 -0
  63. package/template/apps/web/src/lib/session.tsx +92 -0
  64. package/template/apps/web/src/lib/use-load.ts +46 -0
  65. package/template/apps/web/src/main.tsx +18 -0
  66. package/template/apps/web/src/pages/accept.tsx +108 -0
  67. package/template/apps/web/src/pages/brand.tsx +94 -0
  68. package/template/apps/web/src/pages/brands.tsx +104 -0
  69. package/template/apps/web/src/pages/home.tsx +51 -0
  70. package/template/apps/web/src/pages/new-passport.tsx +114 -0
  71. package/template/apps/web/src/pages/operations.tsx +150 -0
  72. package/template/apps/web/src/pages/passport.tsx +568 -0
  73. package/template/apps/web/src/pages/public-passport.tsx +24 -0
  74. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  75. package/template/apps/web/src/pages/verify.tsx +30 -0
  76. package/template/apps/web/src/pages/wallet.tsx +141 -0
  77. package/template/apps/web/tsconfig.json +29 -0
  78. package/template/apps/web/vite.config.ts +15 -0
  79. package/template/deploy/compose.yml +26 -0
  80. package/template/package.json +42 -0
  81. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,106 @@
1
+ // The duties that run on their own, after the screen that caused them:
2
+ // announcing again when the index could not be reached, fetching each
3
+ // state's merkle proof once it is mined, and pushing that proof to the
4
+ // index. They are read from the journal, never from a separate queue, so
5
+ // the journal stays the one source of truth and a retry never rebuilds.
6
+ // Run one worker per platform; it is a loop over pending work, not a job
7
+ // library.
8
+ import { Utils } from '@bsv/sdk'
9
+ import type { IndexClient } from './index-client.js'
10
+ import type { PassportRecord, Store } from './store.js'
11
+ import type { Writer } from './writer.js'
12
+
13
+ export interface Duty {
14
+ passportId: string
15
+ txid: string
16
+ op: string
17
+ duty: 'announce' | 'prove' | 'push-proof' | 'resolve-interrupted'
18
+ since: string
19
+ }
20
+
21
+ export interface WorkerOptions {
22
+ store: Store
23
+ index: IndexClient
24
+ writer: Writer
25
+ log?: (line: string) => void
26
+ }
27
+
28
+ /** What is still owed for every passport, oldest first. */
29
+ export async function pendingDuties(store: Store): Promise<Duty[]> {
30
+ const duties: Duty[] = []
31
+ for (const passport of await store.listPassports()) {
32
+ for (const state of passport.states) {
33
+ if (state.network === 'pending') {
34
+ duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'resolve-interrupted', since: state.timestamp })
35
+ continue
36
+ }
37
+ if (state.network !== 'accepted' && state.network !== 'dry-run') continue
38
+ if (state.index === 'unreachable' || state.index === 'pending') duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'announce', since: state.timestamp })
39
+ if (state.proof == null) duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'prove', since: state.timestamp })
40
+ else if (state.proofPushed !== true) duties.push({ passportId: passport.passportId, txid: state.txid, op: state.op, duty: 'push-proof', since: state.timestamp })
41
+ }
42
+ }
43
+ return duties.sort((a, b) => a.since.localeCompare(b.since))
44
+ }
45
+
46
+ /** One pass over the pending duties. Returns what it did, one line each. */
47
+ export async function runDuties(options: WorkerOptions): Promise<string[]> {
48
+ const { store, index, writer } = options
49
+ const log = options.log ?? (() => {})
50
+ const done: string[] = []
51
+ const say = (line: string): void => {
52
+ done.push(line)
53
+ log(line)
54
+ }
55
+ for (const duty of await pendingDuties(store)) {
56
+ const passport = await store.getPassport(duty.passportId)
57
+ const state = passport?.states.find((s) => s.txid === duty.txid)
58
+ if (passport == null || state == null) continue
59
+ // Only the operator can say what became of an interrupted write; it is listed, never guessed.
60
+ if (duty.duty === 'resolve-interrupted') continue
61
+ try {
62
+ if (duty.duty === 'announce') {
63
+ const announced = await index.announce(Utils.toArray(state.beef, 'base64') as number[])
64
+ state.index = announced
65
+ state.refusal = index.lastRefusal
66
+ await store.savePassport(passport)
67
+ say(`${duty.op} ${duty.txid.slice(0, 12)}... announced again: ${announced}${index.lastRefusal == null ? '' : ` (${index.lastRefusal})`}`)
68
+ } else {
69
+ const proven = await writer.prove(passport, duty.txid)
70
+ say(`${duty.op} ${duty.txid.slice(0, 12)}... ${proven ? 'proof held' : 'no proof yet'}`)
71
+ }
72
+ } catch (cause) {
73
+ say(`${duty.op} ${duty.txid.slice(0, 12)}... ${duty.duty} failed: ${cause instanceof Error ? cause.message : String(cause)}`)
74
+ }
75
+ }
76
+ return done
77
+ }
78
+
79
+ /** Run the duties on an interval until stopped. */
80
+ export function startWorker(options: WorkerOptions & { intervalMs?: number }): { stop: () => void } {
81
+ const interval = options.intervalMs ?? 60_000
82
+ let running = false
83
+ let stopped = false
84
+ const tick = async (): Promise<void> => {
85
+ if (running || stopped) return
86
+ running = true
87
+ try {
88
+ await runDuties(options)
89
+ } finally {
90
+ running = false
91
+ }
92
+ }
93
+ const timer = setInterval(() => void tick(), interval)
94
+ void tick()
95
+ return {
96
+ stop: () => {
97
+ stopped = true
98
+ clearInterval(timer)
99
+ },
100
+ }
101
+ }
102
+
103
+ export function summariseJournal(passport: PassportRecord): { states: number; proven: number; pending: number; status: string } {
104
+ const proven = passport.states.filter((s) => s.proof != null && s.proofPushed === true).length
105
+ return { states: passport.states.length, proven, pending: passport.states.length - proven, status: passport.status }
106
+ }
@@ -0,0 +1,351 @@
1
+ // The writer: every state goes through the six steps of spec/writing.md in
2
+ // order. Build it unsent; check it with the reader's own rules; announce it
3
+ // to the index and send only on admission; send, and report only the
4
+ // network's answer; push the proof once the wallet has it; keep everything.
5
+ // The journal entry is written before each step is acted on, so a retry
6
+ // continues an operation and never builds a second transaction.
7
+ //
8
+ // Under managed custody the platform wallet is publisher and holds the lock;
9
+ // the acting party (a brand, a holder) signs as actor from a key the
10
+ // platform derives for it, and the controller key in field 6 is that
11
+ // party's per-passport key.
12
+ import { MerklePath, Transaction, Utils, type WalletProtocol } from '@bsv/sdk'
13
+ import {
14
+ acceptanceCommitment,
15
+ buildLockingScript,
16
+ completeState,
17
+ findDppOutputs,
18
+ ownerBlobHash,
19
+ ownerKeyFor,
20
+ verifyChain,
21
+ verifyOwnerBlob,
22
+ type DppStateDataV2,
23
+ type DppStateV2,
24
+ type ManagedAcceptanceRecord,
25
+ } from '@bsv/dpp-protocol'
26
+ import type { ProfileId } from '@bsv/dpp-profiles'
27
+ import { identifierProblems, type IdentifierPolicy } from './identifiers.js'
28
+ import type { IndexClient } from './index-client.js'
29
+ import type { Party } from './parties.js'
30
+ import { validatePayload } from './profiles.js'
31
+ import type { PassportRecord, StateEntry, Store } from './store.js'
32
+ import type { PlatformWallet, Tip } from './wallet.js'
33
+
34
+ /** BRC-43 protocol the owner tier is encrypted under (spec/record-model.md section 7). */
35
+ const OWNER_DATA_PROTOCOL: WalletProtocol = [2, 'dpp owner data v1']
36
+
37
+ export class WriteRefused extends Error {
38
+ constructor(
39
+ readonly code: string,
40
+ detail: string
41
+ ) {
42
+ super(detail)
43
+ }
44
+ }
45
+
46
+ export interface WriterOptions {
47
+ store: Store
48
+ wallet: PlatformWallet
49
+ index: IndexClient
50
+ identifiers: IdentifierPolicy
51
+ /** Whether writes may reach the chain. False builds, checks and journals a state and then stops before the send. */
52
+ livePublishing: boolean
53
+ spendCapSatoshis: number
54
+ log?: (line: string) => void
55
+ }
56
+
57
+ export interface WriteOutcome {
58
+ entry: StateEntry
59
+ state: DppStateV2
60
+ record: PassportRecord
61
+ }
62
+
63
+ const instant = (): string => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
64
+ const short = (hex: string): string => `${hex.slice(0, 12)}...`
65
+
66
+ export class Writer {
67
+ private readonly log: (line: string) => void
68
+
69
+ constructor(private readonly options: WriterOptions) {
70
+ this.log = options.log ?? (() => {})
71
+ }
72
+
73
+ /** The platform wallet's lock key for a passport: its own per-passport key, which only it can open. */
74
+ private lockKey(passportId: string): Promise<string> {
75
+ return ownerKeyFor(passportId, this.options.wallet.publisher)
76
+ }
77
+
78
+ /** The tip from the journal's BEEF, which carries its ancestry and, once proven, its merkle path. */
79
+ private tipOf(record: PassportRecord): Tip | undefined {
80
+ const last = record.states.at(-1)
81
+ if (last == null) return undefined
82
+ const beef = Utils.toArray(last.beef, 'base64') as number[]
83
+ return { tx: Transaction.fromAtomicBEEF(beef), txid: last.txid, outputIndex: last.outputIndex, beef }
84
+ }
85
+
86
+ private async sealOwnerTier(controller: Party, passportId: string, profile: ProfileId, fields: Record<string, unknown>): Promise<{ hash: string; ciphertext: number[] }> {
87
+ const check = validatePayload(profile, 'restricted', fields)
88
+ if (!check.valid) throw new WriteRefused('owner-tier-invalid', `the owner tier is refused by the restricted schema of ${profile}: ${check.problems.join('; ')}`)
89
+ const plaintext = Utils.toArray(JSON.stringify(fields), 'utf8') as number[]
90
+ const { ciphertext } = await controller.wallet.encrypt({ plaintext, protocolID: OWNER_DATA_PROTOCOL, keyID: passportId, counterparty: 'self' })
91
+ const hash = ownerBlobHash(ciphertext)
92
+ if (!verifyOwnerBlob(ciphertext, hash)) throw new WriteRefused('owner-tier-unsound', 'the sealed owner tier does not verify against its hash')
93
+ return { hash, ciphertext }
94
+ }
95
+
96
+ private async withinSpendCap(): Promise<void> {
97
+ const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString()
98
+ const spent = await this.options.store.spentSince(dayAgo)
99
+ if (spent >= this.options.spendCapSatoshis) throw new WriteRefused('spend-cap', `the platform has spent ${spent} satoshis in the last day, at or over SPEND_CAP_SATOSHIS=${this.options.spendCapSatoshis}`)
100
+ }
101
+
102
+ /**
103
+ * One state through the six steps. `actor` signs as actor; `controller` is
104
+ * the party whose per-passport key field 6 names after this state (the
105
+ * actor until a hand-on, the recipient on a TRANSFER).
106
+ */
107
+ private async writeState(args: {
108
+ record: PassportRecord
109
+ op: StateEntry['op']
110
+ actor: Party
111
+ controller: Party
112
+ profile: ProfileId
113
+ /** A new public payload and owner tier; absent, the tip's are carried unchanged, which RETIRE requires and a hand-on keeps simple. */
114
+ payload?: Record<string, unknown>
115
+ ownerFields?: Record<string, unknown>
116
+ eventData?: Record<string, unknown>
117
+ acceptance?: ManagedAcceptanceRecord
118
+ }): Promise<WriteOutcome> {
119
+ const { record, op, actor, controller, profile } = args
120
+ const { store, wallet, index } = this.options
121
+ const passportId = record.passportId
122
+ const tip = this.tipOf(record)
123
+ if (op === 'ISSUE' && tip != null) throw new WriteRefused('already-issued', `${passportId} already has ${record.states.length} state(s); a second genesis is never written`)
124
+ if (op !== 'ISSUE' && tip == null) throw new WriteRefused('not-issued', `${passportId} has no genesis to follow`)
125
+ if (record.status === 'retired') throw new WriteRefused('retired', `${passportId} ended with a RETIRE; nothing may follow it`)
126
+ const pending = record.states.find((s) => s.network === 'pending')
127
+ if (pending != null) throw new WriteRefused('operation-interrupted', `${short(pending.txid)} was built and announced but its send was never answered for; resolve it first (was it sent, or abandoned?) before the next state`)
128
+
129
+ const tipEntry = record.states.at(-1)
130
+ let payloadPublic: string
131
+ let sealed: { hash: string; ciphertext: number[] }
132
+ if (args.payload != null) {
133
+ const publicCheck = validatePayload(profile, 'public', args.payload)
134
+ if (!publicCheck.valid) throw new WriteRefused('payload-invalid', `the public payload is refused by the ${profile} schema: ${publicCheck.problems.join('; ')}`)
135
+ payloadPublic = JSON.stringify(args.payload)
136
+ // A new payload with no owner fields carries the tip's sealed tier unchanged, when the actor still controls it.
137
+ sealed =
138
+ args.ownerFields == null && tipEntry?.ownerTier != null
139
+ ? { hash: tipEntry.ownerTier.hash, ciphertext: Utils.toArray(tipEntry.ownerTier.ciphertext, 'base64') as number[] }
140
+ : await this.sealOwnerTier(controller, passportId, profile, args.ownerFields ?? {})
141
+ } else {
142
+ if (tipEntry?.ownerTier == null) throw new WriteRefused('nothing-to-carry', `${passportId} has no tip whose payload and owner tier this ${op} could carry`)
143
+ payloadPublic = tipEntry.payloadPublic
144
+ sealed = { hash: tipEntry.ownerTier.hash, ciphertext: Utils.toArray(tipEntry.ownerTier.ciphertext, 'base64') as number[] }
145
+ }
146
+ await this.withinSpendCap()
147
+
148
+ const previousController = tip == null ? undefined : record.holder.controllerKey
149
+ const controllerKey = await controller.controllerKey(passportId)
150
+ const data: DppStateDataV2 = {
151
+ version: '2',
152
+ op,
153
+ passportId,
154
+ timestamp: instant(),
155
+ ownerIdentityKey: controllerKey,
156
+ actorIdentityKey: actor.identityKey,
157
+ actorKeyId: actor.name,
158
+ eventData: args.eventData == null ? '' : JSON.stringify(args.eventData),
159
+ payloadPublic,
160
+ payloadOwnerHash: sealed.hash,
161
+ previousTxid: tip == null ? '' : tip.txid,
162
+ previousOutputIndex: tip == null ? null : tip.outputIndex,
163
+ lineageGenesis: tip == null ? null : { txid: record.states[0].txid, outputIndex: record.states[0].outputIndex },
164
+ // The actor is never the controller key itself, so every later state proves control by linkage from the actor's identity key to the previous field 6.
165
+ controlLinkage: tip == null ? '' : await actor.controlLinkage(passportId),
166
+ authorisationCommitment: args.acceptance == null ? '' : acceptanceCommitment(args.acceptance),
167
+ }
168
+ if (tip != null && previousController != null && (await actor.controllerKey(passportId)) !== previousController) {
169
+ throw new WriteRefused('not-the-controller', `${actor.name} does not control ${passportId}; its controller key is held by ${record.holder.party}`)
170
+ }
171
+ const state = (await completeState(data, actor.wallet, wallet.publisher)) as DppStateV2
172
+ const lockingScript = buildLockingScript(state, await this.lockKey(passportId))
173
+
174
+ // Section 3: built unsent, complete and signed, spending nothing until it is sent.
175
+ let built
176
+ try {
177
+ built = await wallet.adapter.build({ lockingScript, tip, passportId })
178
+ } catch (cause) {
179
+ throw new WriteRefused('wallet-build-failed', `the wallet could not build the ${op} (${cause instanceof Error ? cause.message : String(cause)}); nothing was sent. An empty wallet needs funding first.`)
180
+ }
181
+ const outputIndex = findDppOutputs(built.tx)[0]?.outputIndex ?? 0
182
+ const entry: StateEntry = {
183
+ op,
184
+ txid: built.txid,
185
+ outputIndex,
186
+ rawTx: built.tx.toHex(),
187
+ beef: Utils.toBase64(built.beef),
188
+ timestamp: data.timestamp,
189
+ actor: actor.name,
190
+ controllerKey,
191
+ payloadPublic: data.payloadPublic,
192
+ ownerTier: { hash: sealed.hash, ciphertext: Utils.toBase64(sealed.ciphertext) },
193
+ index: 'pending',
194
+ network: 'pending',
195
+ }
196
+ record.states.push(entry)
197
+ await store.savePassport(record)
198
+ this.log(`${op} ${short(built.txid)} built unsent for ${passportId}`)
199
+
200
+ const settle = async (patch: Partial<StateEntry>): Promise<void> => {
201
+ Object.assign(entry, patch)
202
+ await store.savePassport(record)
203
+ }
204
+ // A state that is not written leaves the journal as it was: the unsent action is aborted and the entry removed.
205
+ const abandon = async (code: string, detail: string): Promise<never> => {
206
+ await wallet.adapter.discard(built)
207
+ record.states.pop()
208
+ if (record.states.length === 0) await store.deletePassport(record.passportId)
209
+ else await store.savePassport(record)
210
+ throw new WriteRefused(code, detail)
211
+ }
212
+
213
+ // Section 2: the verifier's own checks on the unsent transaction, with the lineage so far in front of it.
214
+ const lineage = record.states.slice(0, -1).map((s) => Transaction.fromHex(s.rawTx))
215
+ const checked = await verifyChain([...lineage, built.tx], { chainTracker: 'scripts only', serverIdentityKey: wallet.identityKey, managedAcceptance: true })
216
+ if (!checked.valid) await abandon('own-check-refused', `the writer's own check refuses the unsent ${op}: ${checked.error ?? 'no reason given'}`)
217
+
218
+ // Section 3: a state after the genesis spends the tip the index returns for the passport.
219
+ if (tip != null) {
220
+ const held = await index.lineage(passportId).catch(() => undefined)
221
+ const heldTip = held?.at(-1)?.id('hex')
222
+ if (held != null && heldTip !== tip.txid) {
223
+ await abandon('tip-moved', `the index's tip for ${passportId} is ${heldTip == null ? 'nothing' : short(heldTip)}, not ${short(tip.txid)}`)
224
+ }
225
+ }
226
+
227
+ // Section 3: announce first, send only on admission. An unreachable index refuses nothing.
228
+ let announced = await index.announce(built.beef)
229
+ await settle({ index: announced, refusal: index.lastRefusal })
230
+ if (announced === 'refused') await abandon('index-refused', `the index refused ${short(built.txid)} while it was still a draft: ${index.lastRefusal ?? 'no reason given'}`)
231
+ if (announced === 'unauthorised') await abandon('index-unauthorised', 'the index wants a submit token, or a different one; nothing was sent')
232
+
233
+ if (!this.options.livePublishing && wallet.kind === 'toolbox') {
234
+ await abandon('live-publishing-off', 'LIVE_PUBLISHING is false: the state was built, checked and admitted as a draft, then aborted. Set LIVE_PUBLISHING=true to write to the chain.')
235
+ }
236
+
237
+ // Sections 4 and 5: send, and report only the network's answer.
238
+ const sent = await wallet.adapter.send(built)
239
+ await settle({ network: wallet.kind === 'test' ? 'dry-run' : sent })
240
+ if (sent === 'refused') {
241
+ if (announced === 'admitted') await index.retract(built.txid, 'the network refused the transaction after the index admitted it')
242
+ await abandon('network-refused', `the network refused ${short(built.txid)}; the state never existed and nothing was spent`)
243
+ }
244
+ if (sent === 'unanswered') throw new WriteRefused('network-unanswered', `the wallet has not yet reported the network's answer for ${short(built.txid)}; do not rebuild, the worker will continue from the journal`)
245
+ await store.recordSpend({ txid: built.txid, satoshis: Math.ceil(built.tx.toBinary().length / 10) + 1, at: instant() })
246
+
247
+ // Section 6: an announcement that could not be made is retried, never a reason to spend again.
248
+ if (announced === 'unreachable') {
249
+ announced = await index.announce(built.beef)
250
+ await settle({ index: announced, refusal: index.lastRefusal })
251
+ }
252
+
253
+ record.holder = { party: controller.name, controllerKey }
254
+ if (op === 'RETIRE') record.status = 'retired'
255
+ if (args.acceptance != null) record.acceptanceRecords.push(args.acceptance)
256
+ await store.savePassport(record)
257
+ this.log(`${op} ${short(built.txid)} written: index ${entry.index}, network ${entry.network}`)
258
+ return { entry, state, record }
259
+ }
260
+
261
+ /**
262
+ * A write interrupted between the announcement and the network's answer,
263
+ * for example by a crash, leaves an entry with network 'pending'. Only the
264
+ * operator knows what happened: 'sent' keeps it and carries on; 'abandoned'
265
+ * withdraws it from the index, aborts it in the wallet and removes it, so
266
+ * the next state builds on the previous tip. Never rebuild a state that
267
+ * was sent.
268
+ */
269
+ async resolveInterrupted(record: PassportRecord, txid: string, outcome: 'sent' | 'abandoned'): Promise<PassportRecord> {
270
+ const at = record.states.findIndex((s) => s.txid === txid)
271
+ const entry = record.states[at]
272
+ if (entry == null) throw new WriteRefused('unknown-state', `${short(txid)} is not in the journal of ${record.passportId}`)
273
+ if (entry.network !== 'pending') throw new WriteRefused('not-interrupted', `${short(txid)} is ${entry.network}, not interrupted`)
274
+ if (at !== record.states.length - 1) throw new WriteRefused('not-the-tip', `${short(txid)} is not the newest state`)
275
+ if (outcome === 'sent') {
276
+ entry.network = 'accepted'
277
+ await this.options.store.savePassport(record)
278
+ return record
279
+ }
280
+ if (entry.index === 'admitted') await this.options.index.retract(txid, 'the write was interrupted before the network answered')
281
+ await this.options.wallet.adapter.discard({ tx: Transaction.fromHex(entry.rawTx), txid, beef: Utils.toArray(entry.beef, 'base64') as number[] })
282
+ record.states.pop()
283
+ if (record.states.length === 0) await this.options.store.deletePassport(record.passportId)
284
+ else {
285
+ // The actor of the abandoned state was the holder when it was built; control returns to the previous tip's key.
286
+ const previous = record.states.at(-1)!
287
+ record.holder = { party: entry.actor, controllerKey: previous.controllerKey }
288
+ record.status = 'active'
289
+ await this.options.store.savePassport(record)
290
+ }
291
+ return record
292
+ }
293
+
294
+ /** Section 7: the wallet's proof, pushed to the index and kept with the bytes. Returns whether a proof is now held. */
295
+ async prove(record: PassportRecord, txid: string): Promise<boolean> {
296
+ const entry = record.states.find((s) => s.txid === txid)
297
+ if (entry == null) throw new WriteRefused('unknown-state', `${short(txid)} is not in the journal of ${record.passportId}`)
298
+ if (entry.proof == null) {
299
+ const path = await this.options.wallet.adapter.merklePathFor(txid)
300
+ if (path == null) return false
301
+ entry.proof = { merklePath: path.toHex(), blockHeight: path.blockHeight }
302
+ const tx = Transaction.fromHex(entry.rawTx)
303
+ tx.merklePath = path
304
+ entry.beef = Utils.toBase64(tx.toAtomicBEEF())
305
+ await this.options.store.savePassport(record)
306
+ }
307
+ if (entry.proofPushed !== true) {
308
+ const pushed = await this.options.index.pushProof(txid, MerklePath.fromHex(entry.proof.merklePath))
309
+ entry.proofPushed = pushed.ok
310
+ await this.options.store.savePassport(record)
311
+ this.log(`proof for ${short(txid)} ${pushed.ok ? 'reached the index' : `not taken by the index: ${pushed.detail}`}`)
312
+ }
313
+ return true
314
+ }
315
+
316
+ /** The first state: the brand opens the passport under its own controller key. */
317
+ async issue(args: { brandId: string; brand: Party; passportId: string; profile: ProfileId; payload: Record<string, unknown>; ownerFields: Record<string, unknown> }): Promise<WriteOutcome> {
318
+ const problems = identifierProblems(args.passportId, this.options.identifiers)
319
+ if (problems.length > 0) throw new WriteRefused('identifier-refused', `${args.passportId} cannot be written because ${problems.join('; and ')}`)
320
+ const existing = await this.options.store.getPassport(args.passportId)
321
+ if (existing != null && existing.states.length > 0) throw new WriteRefused('already-issued', `${args.passportId} is already in the journal`)
322
+ const held = await this.options.index.lineage(args.passportId).catch(() => [])
323
+ if (held.length > 0) throw new WriteRefused('already-on-index', `the index already holds ${held.length} state(s) for ${args.passportId}; use a serial that is not in use`)
324
+ const record: PassportRecord = {
325
+ passportId: args.passportId,
326
+ brandId: args.brandId,
327
+ profile: args.profile,
328
+ createdAt: instant(),
329
+ status: 'active',
330
+ holder: { party: args.brand.name, controllerKey: await args.brand.controllerKey(args.passportId) },
331
+ states: [],
332
+ acceptanceRecords: [],
333
+ }
334
+ return await this.writeState({ record, op: 'ISSUE', actor: args.brand, controller: args.brand, profile: args.profile, payload: args.payload, ownerFields: args.ownerFields })
335
+ }
336
+
337
+ /** A later state that changes the data, by the party that controls the passport. */
338
+ async update(args: { record: PassportRecord; actor: Party; payload: Record<string, unknown>; ownerFields?: Record<string, unknown>; eventData?: Record<string, unknown> }): Promise<WriteOutcome> {
339
+ return await this.writeState({ record: args.record, op: 'UPDATE', actor: args.actor, controller: args.actor, profile: args.record.profile as ProfileId, payload: args.payload, ownerFields: args.ownerFields, eventData: args.eventData })
340
+ }
341
+
342
+ /** The hand-on: the holder acts, control moves to the recipient's key, field 15 commits to the custodian-signed acceptance record, and the payload and owner tier travel unchanged. */
343
+ async transfer(args: { record: PassportRecord; holder: Party; recipient: Party; acceptance: ManagedAcceptanceRecord; eventData?: Record<string, unknown> }): Promise<WriteOutcome> {
344
+ return await this.writeState({ record: args.record, op: 'TRANSFER', actor: args.holder, controller: args.recipient, profile: args.record.profile as ProfileId, eventData: args.eventData, acceptance: args.acceptance })
345
+ }
346
+
347
+ /** The end of the lineage; nothing may follow it. The payload and owner tier do not change on RETIRE (record model version 2, rule 8). */
348
+ async retire(args: { record: PassportRecord; actor: Party; reason: string }): Promise<WriteOutcome> {
349
+ return await this.writeState({ record: args.record, op: 'RETIRE', actor: args.actor, controller: args.actor, profile: args.record.profile as ProfileId, eventData: { reason: args.reason } })
350
+ }
351
+ }
@@ -0,0 +1,15 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { loadConfig } from '../src/config.js'
3
+
4
+ const rootKey = '11'.repeat(32)
5
+
6
+ describe('configuration', () => {
7
+ it('runs without an index in development', () => {
8
+ expect(loadConfig({ LIVE_PUBLISHING: 'false' }).index.url).toBeUndefined()
9
+ })
10
+
11
+ it('refuses to write to the chain without an index that persists', () => {
12
+ expect(() => loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey })).toThrow(/INDEX_URL/)
13
+ expect(loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey, INDEX_URL: 'http://index.example:8080/' }).index.url).toBe('http://index.example:8080')
14
+ })
15
+ })
@@ -0,0 +1,31 @@
1
+ import { createServer } from 'node:http'
2
+ import { once } from 'node:events'
3
+ import type { AddressInfo } from 'node:net'
4
+ import { expect, it } from 'vitest'
5
+ import { loadConfig } from '../src/config.js'
6
+ import { openPlatform } from '../src/platform.js'
7
+
8
+ it('uses the configured index and reports its failure without falling back to a development index', async () => {
9
+ let healthy = true
10
+ const requests: string[] = []
11
+ const server = createServer((request, response) => {
12
+ requests.push(request.url ?? '')
13
+ response.writeHead(healthy ? 200 : 503, { 'Content-Type': 'application/json' })
14
+ response.end(JSON.stringify({ publisherPolicy: { publisherKeys: ['configured-provider'] } }))
15
+ })
16
+ server.listen(0, '127.0.0.1')
17
+ await once(server, 'listening')
18
+ const url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
19
+ const platform = await openPlatform({ config: loadConfig({ INDEX_URL: url, LIVE_PUBLISHING: 'false' }), mode: 'test', log: () => {} })
20
+ try {
21
+ expect(platform.index.url).toBe(url)
22
+ expect(await platform.index.publisherKeys()).toEqual(['configured-provider'])
23
+ healthy = false
24
+ await expect(platform.index.publisherKeys()).rejects.toThrow('HTTP 503')
25
+ expect(platform.index.url).toBe(url)
26
+ expect(requests).toEqual(['/capabilities', '/capabilities'])
27
+ } finally {
28
+ await platform.close()
29
+ await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()))
30
+ }
31
+ })
@@ -0,0 +1,136 @@
1
+ // The first run: a whole passport lifecycle with no wallet, no funds, no
2
+ // Docker and no network. A test wallet with fixed keys stands in for the
3
+ // platform wallet, the index runs in this process with in-memory storage and
4
+ // its header checks off, and the records live in memory. Everything else is
5
+ // the code the live platform runs: the writer's six steps, the index's real
6
+ // admission rules, managed custody, claims, and the reader's report.
7
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
8
+ import { verifyLifecycleClaim } from '@bsv/dpp-protocol'
9
+ import { loadConfig } from '../src/config.js'
10
+ import { mintPassportId } from '../src/identifiers.js'
11
+ import { openPlatform, type Platform } from '../src/platform.js'
12
+ import { samplePayload } from '../src/profiles.js'
13
+ import type { PassportRecord } from '../src/store.js'
14
+ import { pendingDuties, runDuties } from '../src/worker.js'
15
+ import { WriteRefused } from '../src/writer.js'
16
+
17
+ const config = loadConfig({ NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' })
18
+ let platform: Platform
19
+ const brandId = 'brand-test-1'
20
+ const profile = 'general@2' as const
21
+ let passportId: string
22
+ let payload: Record<string, unknown>
23
+
24
+ beforeAll(async () => {
25
+ platform = await openPlatform({ config, mode: 'test', log: () => {} })
26
+ passportId = mintPassportId({ host: config.passportHost, prefix: config.gs1Prefix }, '100000001', `TEST-${Date.now().toString(36).toUpperCase()}`)
27
+ payload = samplePayload(profile, true)
28
+ })
29
+
30
+ afterAll(async () => {
31
+ await platform.close()
32
+ })
33
+
34
+ const latest = async (): Promise<PassportRecord> => {
35
+ const record = await platform.store.getPassport(passportId)
36
+ if (record == null) throw new Error('the passport is not in the journal')
37
+ return record
38
+ }
39
+
40
+ describe('a passport lifecycle under managed custody', () => {
41
+ it('names the platform wallet as a publisher on the index', async () => {
42
+ const keys = await platform.index.publisherKeys()
43
+ expect(keys).toContain(platform.wallet.identityKey)
44
+ })
45
+
46
+ it('refuses an identifier outside the configured prefix and host', async () => {
47
+ const brand = platform.parties.brand(brandId)
48
+ await expect(
49
+ platform.writer.issue({ brandId, brand, passportId: 'https://id.gs1.org/01/09506000134352/21/7AC18477503A', profile, payload, ownerFields: {} })
50
+ ).rejects.toBeInstanceOf(WriteRefused)
51
+ })
52
+
53
+ it('refuses a payload the profile schema rejects', async () => {
54
+ const brand = platform.parties.brand(brandId)
55
+ await expect(platform.writer.issue({ brandId, brand, passportId, profile, payload: { nonsense: true }, ownerFields: {} })).rejects.toMatchObject({ code: 'payload-invalid' })
56
+ expect(await platform.store.getPassport(passportId)).toBeUndefined()
57
+ })
58
+
59
+ it('issues the passport: the genesis is admitted by the index', async () => {
60
+ const brand = platform.parties.brand(brandId)
61
+ const outcome = await platform.writer.issue({ brandId, brand, passportId, profile, payload, ownerFields: { serviceNotes: 'first revision' } })
62
+ expect(outcome.entry.op).toBe('ISSUE')
63
+ expect(outcome.entry.index).toBe('admitted')
64
+ expect(outcome.record.holder.party).toBe(brand.name)
65
+ const held = await platform.index.lineage(passportId)
66
+ expect(held.map((tx) => tx.id('hex'))).toEqual([outcome.entry.txid])
67
+ })
68
+
69
+ it('updates the passport, proving control by linkage', async () => {
70
+ const brand = platform.parties.brand(brandId)
71
+ const revised = { ...payload, careNote: 'revised by the UPDATE' }
72
+ const outcome = await platform.writer.update({ record: await latest(), actor: brand, payload: revised, ownerFields: { serviceNotes: 'second revision' } })
73
+ expect(outcome.entry.op).toBe('UPDATE')
74
+ expect(outcome.entry.index).toBe('admitted')
75
+ expect(outcome.state.controlLinkage).toHaveLength(64)
76
+ })
77
+
78
+ it('refuses an update by a party that does not control the passport', async () => {
79
+ const stranger = platform.parties.member('someone-else')
80
+ await expect(platform.writer.update({ record: await latest(), actor: stranger, payload, ownerFields: {} })).rejects.toMatchObject({ code: 'not-the-controller' })
81
+ })
82
+
83
+ it('runs the unattended duties: proofs are fetched and pushed to the index', async () => {
84
+ expect((await pendingDuties(platform.store)).map((d) => d.duty)).toEqual(['prove', 'prove'])
85
+ await runDuties({ store: platform.store, index: platform.index, writer: platform.writer })
86
+ const record = await latest()
87
+ expect(record.states.every((s) => s.proof != null && s.proofPushed === true)).toBe(true)
88
+ expect(await pendingDuties(platform.store)).toEqual([])
89
+ })
90
+
91
+ it('hands the passport on: offer, acceptance by claim code, and a TRANSFER that commits to the record', async () => {
92
+ const brand = platform.parties.brand(brandId)
93
+ const { offer, claimCode } = await platform.custody.offer({ record: await latest(), holder: brand, terms: { word: 'Passed on', note: 'Handed to the distributor' } })
94
+ expect(offer.status).toBe('open')
95
+ expect(claimCode).toMatch(/^[0-9a-f]{16}$/)
96
+ await expect(platform.custody.accept({ requestId: offer.requestId, claimCode: 'wrong' })).rejects.toMatchObject({ code: 'claim-code-wrong' })
97
+ const accepted = await platform.custody.accept({ requestId: offer.requestId, claimCode })
98
+ expect(accepted.offer.status).toBe('transferred')
99
+ expect(accepted.record.custodian).toBe(platform.wallet.identityKey)
100
+ const record = await latest()
101
+ expect(record.states.at(-1)?.op).toBe('TRANSFER')
102
+ expect(record.holder.party).toBe(`recipient:${offer.requestId}`)
103
+ expect(record.acceptanceRecords).toHaveLength(1)
104
+ })
105
+
106
+ it('reads the passport back as a stranger would, with the acceptance record supplied', async () => {
107
+ const reading = await platform.read(passportId)
108
+ expect(reading.lineage.map((s) => s.op)).toEqual(['ISSUE', 'UPDATE', 'TRANSFER'])
109
+ const status = (name: string): string | undefined => reading.checks.find((c) => c.name === name)?.status
110
+ expect(status('recordEncoding')).toBe('pass')
111
+ expect(status('actorSignatures')).toBe('pass')
112
+ expect(status('publisherSignatures')).toBe('pass')
113
+ expect(status('linkage')).toBe('pass')
114
+ expect(status('evidenceAvailability')).toBe('pass')
115
+ expect(status('issuerAuthority')).toBe('pass')
116
+ // Nothing here is mined and no header source was asked.
117
+ expect(status('inclusion')).toBe('unknown')
118
+ })
119
+
120
+ it('lets the recipient retire the passport, and nothing follows', async () => {
121
+ const record = await latest()
122
+ const recipient = platform.custody.holderOf(record)
123
+ const outcome = await platform.writer.retire({ record, actor: recipient, reason: 'recycled' })
124
+ expect(outcome.entry.op).toBe('RETIRE')
125
+ expect(outcome.record.status).toBe('retired')
126
+ await expect(platform.writer.update({ record: await latest(), actor: recipient, payload, ownerFields: {} })).rejects.toMatchObject({ code: 'retired' })
127
+ })
128
+
129
+ it('signs a lifecycle claim on the other rail, by the recycler, without touching the passport', async () => {
130
+ const recycler = platform.parties.member('recycler-line-3')
131
+ const claim = await platform.claims.sign({ passport: await latest(), issuer: recycler, eventType: 'Disposition' })
132
+ expect(verifyLifecycleClaim(claim.claim).signature).toBe('verified')
133
+ expect(claim.claim.issuer).toBe(recycler.did)
134
+ expect((await platform.store.listClaims({ passportId })).length).toBe(1)
135
+ })
136
+ })
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src",
6
+ "types": ["node"]
7
+ },
8
+ "include": ["src"]
9
+ }
@@ -0,0 +1,9 @@
1
+ import { defineConfig } from 'vitest/config'
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ include: ['test/**/*.test.ts'],
6
+ testTimeout: 60_000,
7
+ hookTimeout: 60_000,
8
+ },
9
+ })