@bsv/create-dpp-app 0.1.0-beta.1 → 0.1.0-beta.2

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 (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -1,17 +1,16 @@
1
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.
2
+ // order. Check the signed draft before spending. Announce it before sending
3
+ // to a retraction-capable index, or after sending to another index. Report
4
+ // the wallet's answer and retain the transaction, its BEEF and its proof.
5
5
  // The journal entry is written before each step is acted on, so a retry
6
6
  // continues an operation and never builds a second transaction.
7
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.
8
+ // The platform funds and publishes managed writes. Each new output locks
9
+ // to its controller's field-6 key. Its holder signs the next spend.
12
10
  import { MerklePath, Transaction, Utils, type WalletProtocol } from '@bsv/sdk'
13
11
  import {
14
12
  acceptanceCommitment,
13
+ bindAcceptanceToState,
15
14
  buildLockingScript,
16
15
  completeState,
17
16
  findDppOutputs,
@@ -23,31 +22,59 @@ import {
23
22
  type DppStateV2,
24
23
  type ManagedAcceptanceRecord,
25
24
  } from '@bsv/dpp-protocol'
26
- import type { ProfileId } from '@bsv/dpp-profiles'
27
- import { identifierProblems, type IdentifierPolicy } from './identifiers.js'
25
+ import { PROFILE_RETIRED, RETIRED_PROFILE_REPLACEMENTS, describeRetiredProfile, isRetiredProfile, type BindingProfile, type BindingValidationDetail, type PayloadValidation } from '@bsv/dpp-profiles'
26
+ import type { BoundProfiles, ViewCheck } from './bound-profiles.js'
27
+ import { identifierProblems, isDemonstrationPolicy, type IdentifierPolicy } from './identifiers.js'
28
28
  import type { IndexClient } from './index-client.js'
29
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'
30
+ import { DEMONSTRATION_NOTICE, isProfileId, sectorIssueSuccessor, validatePayload, type ManifestProfileId } from './profiles.js'
31
+ import { isInterrupted, type PassportRecord, type StateEntry, type Store } from './store.js'
32
+ import { ActionAlreadySeen, type PlatformWallet, type Tip } from './wallet.js'
33
33
 
34
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']
35
+ export const OWNER_DATA_PROTOCOL: WalletProtocol = [2, 'dpp owner data v1']
36
36
 
37
37
  export class WriteRefused extends Error {
38
38
  constructor(
39
39
  readonly code: string,
40
- detail: string
40
+ detail: string,
41
+ /** What the API adds to its answer beside the code and the sentence: for a product document that was refused, the validation with its findings. It goes to the caller that sent the document and is never logged. */
42
+ readonly data?: Record<string, unknown>
41
43
  ) {
42
44
  super(detail)
43
45
  }
44
46
  }
45
47
 
48
+ /**
49
+ * Refuse a write under a retired profile, by the one code every such
50
+ * refusal carries. It covers a new payload and equally a state that would
51
+ * carry an old payload forward, since that state would declare the retired
52
+ * profile too. Called before anything is derived, signed or asked of the
53
+ * index.
54
+ */
55
+ export function refuseRetiredProfile(profile: string): void {
56
+ if (isRetiredProfile(profile)) throw new WriteRefused(PROFILE_RETIRED, `${describeRetiredProfile(profile)} Nothing was signed.`, { replacedBy: RETIRED_PROFILE_REPLACEMENTS[profile] })
57
+ }
58
+
59
+ export function requireIssuableProfile(profile: string): void {
60
+ if (isRetiredProfile(profile)) {
61
+ const historical = RETIRED_PROFILE_REPLACEMENTS[profile]
62
+ const replacedBy = sectorIssueSuccessor(historical) ?? historical
63
+ throw new WriteRefused(PROFILE_RETIRED, `${describeRetiredProfile(profile)} Use ${replacedBy} for new issuance. Nothing was signed.`, { replacedBy })
64
+ }
65
+ const replacedBy = sectorIssueSuccessor(profile)
66
+ if (replacedBy != null) throw new WriteRefused('profile-superseded', `Use ${replacedBy} to issue a new passport. Existing ${profile} passports keep their original binding.`, { replacedBy })
67
+ }
68
+
69
+ type SealedTier = { hash: string; ciphertext: number[]; senderIdentityKey?: string }
70
+
46
71
  export interface WriterOptions {
47
72
  store: Store
48
73
  wallet: PlatformWallet
49
74
  index: IndexClient
50
75
  identifiers: IdentifierPolicy
76
+ /** The profiles held by a binding, with the validation engine. */
77
+ bound: BoundProfiles
51
78
  /** Whether writes may reach the chain. False builds, checks and journals a state and then stops before the send. */
52
79
  livePublishing: boolean
53
80
  spendCapSatoshis: number
@@ -60,8 +87,19 @@ export interface WriteOutcome {
60
87
  record: PassportRecord
61
88
  }
62
89
 
90
+ /** The precise cause a binding validation names, or a word for an answer that names none. */
91
+ const causeOf = (validation: PayloadValidation): string =>
92
+ typeof validation.detail === 'object' && validation.detail != null && !Array.isArray(validation.detail) ? ((validation.detail as BindingValidationDetail).cause ?? validation.status) : validation.status
93
+
63
94
  const instant = (): string => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
64
95
  const short = (hex: string): string => `${hex.slice(0, 12)}...`
96
+ const mayHoldDraft = (index: StateEntry['index']): boolean => index === 'admitted' || index === 'duplicate' || index === 'pending' || index === 'unreachable'
97
+
98
+ function journalTip(record: PassportRecord | undefined, txid: string): StateEntry {
99
+ const tip = record?.states.at(-1)
100
+ if (tip?.txid !== txid) throw new WriteRefused('tip-moved', 'the journal tip changed before this operation could finish')
101
+ return tip
102
+ }
65
103
 
66
104
  export class Writer {
67
105
  private readonly log: (line: string) => void
@@ -70,9 +108,18 @@ export class Writer {
70
108
  this.log = options.log ?? (() => {})
71
109
  }
72
110
 
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)
111
+ private async spendableTip(tip: Tip, record: PassportRecord, actor: Party) {
112
+ const output = findDppOutputs(tip.tx).find(ref => ref.outputIndex === tip.outputIndex)
113
+ if (output?.state.ownerIdentityKey !== record.holder.controllerKey) {
114
+ throw new WriteRefused('tip-controller-mismatch', 'the signed predecessor and journal name different controllers')
115
+ }
116
+ const lock = output.lockingPublicKey.toString()
117
+ if (lock === record.holder.controllerKey) return { ...tip, signer: actor.wallet }
118
+ // Older starter outputs used the funding wallet's per-passport lock. Spend the original
119
+ // outpoint with that wallet once, then place the successor under its signed controller.
120
+ const publisher = this.options.wallet.publisher
121
+ if (lock === await ownerKeyFor(record.passportId, publisher)) return { ...tip, signer: publisher }
122
+ throw new WriteRefused('tip-lock-unavailable', 'the predecessor is locked to a key this writer cannot spend')
76
123
  }
77
124
 
78
125
  /** The tip from the journal's BEEF, which carries its ancestry and, once proven, its merkle path. */
@@ -83,9 +130,20 @@ export class Writer {
83
130
  return { tx: Transaction.fromAtomicBEEF(beef), txid: last.txid, outputIndex: last.outputIndex, beef }
84
131
  }
85
132
 
86
- private async sealOwnerTier(controller: Party, passportId: string, profile: ProfileId, fields: Record<string, unknown>): Promise<{ hash: string; ciphertext: number[] }> {
133
+ /** The owner tier of a manifest profile: checked against the profile's restricted schema, then sealed. */
134
+ private async sealOwnerTier(controller: Party, passportId: string, profile: ManifestProfileId, fields: Record<string, unknown>): Promise<{ hash: string; ciphertext: number[] }> {
87
135
  const check = validatePayload(profile, 'restricted', fields)
88
136
  if (!check.valid) throw new WriteRefused('owner-tier-invalid', `the owner tier is refused by the restricted schema of ${profile}: ${check.problems.join('; ')}`)
137
+ return await this.seal(controller, passportId, fields)
138
+ }
139
+
140
+ /**
141
+ * One owner tier, sealed: encrypted to the controller's own key for this
142
+ * passport and committed to by the hash of the ciphertext, which is what
143
+ * field 11 carries (spec/record-model.md section 7). Every profile's
144
+ * restricted data goes through here, whatever checked it first.
145
+ */
146
+ private async seal(controller: Party, passportId: string, fields: Record<string, unknown>): Promise<{ hash: string; ciphertext: number[] }> {
89
147
  const plaintext = Utils.toArray(JSON.stringify(fields), 'utf8') as number[]
90
148
  const { ciphertext } = await controller.wallet.encrypt({ plaintext, protocolID: OWNER_DATA_PROTOCOL, keyID: passportId, counterparty: 'self' })
91
149
  const hash = ownerBlobHash(ciphertext)
@@ -93,6 +151,30 @@ export class Writer {
93
151
  return { hash, ciphertext }
94
152
  }
95
153
 
154
+ /** Resolve carried bytes against the selected predecessor output, including a historical state with no owner commitment. */
155
+ private carriedTier(passportId: string, tip: Tip, entry: StateEntry): SealedTier | undefined {
156
+ const previous = findDppOutputs(tip.tx).find((output) => output.outputIndex === tip.outputIndex)?.state
157
+ if (tip.tx.id('hex') !== tip.txid || previous?.passportId !== passportId) throw new WriteRefused('owner-tier-unsound', 'the retained predecessor differs from the selected passport tip')
158
+ const tier = entry.ownerTier
159
+ if (tier == null && previous.payloadOwnerHash === '') return undefined
160
+ const ciphertext = tier == null ? undefined : Utils.toArray(tier.ciphertext, 'base64')
161
+ if (tier == null || ciphertext == null || tier.hash !== previous.payloadOwnerHash || !verifyOwnerBlob(ciphertext, previous.payloadOwnerHash)) {
162
+ throw new WriteRefused('owner-tier-unsound', 'the retained owner tier does not match the signed predecessor commitment')
163
+ }
164
+ return { ...tier, ciphertext }
165
+ }
166
+
167
+ private async transferTier(passportId: string, tier: SealedTier, giver: Party, recipient: Party): Promise<SealedTier> {
168
+ const key = { protocolID: OWNER_DATA_PROTOCOL, keyID: passportId }
169
+ try {
170
+ const { plaintext } = await giver.wallet.decrypt({ ...key, ciphertext: tier.ciphertext, counterparty: tier.senderIdentityKey ?? 'self' })
171
+ const { ciphertext } = await giver.wallet.encrypt({ ...key, plaintext, counterparty: recipient.identityKey })
172
+ return { hash: ownerBlobHash(ciphertext), ciphertext, senderIdentityKey: giver.identityKey }
173
+ } catch {
174
+ throw new WriteRefused('owner-tier-unavailable', 'the holder could not open and re-encrypt the committed owner tier for this recipient')
175
+ }
176
+ }
177
+
96
178
  private async withinSpendCap(): Promise<void> {
97
179
  const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString()
98
180
  const spent = await this.options.store.spentSince(dayAgo)
@@ -109,42 +191,70 @@ export class Writer {
109
191
  op: StateEntry['op']
110
192
  actor: Party
111
193
  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. */
194
+ profile: string
195
+ /** A new public payload and owner tier; RETIRE carries the tip's bytes unchanged. TRANSFER re-encrypts the restricted part to the new holder. */
114
196
  payload?: Record<string, unknown>
115
197
  ownerFields?: Record<string, unknown>
198
+ /** Under a profile held by a binding: the complete product document, in place of `payload` and `ownerFields`. */
199
+ product?: Record<string, unknown>
116
200
  eventData?: Record<string, unknown>
117
201
  acceptance?: ManagedAcceptanceRecord
118
202
  }): Promise<WriteOutcome> {
119
- const { record, op, actor, controller, profile } = args
203
+ const { op, actor, controller, profile } = args
120
204
  const { store, wallet, index } = this.options
121
- const passportId = record.passportId
205
+ const passportId = args.record.passportId
206
+ // The caller may have read the passport before another request advanced it.
207
+ const latest = await store.getPassport(passportId)
208
+ const record = latest ?? args.record
209
+ const unresolved = latest?.states.find(isInterrupted)
210
+ if (unresolved != null) throw new WriteRefused('operation-interrupted', `resolve ${short(unresolved.txid)} before writing another state`)
211
+ if (op !== 'ISSUE' && latest?.states.at(-1)?.txid !== args.record.states.at(-1)?.txid) throw new WriteRefused('tip-moved', 'the requested predecessor is no longer the journal tip')
212
+ // Every operation, RETIRE included: each would sign a state whose payload declares the retired profile.
213
+ refuseRetiredProfile(profile)
122
214
  const tip = this.tipOf(record)
123
215
  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
216
  if (op !== 'ISSUE' && tip == null) throw new WriteRefused('not-issued', `${passportId} has no genesis to follow`)
125
217
  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
218
  const tipEntry = record.states.at(-1)
130
219
  let payloadPublic: string
131
- let sealed: { hash: string; ciphertext: number[] }
132
- if (args.payload != null) {
133
- const publicCheck = validatePayload(profile, 'public', args.payload)
220
+ let sealed: SealedTier | undefined
221
+ const bound = this.options.bound.get(profile)
222
+ const writesData = args.payload != null || args.product != null
223
+ if (writesData && bound == null && !isProfileId(profile)) throw new WriteRefused('profile-unknown', `${profile} is not a profile this platform holds: it is neither a published industry profile nor a binding registered at start-up`)
224
+ if (writesData && bound != null) {
225
+ if (args.product == null || args.payload != null || args.ownerFields != null) {
226
+ throw new WriteRefused('product-required', `${profile} is held by a binding: send the complete product document as product, and neither payload nor ownerFields. The API splits it into its public and restricted parts.`)
227
+ }
228
+ // The identifier the document is checked against is this state's own, the one written into field 3 and signed below.
229
+ const prepared = await this.prepareBound(bound, args.product, passportId)
230
+ payloadPublic = prepared.payloadPublic
231
+ sealed = await this.seal(controller, passportId, prepared.restrictedProduct ?? {})
232
+ } else if (args.payload != null) {
233
+ if (args.product != null) throw new WriteRefused('payload-required', `${profile} is a manifest profile: send payload and ownerFields, not product`)
234
+ if (!isProfileId(profile)) throw new WriteRefused('profile-unknown', `${profile} is not a profile this platform holds`)
235
+ const demo = isDemonstrationPolicy(this.options.identifiers)
236
+ if (!demo && Object.hasOwn(args.payload, 'notice')) throw new WriteRefused('demonstration-notice-unexpected', 'A real-product record cannot carry a demonstration notice.')
237
+ const { notice = DEMONSTRATION_NOTICE, ...fields } = args.payload
238
+ const payload = demo ? { notice, ...fields } : args.payload
239
+ const publicCheck = validatePayload(profile, 'public', payload)
134
240
  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)
241
+ payloadPublic = JSON.stringify(payload)
136
242
  // A new payload with no owner fields carries the tip's sealed tier unchanged, when the actor still controls it.
137
243
  sealed =
138
- args.ownerFields == null && tipEntry?.ownerTier != null
139
- ? { hash: tipEntry.ownerTier.hash, ciphertext: Utils.toArray(tipEntry.ownerTier.ciphertext, 'base64') as number[] }
244
+ args.ownerFields == null && tip != null && tipEntry != null
245
+ ? this.carriedTier(passportId, tip, tipEntry)
140
246
  : await this.sealOwnerTier(controller, passportId, profile, args.ownerFields ?? {})
247
+ } else if (args.product != null) {
248
+ throw new WriteRefused('payload-required', `${profile} is a manifest profile: send payload and ownerFields, not product`)
141
249
  } 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`)
250
+ if (tip == null || tipEntry == null) throw new WriteRefused('nothing-to-carry', `${passportId} has no tip whose payload this ${op} could carry`)
143
251
  payloadPublic = tipEntry.payloadPublic
144
- sealed = { hash: tipEntry.ownerTier.hash, ciphertext: Utils.toArray(tipEntry.ownerTier.ciphertext, 'base64') as number[] }
252
+ sealed = this.carriedTier(passportId, tip, tipEntry)
145
253
  }
146
254
  await this.withinSpendCap()
147
255
 
256
+ if (op === 'TRANSFER' && sealed != null) sealed = await this.transferTier(passportId, sealed, actor, controller)
257
+
148
258
  const previousController = tip == null ? undefined : record.holder.controllerKey
149
259
  const controllerKey = await controller.controllerKey(passportId)
150
260
  const data: DppStateDataV2 = {
@@ -157,7 +267,7 @@ export class Writer {
157
267
  actorKeyId: actor.name,
158
268
  eventData: args.eventData == null ? '' : JSON.stringify(args.eventData),
159
269
  payloadPublic,
160
- payloadOwnerHash: sealed.hash,
270
+ payloadOwnerHash: sealed?.hash ?? '',
161
271
  previousTxid: tip == null ? '' : tip.txid,
162
272
  previousOutputIndex: tip == null ? null : tip.outputIndex,
163
273
  lineageGenesis: tip == null ? null : { txid: record.states[0].txid, outputIndex: record.states[0].outputIndex },
@@ -166,15 +276,22 @@ export class Writer {
166
276
  authorisationCommitment: args.acceptance == null ? '' : acceptanceCommitment(args.acceptance),
167
277
  }
168
278
  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}`)
279
+ // The holder itself under another key is a deployment that does not hold the secret its keys are derived from, such as one restored without it.
280
+ throw new WriteRefused(
281
+ 'not-the-controller',
282
+ actor.name === record.holder.party
283
+ ? `${passportId} is controlled by ${record.holder.party} under the key ${previousController}, and the key this deployment derives for ${actor.name} is another one: it does not hold the secret the passport was written under (BRAND_ROOT_SECRET for a brand, MANAGED_IDENTITY_SECRET for a recipient). Nothing was signed.`
284
+ : `${actor.name} does not control ${passportId}; its controller key is held by ${record.holder.party}`
285
+ )
170
286
  }
287
+ const spend = tip && await this.spendableTip(tip, record, actor)
171
288
  const state = (await completeState(data, actor.wallet, wallet.publisher)) as DppStateV2
172
- const lockingScript = buildLockingScript(state, await this.lockKey(passportId))
289
+ const lockingScript = buildLockingScript(state, controllerKey)
173
290
 
174
291
  // Section 3: built unsent, complete and signed, spending nothing until it is sent.
175
292
  let built
176
293
  try {
177
- built = await wallet.adapter.build({ lockingScript, tip, passportId })
294
+ built = await wallet.adapter.build({ lockingScript, tip: spend, passportId })
178
295
  } catch (cause) {
179
296
  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
297
  }
@@ -189,132 +306,264 @@ export class Writer {
189
306
  actor: actor.name,
190
307
  controllerKey,
191
308
  payloadPublic: data.payloadPublic,
192
- ownerTier: { hash: sealed.hash, ciphertext: Utils.toBase64(sealed.ciphertext) },
193
- index: 'pending',
309
+ ...(sealed == null ? {} : { ownerTier: { ...sealed, ciphertext: Utils.toBase64(sealed.ciphertext) } }),
310
+ ...(index.supportsRetraction ? { draftIndexId: index.destinationId } : {}),
311
+ index: index.supportsRetraction ? 'pending' : 'not-asked',
194
312
  network: 'pending',
195
313
  }
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)
314
+ entry.nextHolder = { party: controller.name, controllerKey }
315
+ if (args.acceptance != null) entry.acceptance = args.acceptance
316
+ if (built.reference != null) entry.walletReference = built.reference
317
+ const settle = async (patch: Partial<StateEntry>) => {
318
+ const updated = await store.changePassport(passportId, (current) => {
319
+ const draft = journalTip(current, built.txid)
320
+ if (draft.network !== 'pending') throw new WriteRefused('operation-interrupted', 'the draft was already resolved')
321
+ Object.assign(draft, patch)
322
+ return current
323
+ })
324
+ return updated!
203
325
  }
204
- // A state that is not written leaves the journal as it was: the unsent action is aborted and the entry removed.
205
326
  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)
327
+ const current = await settle({ network: code === 'network-refused' ? 'refused' : 'not-sent' })
328
+ await this.removeDraft(current, built.txid, detail)
210
329
  throw new WriteRefused(code, detail)
211
330
  }
212
331
 
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)}`)
332
+ try {
333
+ // Verify against the selected predecessor before reserving an unsent draft.
334
+ const lineage = record.states.map((s) => Transaction.fromHex(s.rawTx))
335
+ const checked = await verifyChain([...lineage, built.tx], { chainTracker: 'scripts only', serverIdentityKey: wallet.identityKey, managedAcceptance: true })
336
+ if (!checked.valid) throw new WriteRefused('own-check-refused', `the writer's own check refuses the unsent ${op}: ${checked.error ?? 'no reason given'}`)
337
+ // Under a binding the reader's payload check runs here too, on the state as the unsent transaction carries it:
338
+ // the public payload and the passport identifier are read back from the signed bytes, never from what was prepared.
339
+ if (bound != null && writesData) {
340
+ const signed = findDppOutputs(built.tx)[0]?.state
341
+ const view = signed == null ? undefined : await this.options.bound.validatePublic({ profile: bound.id, profileVersion: bound.version, payloadPublic: signed.payloadPublic, passportId: signed.passportId })
342
+ const cause = view == null ? 'no state was decoded' : causeOf(view)
343
+ if (view == null || view.status === 'fail' || (view.status === 'unknown' && cause !== 'restricted-tier-withheld')) {
344
+ throw new WriteRefused('own-check-refused', `the writer's own check refuses the unsent ${op}: its public payload does not validate under ${profile} for the passport identifier it signs (${cause})`)
345
+ }
346
+ }
347
+
348
+ // Section 3: a state after the genesis spends the tip the index returns for the passport.
349
+ if (tip != null) {
350
+ const held = await index.lineage(passportId).catch(() => undefined)
351
+ const heldTip = held?.at(-1)?.id('hex')
352
+ if (held != null && heldTip !== tip.txid) {
353
+ throw new WriteRefused('tip-moved', `the index's tip for ${passportId} is ${heldTip == null ? 'nothing' : short(heldTip)}, not ${short(tip.txid)}`)
354
+ }
224
355
  }
356
+
357
+ if (args.acceptance != null && bindAcceptanceToState(args.acceptance, state).length !== 0) throw new WriteRefused('acceptance-mismatch', 'the signed acceptance does not bind to the proposed transfer')
358
+ await store.changePassport(passportId, (current) => {
359
+ if (op === 'ISSUE' && current?.states.length) throw new WriteRefused('already-issued', 'another write already reserved this passport')
360
+ const unresolved = current?.states.find(isInterrupted)
361
+ if (unresolved != null) throw new WriteRefused('operation-interrupted', `resolve ${short(unresolved.txid)} before writing another state`)
362
+ if (current?.states.at(-1)?.txid !== tip?.txid || current?.status === 'retired') throw new WriteRefused('tip-moved', 'the journal tip changed while the candidate was prepared')
363
+ const latest = current ?? { ...record, states: [], acceptanceRecords: [] }
364
+ latest.states.push(entry)
365
+ return latest
366
+ })
367
+ } catch (cause) {
368
+ // After a lost acknowledgement the journal can already hold this exact transaction.
369
+ // Discard only a draft that no persisted writer owns.
370
+ const held = await store.getPassport(passportId)
371
+ if (!held?.states.some((item) => item.txid === built.txid)) await wallet.adapter.discard(built)
372
+ throw cause
225
373
  }
374
+ this.log(`${op} ${short(built.txid)} built unsent for ${passportId}`)
226
375
 
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')
376
+ let announced = entry.index
377
+ if (index.supportsRetraction) {
378
+ announced = await index.announce(built.beef)
379
+ await settle({ index: announced, refusal: index.lastRefusal })
380
+ if (announced === 'refused') await abandon('index-refused', `the index refused ${short(built.txid)} while it was still a draft: ${index.lastRefusal ?? 'no reason given'}`)
381
+ if (announced === 'unauthorised') await abandon('index-unauthorised', 'the index wants a submit token, or a different one; nothing was sent')
382
+ }
232
383
 
233
384
  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.')
385
+ await abandon('live-publishing-off', 'LIVE_PUBLISHING is false: the unsent draft was aborted.')
235
386
  }
236
387
 
237
388
  // 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`)
389
+ const sent = await wallet.adapter.send(built).catch(() => 'unanswered' as const)
390
+ if (sent === 'refused') await abandon('network-refused', `the network refused ${short(built.txid)}`)
391
+ if (sent === 'unanswered') {
392
+ await settle({ network: 'unanswered' })
393
+ throw new WriteRefused('network-unanswered', `the network has not answered for ${short(built.txid)}; resolve the retained transaction before writing another state`)
243
394
  }
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 })
395
+ let updated = await this.finishDraft(passportId, entry, entry.nextHolder!, args.acceptance)
396
+ if (announced === 'not-asked' || announced === 'unreachable') {
397
+ announced = await index.announce(built.beef).catch(() => 'unreachable' as const)
398
+ updated = await this.recordAnnouncement(passportId, built.txid, announced, index.lastRefusal)
251
399
  }
400
+ const written = updated.states.find((item) => item.txid === built.txid)!
401
+ this.log(`${op} ${short(built.txid)} written: index ${written.index}, network ${written.network}`)
402
+ return { entry: written, state, record: updated }
403
+ }
252
404
 
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 }
405
+ private async finishDraft(id: string, entry: StateEntry, holder: PassportRecord['holder'], acceptance?: ManagedAcceptanceRecord): Promise<PassportRecord> {
406
+ const accepted = this.options.wallet.kind === 'test' ? 'dry-run' : 'accepted'
407
+ if (entry.network !== 'pending' && entry.network !== 'unanswered') throw new WriteRefused('not-interrupted', 'this draft cannot be marked sent')
408
+ if (holder.controllerKey !== entry.controllerKey) throw new WriteRefused('not-the-controller', 'the retained holder differs from the signed controller')
409
+ // Repeating this accounting after interruption is idempotent by transaction ID.
410
+ await this.options.store.recordSpend({ txid: entry.txid, satoshis: Math.ceil(entry.rawTx.length / 20) + 1, at: entry.timestamp })
411
+ const record = await this.options.store.changePassport(id, (current) => {
412
+ const draft = journalTip(current, entry.txid)
413
+ if (draft.network !== 'pending' && draft.network !== 'unanswered') throw new WriteRefused('not-interrupted', 'this draft cannot be marked sent')
414
+ draft.network = accepted
415
+ current!.holder = holder
416
+ if (draft.op === 'RETIRE') current!.status = 'retired'
417
+ if (acceptance != null && !current!.acceptanceRecords.some((item) => acceptanceCommitment(item) === acceptanceCommitment(acceptance))) current!.acceptanceRecords.push(acceptance)
418
+ delete draft.nextHolder
419
+ delete draft.acceptance
420
+ delete draft.walletReference
421
+ delete draft.draftIndexId
422
+ return current
423
+ })
424
+ return record!
259
425
  }
260
426
 
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
- */
427
+ private async removeDraft(record: PassportRecord, txid: string, reason: string): Promise<PassportRecord> {
428
+ const entry = journalTip(record, txid)
429
+ try {
430
+ await this.options.wallet.adapter.discard({ tx: Transaction.fromHex(entry.rawTx), txid, beef: Utils.toArray(entry.sentBeef ?? entry.beef, 'base64') as number[], reference: entry.walletReference })
431
+ } catch (cause) {
432
+ if (cause instanceof ActionAlreadySeen) {
433
+ await this.options.store.changePassport(record.passportId, (latest) => {
434
+ const draft = journalTip(latest, txid)
435
+ if (draft.network === 'not-sent' || draft.network === 'refused') draft.network = 'unanswered'
436
+ return latest
437
+ })
438
+ throw new WriteRefused('network-seen', 'the wallet reports that the transaction was seen; retain it and resolve the network outcome')
439
+ }
440
+ throw cause
441
+ }
442
+ if (mayHoldDraft(entry.index)) {
443
+ const withdrawn = await this.options.index.retract(txid, reason, entry.outputIndex)
444
+ if (!withdrawn.ok && !withdrawn.absent) throw new WriteRefused('retraction-pending', `the draft is retained until the index confirms withdrawal: ${withdrawn.detail}`)
445
+ }
446
+ const remaining = await this.options.store.changePassport(record.passportId, (current) => {
447
+ const draft = journalTip(current, txid)
448
+ if (draft.network !== 'refused' && draft.network !== 'not-sent') throw new WriteRefused('not-interrupted', 'the draft was already resolved')
449
+ current!.states.pop()
450
+ return current!.states.length === 0 ? undefined : current
451
+ })
452
+ return remaining ?? { ...record, states: [] }
453
+ }
454
+
455
+ /** Resolve the retained transaction once its fate is known. */
269
456
  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
457
+ const latest = await this.options.store.getPassport(record.passportId)
458
+ const entry = latest?.states.find((s) => s.txid === txid)
459
+ if (latest == null || entry == null) throw new WriteRefused('unknown-state', `${short(txid)} is not in the journal`)
460
+ if (!isInterrupted(entry)) throw new WriteRefused('not-interrupted', `${short(txid)} is ${entry.network}`)
461
+ if (latest.states.at(-1)?.txid !== txid) throw new WriteRefused('not-the-tip', `${short(txid)} is not the newest state`)
462
+ if (outcome === 'abandoned') {
463
+ if (mayHoldDraft(entry.index) && entry.draftIndexId != null && entry.draftIndexId !== this.options.index.destinationId) {
464
+ throw new WriteRefused('retraction-index-changed', 'reconnect the original index before withdrawing this draft')
465
+ }
466
+ const cancelling = await this.options.store.changePassport(record.passportId, (current) => {
467
+ const draft = journalTip(current, txid)
468
+ if (!isInterrupted(draft)) throw new WriteRefused('not-interrupted', 'the draft was already resolved')
469
+ if (draft.network !== 'refused') draft.network = 'not-sent'
470
+ return current
471
+ })
472
+ const reason = journalTip(cancelling, txid).network === 'refused'
473
+ ? `the network refused ${short(txid)}`
474
+ : 'the operator confirmed that the interrupted transaction was abandoned'
475
+ return this.removeDraft(cancelling!, txid, reason)
279
476
  }
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)
477
+ let acceptance = entry.acceptance
478
+ if (entry.op === 'TRANSFER') {
479
+ const state = findDppOutputs(Transaction.fromHex(entry.rawTx)).find((out) => out.outputIndex === entry.outputIndex)?.state
480
+ if (state?.version !== '2') throw new WriteRefused('acceptance-mismatch', 'the retained transfer cannot be decoded')
481
+ if (acceptance == null) {
482
+ const offers = await this.options.store.listOffers({ passportId: record.passportId })
483
+ acceptance = [...latest.acceptanceRecords, ...offers.flatMap((offer) => offer.record == null ? [] : [offer.record])].find((item) => acceptanceCommitment(item) === state.authorisationCommitment)
484
+ }
485
+ if (acceptance == null || bindAcceptanceToState(acceptance, state).length > 0) throw new WriteRefused('acceptance-mismatch', 'the signed acceptance for the interrupted transfer is unavailable or differs')
290
486
  }
291
- return record
487
+ const holder = entry.nextHolder ?? { party: acceptance == null ? entry.actor : `recipient:${acceptance.requestId}`, controllerKey: entry.controllerKey }
488
+ return this.finishDraft(record.passportId, entry, holder, acceptance)
489
+ }
490
+
491
+ async recordAnnouncement(id: string, txid: string, index: StateEntry['index'], refusal?: string): Promise<PassportRecord> {
492
+ const result = await this.options.store.changePassport(id, (current) => {
493
+ const state = current?.states.find((item) => item.txid === txid)
494
+ if (state == null) throw new WriteRefused('unknown-state', 'the announced transaction is absent from the journal')
495
+ if (state.index !== 'admitted' && state.index !== 'duplicate') Object.assign(state, { index, refusal })
496
+ return current
497
+ })
498
+ return result!
292
499
  }
293
500
 
294
- /** Section 7: the wallet's proof, pushed to the index and kept with the bytes. Returns whether a proof is now held. */
501
+ /** Keep the proof against the exact transaction for which it was obtained. */
295
502
  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}`)
503
+ const id = record.passportId
504
+ let entry = (await this.options.store.getPassport(id))?.states.find((s) => s.txid === txid)
505
+ if (entry == null) throw new WriteRefused('unknown-state', `${short(txid)} is not in the journal of ${id}`)
506
+ if (entry.network !== 'accepted' && entry.network !== 'dry-run') return false
298
507
  if (entry.proof == null) {
299
508
  const path = await this.options.wallet.adapter.merklePathFor(txid)
300
509
  if (path == null) return false
301
- entry.proof = { merklePath: path.toHex(), blockHeight: path.blockHeight }
302
510
  const tx = Transaction.fromHex(entry.rawTx)
303
511
  tx.merklePath = path
304
- entry.beef = Utils.toBase64(tx.toAtomicBEEF())
305
- await this.options.store.savePassport(record)
512
+ const updated = await this.options.store.changePassport(id, (current) => {
513
+ const state = current?.states.find((s) => s.txid === txid)
514
+ if (state == null) throw new WriteRefused('unknown-state', 'the proven state is absent')
515
+ if (state.proof == null) {
516
+ state.sentBeef = state.beef
517
+ state.beef = Utils.toBase64(tx.toAtomicBEEF())
518
+ state.proof = { merklePath: path.toHex(), blockHeight: path.blockHeight }
519
+ }
520
+ return current
521
+ })
522
+ entry = updated!.states.find((s) => s.txid === txid)!
306
523
  }
307
524
  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}`}`)
525
+ const proof = entry.proof!
526
+ const pushed = await this.options.index.pushProof(txid, MerklePath.fromHex(proof.merklePath))
527
+ if (pushed.ok) await this.options.store.changePassport(id, (current) => {
528
+ const state = current?.states.find((s) => s.txid === txid)
529
+ if (state?.proof?.merklePath === proof.merklePath) state.proofPushed = true
530
+ return current
531
+ })
312
532
  }
313
533
  return true
314
534
  }
315
535
 
536
+ /**
537
+ * A product document under a binding, validated whole, split and built into
538
+ * the exact public payload, before anything is signed. A document that
539
+ * fails, that could not be checked or whose public part is too large is
540
+ * refused here, with the validation in the refusal for the form to show.
541
+ */
542
+ private async prepareBound(bound: BindingProfile, product: Record<string, unknown>, passportId: string) {
543
+ const { identifiers } = this.options
544
+ const prepared = await this.options.bound.prepare({ profile: bound, product, passportId, ...(isDemonstrationPolicy(identifiers) ? { notice: DEMONSTRATION_NOTICE } : {}) })
545
+ if (prepared.ok) return prepared
546
+ const views: { validation?: ViewCheck; publicView?: ViewCheck } = {}
547
+ if (prepared.validation != null) views.validation = await this.options.bound.viewCheck('whole', prepared.validation, { profile: bound, product })
548
+ if (prepared.publicView != null) views.publicView = await this.options.bound.viewCheck('public', prepared.publicView)
549
+ const failed = (views.publicView ?? views.validation)?.steps.filter((step) => step.status !== 'pass').flatMap((step) => step.messages) ?? []
550
+ const said = failed.length === 0 ? '' : ` ${failed.slice(0, 5).join(' ')}${failed.length > 5 ? ` And ${failed.length - 5} more.` : ''}`
551
+ const engine = this.options.bound.engineProblem
552
+ if (prepared.code === 'validation-failed') throw new WriteRefused('product-invalid', `${prepared.detail} Nothing was signed.${said}`, { ...views, cause: views.validation?.cause })
553
+ if (prepared.code === 'validation-unavailable') {
554
+ throw new WriteRefused('product-not-validated', `${prepared.detail} Nothing was signed.${engine == null ? said : ` The validation engine is not available: ${engine}`}`, { ...views, cause: views.validation?.cause })
555
+ }
556
+ if (prepared.code === 'public-payload-too-large') {
557
+ throw new WriteRefused('public-payload-too-large', `${prepared.detail} Nothing was signed. Move data out of the public properties or shorten it: the restricted part does not count towards the limit.`, { byteLength: prepared.byteLength, limit: prepared.limit })
558
+ }
559
+ if (prepared.code === 'public-view-failed') throw new WriteRefused('public-view-failed', `${prepared.detail} Nothing was signed.${said}`, { ...views, cause: views.publicView?.cause })
560
+ throw new WriteRefused(prepared.code, `${prepared.detail} Nothing was signed.`)
561
+ }
562
+
316
563
  /** 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> {
564
+ async issue(args: { brandId: string; brand: Party; passportId: string; profile: string; payload?: Record<string, unknown>; ownerFields?: Record<string, unknown>; product?: Record<string, unknown> }): Promise<WriteOutcome> {
565
+ // Before the identifier is checked or the index asked: the answer does not depend on either.
566
+ requireIssuableProfile(args.profile)
318
567
  const problems = identifierProblems(args.passportId, this.options.identifiers)
319
568
  if (problems.length > 0) throw new WriteRefused('identifier-refused', `${args.passportId} cannot be written because ${problems.join('; and ')}`)
320
569
  const existing = await this.options.store.getPassport(args.passportId)
@@ -331,21 +580,24 @@ export class Writer {
331
580
  states: [],
332
581
  acceptanceRecords: [],
333
582
  }
334
- return await this.writeState({ record, op: 'ISSUE', actor: args.brand, controller: args.brand, profile: args.profile, payload: args.payload, ownerFields: args.ownerFields })
583
+ // A manifest profile's genesis always carries a payload and an owner tier; a bound profile's carries the product document.
584
+ const data = args.product != null ? { product: args.product } : { payload: args.payload ?? {}, ownerFields: args.ownerFields ?? {} }
585
+ return await this.writeState({ record, op: 'ISSUE', actor: args.brand, controller: args.brand, profile: args.profile, ...data })
335
586
  }
336
587
 
337
588
  /** 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 })
589
+ async update(args: { record: PassportRecord; actor: Party; payload?: Record<string, unknown>; ownerFields?: Record<string, unknown>; product?: Record<string, unknown>; eventData?: Record<string, unknown> }): Promise<WriteOutcome> {
590
+ const data = args.product != null ? { product: args.product } : { payload: args.payload ?? {}, ownerFields: args.ownerFields }
591
+ return await this.writeState({ record: args.record, op: 'UPDATE', actor: args.actor, controller: args.actor, profile: args.record.profile, ...data, eventData: args.eventData })
340
592
  }
341
593
 
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. */
594
+ /** The hand-on: the holder acts, control moves to the recipient's key, field 15 commits to the custodian-signed acceptance record, and the new commitment binds the ciphertext delivered to the recipient. */
343
595
  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 })
596
+ return await this.writeState({ record: args.record, op: 'TRANSFER', actor: args.holder, controller: args.recipient, profile: args.record.profile, eventData: args.eventData, acceptance: args.acceptance })
345
597
  }
346
598
 
347
599
  /** 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
600
  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 } })
601
+ return await this.writeState({ record: args.record, op: 'RETIRE', actor: args.actor, controller: args.actor, profile: args.record.profile, eventData: { reason: args.reason } })
350
602
  }
351
603
  }