@bsv/create-dpp-app 0.0.0-stage → 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/LICENSE +203 -0
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +93 -2
- package/dist/index.js +125 -0
- package/package.json +57 -4
- package/template/Dockerfile +37 -0
- package/template/README.md +389 -0
- package/template/_dockerignore +6 -0
- package/template/_env.example +122 -0
- package/template/_github/workflows/ci.yml +23 -0
- package/template/_gitignore +8 -0
- package/template/_prettierrc +6 -0
- package/template/apps/api/API.md +119 -0
- package/template/apps/api/package.json +39 -0
- package/template/apps/api/src/auth.ts +55 -0
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +204 -0
- package/template/apps/api/src/cli.ts +99 -0
- package/template/apps/api/src/config.ts +180 -0
- package/template/apps/api/src/custody.ts +358 -0
- package/template/apps/api/src/dev-index.ts +120 -0
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/env.ts +14 -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 +57 -0
- package/template/apps/api/src/index-client.ts +261 -0
- 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 +58 -0
- package/template/apps/api/src/parties.ts +68 -0
- package/template/apps/api/src/platform.ts +176 -0
- 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 +125 -0
- package/template/apps/api/src/reader.ts +265 -0
- 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 +613 -0
- package/template/apps/api/src/store.ts +426 -0
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +359 -0
- package/template/apps/api/src/worker.ts +113 -0
- package/template/apps/api/src/writer.ts +603 -0
- 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 +160 -0
- 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 +32 -0
- 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 +147 -0
- 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/tsconfig.json +9 -0
- package/template/apps/api/vitest.config.ts +12 -0
- package/template/apps/web/components.json +21 -0
- package/template/apps/web/index.html +12 -0
- package/template/apps/web/package.json +33 -0
- package/template/apps/web/src/app.tsx +55 -0
- package/template/apps/web/src/components/bits.tsx +188 -0
- 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 +135 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +244 -0
- package/template/apps/web/src/components/read-passport.tsx +49 -0
- package/template/apps/web/src/components/reading.tsx +150 -0
- package/template/apps/web/src/components/ui/alert.tsx +65 -0
- package/template/apps/web/src/components/ui/badge.tsx +47 -0
- package/template/apps/web/src/components/ui/button.tsx +63 -0
- package/template/apps/web/src/components/ui/card.tsx +91 -0
- package/template/apps/web/src/components/ui/dialog.tsx +156 -0
- package/template/apps/web/src/components/ui/input.tsx +20 -0
- package/template/apps/web/src/components/ui/label.tsx +21 -0
- package/template/apps/web/src/components/ui/select.tsx +189 -0
- package/template/apps/web/src/components/ui/separator.tsx +25 -0
- package/template/apps/web/src/components/ui/table.tsx +115 -0
- package/template/apps/web/src/components/ui/tabs.tsx +90 -0
- package/template/apps/web/src/components/ui/textarea.tsx +17 -0
- package/template/apps/web/src/index.css +81 -0
- package/template/apps/web/src/lib/api.ts +396 -0
- package/template/apps/web/src/lib/auth.ts +10 -0
- 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 +87 -0
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/lib/session.tsx +92 -0
- package/template/apps/web/src/lib/use-load.ts +46 -0
- package/template/apps/web/src/main.tsx +18 -0
- package/template/apps/web/src/pages/accept.tsx +113 -0
- package/template/apps/web/src/pages/brand.tsx +94 -0
- package/template/apps/web/src/pages/brands.tsx +104 -0
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/home.tsx +51 -0
- package/template/apps/web/src/pages/new-passport.tsx +137 -0
- package/template/apps/web/src/pages/operations.tsx +169 -0
- package/template/apps/web/src/pages/passport.tsx +632 -0
- package/template/apps/web/src/pages/public-passport.tsx +64 -0
- package/template/apps/web/src/pages/sign-in.tsx +93 -0
- package/template/apps/web/src/pages/verify.tsx +30 -0
- package/template/apps/web/src/pages/wallet.tsx +141 -0
- package/template/apps/web/tsconfig.json +29 -0
- package/template/apps/web/vite.config.ts +23 -0
- package/template/deploy/compose.yml +38 -0
- package/template/package.json +48 -0
- package/template/tsconfig.base.json +13 -0
|
@@ -0,0 +1,603 @@
|
|
|
1
|
+
// The writer: every state goes through the six steps of spec/writing.md in
|
|
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
|
+
// The journal entry is written before each step is acted on, so a retry
|
|
6
|
+
// continues an operation and never builds a second transaction.
|
|
7
|
+
//
|
|
8
|
+
// 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.
|
|
10
|
+
import { MerklePath, Transaction, Utils, type WalletProtocol } from '@bsv/sdk'
|
|
11
|
+
import {
|
|
12
|
+
acceptanceCommitment,
|
|
13
|
+
bindAcceptanceToState,
|
|
14
|
+
buildLockingScript,
|
|
15
|
+
completeState,
|
|
16
|
+
findDppOutputs,
|
|
17
|
+
ownerBlobHash,
|
|
18
|
+
ownerKeyFor,
|
|
19
|
+
verifyChain,
|
|
20
|
+
verifyOwnerBlob,
|
|
21
|
+
type DppStateDataV2,
|
|
22
|
+
type DppStateV2,
|
|
23
|
+
type ManagedAcceptanceRecord,
|
|
24
|
+
} from '@bsv/dpp-protocol'
|
|
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
|
+
import type { IndexClient } from './index-client.js'
|
|
29
|
+
import type { Party } from './parties.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
|
+
|
|
34
|
+
/** BRC-43 protocol the owner tier is encrypted under (spec/record-model.md section 7). */
|
|
35
|
+
export const OWNER_DATA_PROTOCOL: WalletProtocol = [2, 'dpp owner data v1']
|
|
36
|
+
|
|
37
|
+
export class WriteRefused extends Error {
|
|
38
|
+
constructor(
|
|
39
|
+
readonly code: string,
|
|
40
|
+
detail: string,
|
|
41
|
+
/** 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>
|
|
43
|
+
) {
|
|
44
|
+
super(detail)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
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
|
+
|
|
71
|
+
export interface WriterOptions {
|
|
72
|
+
store: Store
|
|
73
|
+
wallet: PlatformWallet
|
|
74
|
+
index: IndexClient
|
|
75
|
+
identifiers: IdentifierPolicy
|
|
76
|
+
/** The profiles held by a binding, with the validation engine. */
|
|
77
|
+
bound: BoundProfiles
|
|
78
|
+
/** Whether writes may reach the chain. False builds, checks and journals a state and then stops before the send. */
|
|
79
|
+
livePublishing: boolean
|
|
80
|
+
spendCapSatoshis: number
|
|
81
|
+
log?: (line: string) => void
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export interface WriteOutcome {
|
|
85
|
+
entry: StateEntry
|
|
86
|
+
state: DppStateV2
|
|
87
|
+
record: PassportRecord
|
|
88
|
+
}
|
|
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
|
+
|
|
94
|
+
const instant = (): string => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
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
|
+
}
|
|
103
|
+
|
|
104
|
+
export class Writer {
|
|
105
|
+
private readonly log: (line: string) => void
|
|
106
|
+
|
|
107
|
+
constructor(private readonly options: WriterOptions) {
|
|
108
|
+
this.log = options.log ?? (() => {})
|
|
109
|
+
}
|
|
110
|
+
|
|
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')
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The tip from the journal's BEEF, which carries its ancestry and, once proven, its merkle path. */
|
|
126
|
+
private tipOf(record: PassportRecord): Tip | undefined {
|
|
127
|
+
const last = record.states.at(-1)
|
|
128
|
+
if (last == null) return undefined
|
|
129
|
+
const beef = Utils.toArray(last.beef, 'base64') as number[]
|
|
130
|
+
return { tx: Transaction.fromAtomicBEEF(beef), txid: last.txid, outputIndex: last.outputIndex, beef }
|
|
131
|
+
}
|
|
132
|
+
|
|
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[] }> {
|
|
135
|
+
const check = validatePayload(profile, 'restricted', fields)
|
|
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[] }> {
|
|
147
|
+
const plaintext = Utils.toArray(JSON.stringify(fields), 'utf8') as number[]
|
|
148
|
+
const { ciphertext } = await controller.wallet.encrypt({ plaintext, protocolID: OWNER_DATA_PROTOCOL, keyID: passportId, counterparty: 'self' })
|
|
149
|
+
const hash = ownerBlobHash(ciphertext)
|
|
150
|
+
if (!verifyOwnerBlob(ciphertext, hash)) throw new WriteRefused('owner-tier-unsound', 'the sealed owner tier does not verify against its hash')
|
|
151
|
+
return { hash, ciphertext }
|
|
152
|
+
}
|
|
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
|
+
|
|
178
|
+
private async withinSpendCap(): Promise<void> {
|
|
179
|
+
const dayAgo = new Date(Date.now() - 24 * 3600_000).toISOString()
|
|
180
|
+
const spent = await this.options.store.spentSince(dayAgo)
|
|
181
|
+
if (spent >= this.options.spendCapSatoshis) throw new WriteRefused('spend-cap', `the platform has spent ${spent} satoshis in the last day, at or over SPEND_CAP_SATOSHIS=${this.options.spendCapSatoshis}`)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* One state through the six steps. `actor` signs as actor; `controller` is
|
|
186
|
+
* the party whose per-passport key field 6 names after this state (the
|
|
187
|
+
* actor until a hand-on, the recipient on a TRANSFER).
|
|
188
|
+
*/
|
|
189
|
+
private async writeState(args: {
|
|
190
|
+
record: PassportRecord
|
|
191
|
+
op: StateEntry['op']
|
|
192
|
+
actor: Party
|
|
193
|
+
controller: Party
|
|
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. */
|
|
196
|
+
payload?: Record<string, unknown>
|
|
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>
|
|
200
|
+
eventData?: Record<string, unknown>
|
|
201
|
+
acceptance?: ManagedAcceptanceRecord
|
|
202
|
+
}): Promise<WriteOutcome> {
|
|
203
|
+
const { op, actor, controller, profile } = args
|
|
204
|
+
const { store, wallet, index } = this.options
|
|
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)
|
|
214
|
+
const tip = this.tipOf(record)
|
|
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`)
|
|
216
|
+
if (op !== 'ISSUE' && tip == null) throw new WriteRefused('not-issued', `${passportId} has no genesis to follow`)
|
|
217
|
+
if (record.status === 'retired') throw new WriteRefused('retired', `${passportId} ended with a RETIRE; nothing may follow it`)
|
|
218
|
+
const tipEntry = record.states.at(-1)
|
|
219
|
+
let payloadPublic: string
|
|
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)
|
|
240
|
+
if (!publicCheck.valid) throw new WriteRefused('payload-invalid', `the public payload is refused by the ${profile} schema: ${publicCheck.problems.join('; ')}`)
|
|
241
|
+
payloadPublic = JSON.stringify(payload)
|
|
242
|
+
// A new payload with no owner fields carries the tip's sealed tier unchanged, when the actor still controls it.
|
|
243
|
+
sealed =
|
|
244
|
+
args.ownerFields == null && tip != null && tipEntry != null
|
|
245
|
+
? this.carriedTier(passportId, tip, tipEntry)
|
|
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`)
|
|
249
|
+
} else {
|
|
250
|
+
if (tip == null || tipEntry == null) throw new WriteRefused('nothing-to-carry', `${passportId} has no tip whose payload this ${op} could carry`)
|
|
251
|
+
payloadPublic = tipEntry.payloadPublic
|
|
252
|
+
sealed = this.carriedTier(passportId, tip, tipEntry)
|
|
253
|
+
}
|
|
254
|
+
await this.withinSpendCap()
|
|
255
|
+
|
|
256
|
+
if (op === 'TRANSFER' && sealed != null) sealed = await this.transferTier(passportId, sealed, actor, controller)
|
|
257
|
+
|
|
258
|
+
const previousController = tip == null ? undefined : record.holder.controllerKey
|
|
259
|
+
const controllerKey = await controller.controllerKey(passportId)
|
|
260
|
+
const data: DppStateDataV2 = {
|
|
261
|
+
version: '2',
|
|
262
|
+
op,
|
|
263
|
+
passportId,
|
|
264
|
+
timestamp: instant(),
|
|
265
|
+
ownerIdentityKey: controllerKey,
|
|
266
|
+
actorIdentityKey: actor.identityKey,
|
|
267
|
+
actorKeyId: actor.name,
|
|
268
|
+
eventData: args.eventData == null ? '' : JSON.stringify(args.eventData),
|
|
269
|
+
payloadPublic,
|
|
270
|
+
payloadOwnerHash: sealed?.hash ?? '',
|
|
271
|
+
previousTxid: tip == null ? '' : tip.txid,
|
|
272
|
+
previousOutputIndex: tip == null ? null : tip.outputIndex,
|
|
273
|
+
lineageGenesis: tip == null ? null : { txid: record.states[0].txid, outputIndex: record.states[0].outputIndex },
|
|
274
|
+
// The actor is never the controller key itself, so every later state proves control by linkage from the actor's identity key to the previous field 6.
|
|
275
|
+
controlLinkage: tip == null ? '' : await actor.controlLinkage(passportId),
|
|
276
|
+
authorisationCommitment: args.acceptance == null ? '' : acceptanceCommitment(args.acceptance),
|
|
277
|
+
}
|
|
278
|
+
if (tip != null && previousController != null && (await actor.controllerKey(passportId)) !== previousController) {
|
|
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
|
+
)
|
|
286
|
+
}
|
|
287
|
+
const spend = tip && await this.spendableTip(tip, record, actor)
|
|
288
|
+
const state = (await completeState(data, actor.wallet, wallet.publisher)) as DppStateV2
|
|
289
|
+
const lockingScript = buildLockingScript(state, controllerKey)
|
|
290
|
+
|
|
291
|
+
// Section 3: built unsent, complete and signed, spending nothing until it is sent.
|
|
292
|
+
let built
|
|
293
|
+
try {
|
|
294
|
+
built = await wallet.adapter.build({ lockingScript, tip: spend, passportId })
|
|
295
|
+
} catch (cause) {
|
|
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.`)
|
|
297
|
+
}
|
|
298
|
+
const outputIndex = findDppOutputs(built.tx)[0]?.outputIndex ?? 0
|
|
299
|
+
const entry: StateEntry = {
|
|
300
|
+
op,
|
|
301
|
+
txid: built.txid,
|
|
302
|
+
outputIndex,
|
|
303
|
+
rawTx: built.tx.toHex(),
|
|
304
|
+
beef: Utils.toBase64(built.beef),
|
|
305
|
+
timestamp: data.timestamp,
|
|
306
|
+
actor: actor.name,
|
|
307
|
+
controllerKey,
|
|
308
|
+
payloadPublic: data.payloadPublic,
|
|
309
|
+
...(sealed == null ? {} : { ownerTier: { ...sealed, ciphertext: Utils.toBase64(sealed.ciphertext) } }),
|
|
310
|
+
...(index.supportsRetraction ? { draftIndexId: index.destinationId } : {}),
|
|
311
|
+
index: index.supportsRetraction ? 'pending' : 'not-asked',
|
|
312
|
+
network: 'pending',
|
|
313
|
+
}
|
|
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!
|
|
325
|
+
}
|
|
326
|
+
const abandon = async (code: string, detail: string): Promise<never> => {
|
|
327
|
+
const current = await settle({ network: code === 'network-refused' ? 'refused' : 'not-sent' })
|
|
328
|
+
await this.removeDraft(current, built.txid, detail)
|
|
329
|
+
throw new WriteRefused(code, detail)
|
|
330
|
+
}
|
|
331
|
+
|
|
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
|
+
}
|
|
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
|
|
373
|
+
}
|
|
374
|
+
this.log(`${op} ${short(built.txid)} built unsent for ${passportId}`)
|
|
375
|
+
|
|
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
|
+
}
|
|
383
|
+
|
|
384
|
+
if (!this.options.livePublishing && wallet.kind === 'toolbox') {
|
|
385
|
+
await abandon('live-publishing-off', 'LIVE_PUBLISHING is false: the unsent draft was aborted.')
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Sections 4 and 5: send, and report only the network's answer.
|
|
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`)
|
|
394
|
+
}
|
|
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)
|
|
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
|
+
}
|
|
404
|
+
|
|
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!
|
|
425
|
+
}
|
|
426
|
+
|
|
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. */
|
|
456
|
+
async resolveInterrupted(record: PassportRecord, txid: string, outcome: 'sent' | 'abandoned'): Promise<PassportRecord> {
|
|
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)
|
|
476
|
+
}
|
|
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')
|
|
486
|
+
}
|
|
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!
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Keep the proof against the exact transaction for which it was obtained. */
|
|
502
|
+
async prove(record: PassportRecord, txid: string): Promise<boolean> {
|
|
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
|
|
507
|
+
if (entry.proof == null) {
|
|
508
|
+
const path = await this.options.wallet.adapter.merklePathFor(txid)
|
|
509
|
+
if (path == null) return false
|
|
510
|
+
const tx = Transaction.fromHex(entry.rawTx)
|
|
511
|
+
tx.merklePath = path
|
|
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)!
|
|
523
|
+
}
|
|
524
|
+
if (entry.proofPushed !== true) {
|
|
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
|
+
})
|
|
532
|
+
}
|
|
533
|
+
return true
|
|
534
|
+
}
|
|
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
|
+
|
|
563
|
+
/** The first state: the brand opens the passport under its own controller key. */
|
|
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)
|
|
567
|
+
const problems = identifierProblems(args.passportId, this.options.identifiers)
|
|
568
|
+
if (problems.length > 0) throw new WriteRefused('identifier-refused', `${args.passportId} cannot be written because ${problems.join('; and ')}`)
|
|
569
|
+
const existing = await this.options.store.getPassport(args.passportId)
|
|
570
|
+
if (existing != null && existing.states.length > 0) throw new WriteRefused('already-issued', `${args.passportId} is already in the journal`)
|
|
571
|
+
const held = await this.options.index.lineage(args.passportId).catch(() => [])
|
|
572
|
+
if (held.length > 0) throw new WriteRefused('already-on-index', `the index already holds ${held.length} state(s) for ${args.passportId}; use a serial that is not in use`)
|
|
573
|
+
const record: PassportRecord = {
|
|
574
|
+
passportId: args.passportId,
|
|
575
|
+
brandId: args.brandId,
|
|
576
|
+
profile: args.profile,
|
|
577
|
+
createdAt: instant(),
|
|
578
|
+
status: 'active',
|
|
579
|
+
holder: { party: args.brand.name, controllerKey: await args.brand.controllerKey(args.passportId) },
|
|
580
|
+
states: [],
|
|
581
|
+
acceptanceRecords: [],
|
|
582
|
+
}
|
|
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 })
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** A later state that changes the data, by the party that controls the passport. */
|
|
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 })
|
|
592
|
+
}
|
|
593
|
+
|
|
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. */
|
|
595
|
+
async transfer(args: { record: PassportRecord; holder: Party; recipient: Party; acceptance: ManagedAcceptanceRecord; eventData?: Record<string, unknown> }): Promise<WriteOutcome> {
|
|
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 })
|
|
597
|
+
}
|
|
598
|
+
|
|
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). */
|
|
600
|
+
async retire(args: { record: PassportRecord; actor: Party; reason: string }): Promise<WriteOutcome> {
|
|
601
|
+
return await this.writeState({ record: args.record, op: 'RETIRE', actor: args.actor, controller: args.actor, profile: args.record.profile, eventData: { reason: args.reason } })
|
|
602
|
+
}
|
|
603
|
+
}
|