@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.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- 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.
|
|
3
|
-
// to
|
|
4
|
-
//
|
|
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
|
-
//
|
|
9
|
-
//
|
|
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
|
|
27
|
-
import {
|
|
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
|
|
32
|
-
import type
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
|
|
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:
|
|
113
|
-
/** A new public payload and owner tier;
|
|
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 {
|
|
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:
|
|
132
|
-
|
|
133
|
-
|
|
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(
|
|
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
|
|
139
|
-
?
|
|
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
|
|
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 =
|
|
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
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
193
|
-
index:
|
|
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
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
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
|
|
207
|
-
|
|
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
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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
|
|
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
|
-
|
|
240
|
-
if (sent === '
|
|
241
|
-
|
|
242
|
-
|
|
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
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
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
|
-
|
|
254
|
-
|
|
255
|
-
if (
|
|
256
|
-
|
|
257
|
-
this
|
|
258
|
-
|
|
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
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
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
|
|
271
|
-
const entry =
|
|
272
|
-
if (entry == null) throw new WriteRefused('unknown-state', `${short(txid)} is not in the journal
|
|
273
|
-
if (entry
|
|
274
|
-
if (
|
|
275
|
-
if (outcome === '
|
|
276
|
-
entry.
|
|
277
|
-
|
|
278
|
-
|
|
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
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
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
|
-
|
|
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
|
-
/**
|
|
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
|
|
297
|
-
|
|
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
|
-
|
|
305
|
-
|
|
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
|
|
309
|
-
|
|
310
|
-
await this.options.store.
|
|
311
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
|
339
|
-
|
|
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
|
|
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
|
|
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
|
|
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
|
}
|