@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
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
// Restoring an authorised export of this application into a deployment.
|
|
2
|
+
//
|
|
3
|
+
// A restore is two steps, kept apart on purpose. `verifyApplicationPackage`
|
|
4
|
+
// reads a package and checks all of it, against what this deployment trusts,
|
|
5
|
+
// and writes nothing: the manifest and its signature, every file against the
|
|
6
|
+
// inventory, the descriptor, each passport's journal and the index's signed
|
|
7
|
+
// evidence for it, the profile bundle against this deployment's own trusted
|
|
8
|
+
// binding digests, and the EPCIS snapshot by the module's own checks.
|
|
9
|
+
// `restoreApplication` takes what was verified, compares it with what the
|
|
10
|
+
// deployment already holds, and only then writes.
|
|
11
|
+
//
|
|
12
|
+
// Nothing is trusted because it was carried, and nothing because it was
|
|
13
|
+
// signed. The exporter's signature says who assembled the bytes. Whether a
|
|
14
|
+
// profile may be used here is decided by this deployment's trusted digests,
|
|
15
|
+
// so a correctly signed package that carries another definition under a
|
|
16
|
+
// profile's name is refused. Whether a record may be written here is decided
|
|
17
|
+
// by what is already here: an equal record is left alone, which is what makes
|
|
18
|
+
// a restore safe to run twice, and a different one stops the restore before
|
|
19
|
+
// anything is written.
|
|
20
|
+
//
|
|
21
|
+
// A restore is a data operation. It builds no state, signs nothing and moves
|
|
22
|
+
// no custody. It sends the original announcement and any retained proof
|
|
23
|
+
// to this deployment's index, which rebuilds its records from them.
|
|
24
|
+
// Keys and credentials are not restored, because none are
|
|
25
|
+
// carried: continuing to write needs the wallet's keys, which travel by the
|
|
26
|
+
// wallet's own recovery, and each source's credential, which the operator
|
|
27
|
+
// configures again.
|
|
28
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
|
|
29
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path'
|
|
30
|
+
import { fileURLToPath } from 'node:url'
|
|
31
|
+
import { MerklePath, Transaction, Utils } from '@bsv/sdk'
|
|
32
|
+
import {
|
|
33
|
+
ACCEPTANCE_RECORD_REPRESENTATIONS,
|
|
34
|
+
acceptanceCommitment,
|
|
35
|
+
bindAcceptanceToState,
|
|
36
|
+
evidencePackageSigner,
|
|
37
|
+
findDppOutputs,
|
|
38
|
+
inspectEvidencePackage,
|
|
39
|
+
inspectManagedAcceptance,
|
|
40
|
+
MANAGED_CUSTODY_EXPORT_PROFILE,
|
|
41
|
+
verifyChain,
|
|
42
|
+
verifyOwnerBlob,
|
|
43
|
+
type DppStateV2,
|
|
44
|
+
type EvidencePackageManifest,
|
|
45
|
+
type InventoryEntry,
|
|
46
|
+
type ManagedAcceptanceRecord,
|
|
47
|
+
} from '@bsv/dpp-protocol'
|
|
48
|
+
import {
|
|
49
|
+
EPCIS_LIFECYCLE_REPRESENTATION,
|
|
50
|
+
verifyEpcisLifecycleClaim,
|
|
51
|
+
} from '@bsv/dpp-credentials/epcis-lifecycle'
|
|
52
|
+
import { BUNDLED_BINDINGS, BUNDLED_BINDING_DIGESTS, createProfileRegistry, isRetiredProfile, openProfileBundle, profileBundleFiles, registerProfileBundle } from '@bsv/dpp-profiles'
|
|
53
|
+
import { verifyGs1Artefacts } from '@bsv/dpp-credentials'
|
|
54
|
+
import { epcisRecoveryFiles, restoreEpcisRecovery, verifyEpcisRecovery, type EpcisExchangeStorage, type EpcisRestoreCounts, type VerifiedEpcisRecovery } from '@bsv/dpp-credentials/epcis-exchange'
|
|
55
|
+
import { acceptanceMatchesOffer } from '../custody.js'
|
|
56
|
+
import type { EpcisSourceConfig } from '../epcis/sources.js'
|
|
57
|
+
import type { Platform } from '../platform.js'
|
|
58
|
+
import { isProfileId } from '../profiles.js'
|
|
59
|
+
import { isEpcisLifecycleRecord, isInterrupted, type BrandRecord, type ClaimRecord, type OfferRecord, type PassportRecord, type StateEntry } from '../store.js'
|
|
60
|
+
import { declaredBindingDigest, summariseReading } from './export.js'
|
|
61
|
+
import {
|
|
62
|
+
APPLICATION_EXPORT_DESCRIPTOR,
|
|
63
|
+
APPLICATION_EXPORT_FORMAT,
|
|
64
|
+
APPLICATION_EXPORT_LIMITS,
|
|
65
|
+
APPLICATION_EXPORT_VERSION,
|
|
66
|
+
APPLICATION_REPRESENTATIONS,
|
|
67
|
+
EXPORT_SCOPE_PREFIX,
|
|
68
|
+
PortabilityRefused,
|
|
69
|
+
asNumberArrays,
|
|
70
|
+
exportScopeId,
|
|
71
|
+
passportFolder,
|
|
72
|
+
readNestedAcceptance,
|
|
73
|
+
recordBytes,
|
|
74
|
+
sameBytes,
|
|
75
|
+
sha256Hex,
|
|
76
|
+
stableJson,
|
|
77
|
+
type ApplicationExportDescriptor,
|
|
78
|
+
type ExportedReading,
|
|
79
|
+
} from './package.js'
|
|
80
|
+
|
|
81
|
+
const PROJECT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../../..')
|
|
82
|
+
|
|
83
|
+
/** What this deployment trusts, which decides what a package may bring. None of it is read from the package. */
|
|
84
|
+
export interface RestoreTrust {
|
|
85
|
+
/** The identity key the export must be signed under: the publisher key of the deployment that made it. */
|
|
86
|
+
exporterKey: string
|
|
87
|
+
/** The binding digests this deployment reviewed and chose to trust, beside the ones its installed profiles package publishes. */
|
|
88
|
+
trustedBindingDigests: readonly string[]
|
|
89
|
+
/** The exporter identity key of the index whose evidence is carried, when this deployment was told it. Without it, each carried package is held to the key its own manifest names, which the export's signature covers. */
|
|
90
|
+
indexExporterKey?: string
|
|
91
|
+
/** Require the signed exporter to have selected this custody profile for the operation. */
|
|
92
|
+
requiredCustodyProfile?: typeof MANAGED_CUSTODY_EXPORT_PROFILE
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** A package that was read and checked. Nothing has been written anywhere. */
|
|
96
|
+
export interface VerifiedApplicationPackage {
|
|
97
|
+
manifest: EvidencePackageManifest
|
|
98
|
+
descriptor: ApplicationExportDescriptor
|
|
99
|
+
files: Map<string, Uint8Array>
|
|
100
|
+
journals: PassportRecord[]
|
|
101
|
+
brands: BrandRecord[]
|
|
102
|
+
offers: OfferRecord[]
|
|
103
|
+
claims: ClaimRecord[]
|
|
104
|
+
readings: Map<string, ExportedReading>
|
|
105
|
+
/** The profiles the bundle carries, each with the binding digest that registered under this deployment's trust. */
|
|
106
|
+
profiles: Array<{ profile: string; bindingDigest: string }>
|
|
107
|
+
epcis?: VerifiedEpcisRecovery
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
111
|
+
const decoder = new TextDecoder('utf-8', { fatal: true })
|
|
112
|
+
|
|
113
|
+
/* ---------------------------------- verify ------------------------------- */
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Read a package and check all of it. A refusal is thrown as
|
|
117
|
+
* `PortabilityRefused`, with a code that names what was wrong, and nothing is
|
|
118
|
+
* written here whatever the answer.
|
|
119
|
+
*/
|
|
120
|
+
export async function verifyApplicationPackage(pkg: { manifestText?: string; files: Map<string, Uint8Array> }, trust: RestoreTrust): Promise<VerifiedApplicationPackage> {
|
|
121
|
+
const { files } = pkg
|
|
122
|
+
const refuse = (code: string, detail: string, data: Record<string, unknown> = {}): never => {
|
|
123
|
+
throw new PortabilityRefused(code, `${detail} Nothing was written.`, data)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/* ---- the manifest, its signature and its inventory ---- */
|
|
127
|
+
|
|
128
|
+
if (pkg.manifestText == null) refuse('manifest-missing', 'The folder holds no manifest.json, so it is not an evidence package.')
|
|
129
|
+
let manifest: EvidencePackageManifest
|
|
130
|
+
try {
|
|
131
|
+
manifest = JSON.parse(pkg.manifestText as string) as EvidencePackageManifest
|
|
132
|
+
} catch {
|
|
133
|
+
return refuse('manifest-invalid', 'manifest.json is not JSON.')
|
|
134
|
+
}
|
|
135
|
+
if (!isObject(manifest) || typeof manifest.passportId !== 'string' || !manifest.passportId.startsWith(EXPORT_SCOPE_PREFIX)) {
|
|
136
|
+
refuse('not-an-application-export', 'The package is not an export of an application: its manifest does not name an export. A package about one passport is restored into an index, by the index\'s own procedure.')
|
|
137
|
+
}
|
|
138
|
+
if (!/^0[23][0-9a-f]{64}$/.test(trust.exporterKey)) throw new TypeError('exporterKey must be a compressed public key')
|
|
139
|
+
const expectedSigner = evidencePackageSigner(trust.exporterKey, manifest.passportId)
|
|
140
|
+
const inspection = inspectEvidencePackage(manifest, asNumberArrays(files), { expectedSigner })
|
|
141
|
+
const failed = (reason: string): Array<{ path?: string; detail: string }> => inspection.failures.filter((failure) => failure.reason === reason)
|
|
142
|
+
if (!inspection.structureValid) refuse('manifest-invalid', `The manifest does not have the structure of dpp-evidence-package@1: ${inspection.failures.map((failure) => failure.detail).join('; ')}.`)
|
|
143
|
+
if (manifest.exporter?.id !== trust.exporterKey || failed('signer-unexpected').length > 0) {
|
|
144
|
+
refuse('exporter-unexpected', `The package says it was exported by ${String(manifest.exporter?.id)} and is signed by ${String(manifest.signature?.signer)}. This restore expects the exporter ${trust.exporterKey}.`, { exporter: manifest.exporter?.id })
|
|
145
|
+
}
|
|
146
|
+
if (inspection.signatureValid !== true) refuse('signature-invalid', 'The manifest\'s signature does not verify under the exporter\'s key, so nothing says who assembled these bytes.')
|
|
147
|
+
const missing = failed('file-missing')
|
|
148
|
+
if (missing.length > 0) refuse('package-incomplete', `The package is incomplete: ${missing.length === 1 ? 'a file its manifest lists is' : `${missing.length} files its manifest lists are`} not in the folder: ${missing.map((failure) => failure.path).join(', ')}.`, { missing: missing.map((failure) => failure.path) })
|
|
149
|
+
const altered = [...failed('digest-mismatch'), ...failed('length-mismatch')]
|
|
150
|
+
if (altered.length > 0) refuse('file-altered', `A file is not the bytes the signed manifest lists: ${[...new Set(altered.map((failure) => failure.path))].join(', ')}.`, { altered: [...new Set(altered.map((failure) => failure.path))] })
|
|
151
|
+
const unlisted = failed('file-unlisted')
|
|
152
|
+
if (unlisted.length > 0) refuse('file-unlisted', `The folder holds ${unlisted.length === 1 ? 'a file' : 'files'} the signed manifest does not list: ${unlisted.map((failure) => failure.path).join(', ')}. Nothing the exporter did not vouch for is restored.`, { unlisted: unlisted.map((failure) => failure.path) })
|
|
153
|
+
if (!inspection.inventoryVerified || inspection.failures.length > 0) refuse('manifest-invalid', `The package does not inspect: ${inspection.failures.map((failure) => failure.detail).join('; ')}.`)
|
|
154
|
+
|
|
155
|
+
const custodyV3 = Array.isArray(manifest.profiles) && manifest.profiles.every(profile => typeof profile === 'string') && manifest.profiles.includes(MANAGED_CUSTODY_EXPORT_PROFILE)
|
|
156
|
+
if (trust.requiredCustodyProfile != null && (trust.requiredCustodyProfile !== MANAGED_CUSTODY_EXPORT_PROFILE || !custodyV3)) {
|
|
157
|
+
refuse('not-selected', `This recovery requires ${trust.requiredCustodyProfile}, which could not be selected for the signed package.`, { profile: trust.requiredCustodyProfile })
|
|
158
|
+
}
|
|
159
|
+
if (manifest.disclosure.scope !== 'all-tiers' || manifest.disclosure.recoveryBackup !== true) {
|
|
160
|
+
refuse('not-a-recovery-package', `The package was assembled under the ${manifest.disclosure.scope} disclosure and is not a recovery backup. A public export carries no journal and no operational record, and restores nothing.`)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const listed = new Map<string, InventoryEntry>(manifest.inventory.map((entry) => [entry.path, entry]))
|
|
164
|
+
/** A file the package must hold, by the name of what it is. A missing one makes the package incomplete, by that name. */
|
|
165
|
+
const need = (path: string, what: string): Uint8Array => {
|
|
166
|
+
const bytes = listed.has(path) ? files.get(path) : undefined
|
|
167
|
+
if (bytes == null) return refuse('package-incomplete', `The package is incomplete: it does not carry ${what} (${path}).`, { missing: [path] })
|
|
168
|
+
return bytes
|
|
169
|
+
}
|
|
170
|
+
const json = <T>(path: string, what: string): T => {
|
|
171
|
+
const bytes = need(path, what)
|
|
172
|
+
try {
|
|
173
|
+
return JSON.parse(decoder.decode(bytes)) as T
|
|
174
|
+
} catch {
|
|
175
|
+
return refuse('record-invalid', `${what} (${path}) is not JSON.`, { path })
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/* ---- the descriptor ---- */
|
|
180
|
+
|
|
181
|
+
const descriptor = json<ApplicationExportDescriptor>(APPLICATION_EXPORT_DESCRIPTOR, 'the descriptor of the export')
|
|
182
|
+
if (!isObject(descriptor) || descriptor.format !== APPLICATION_EXPORT_FORMAT || descriptor.version !== APPLICATION_EXPORT_VERSION) refuse('descriptor-invalid', `The descriptor is not ${APPLICATION_EXPORT_FORMAT} version ${APPLICATION_EXPORT_VERSION}, which is the one this application reads.`)
|
|
183
|
+
if (descriptor.access !== 'authorised-recovery') refuse('not-a-recovery-package', 'The descriptor says the export is the public form. It restores nothing.')
|
|
184
|
+
if (!Array.isArray(descriptor.passports) || !isObject(descriptor.profiles) || !isObject(descriptor.epcis) || !isObject(descriptor.records) || !isObject(descriptor.application)) refuse('descriptor-invalid', 'The descriptor lacks a member the format requires.')
|
|
185
|
+
if (stableJson(descriptor.limits) !== stableJson(APPLICATION_EXPORT_LIMITS)) refuse('descriptor-invalid', 'The descriptor does not state the limits every export states.')
|
|
186
|
+
if (descriptor.exportId !== manifest.passportId || exportScopeId(descriptor.passports.map((passport) => passport.passportId)) !== manifest.passportId) {
|
|
187
|
+
refuse('export-scope-mismatch', 'The name of the export is not the one its passports give. The manifest was signed for another selection of passports than the descriptor lists.')
|
|
188
|
+
}
|
|
189
|
+
if (descriptor.application.publisherKey !== trust.exporterKey) refuse('descriptor-invalid', 'The descriptor names another publisher key than the one the package is signed under.')
|
|
190
|
+
|
|
191
|
+
/* ---- each passport: the journal, the index's evidence and the reading ---- */
|
|
192
|
+
|
|
193
|
+
const journals: PassportRecord[] = []
|
|
194
|
+
const readings = new Map<string, ExportedReading>()
|
|
195
|
+
const declaredDigests = new Map<string, string>()
|
|
196
|
+
// Only a successful send completes a journal transfer. Index admission can precede it.
|
|
197
|
+
const transfersByCommitment = new Map<string, DppStateV2>()
|
|
198
|
+
const transfersByTxid = new Map<string, DppStateV2>()
|
|
199
|
+
const authority = new Set<string>()
|
|
200
|
+
const heldAcceptances = new Set<string>()
|
|
201
|
+
const interruptedTransfers = new Set<string>()
|
|
202
|
+
const accounted = new Set<string>([APPLICATION_EXPORT_DESCRIPTOR])
|
|
203
|
+
for (const passport of descriptor.passports) {
|
|
204
|
+
const { passportId } = passport
|
|
205
|
+
const folder = passportFolder(passportId)
|
|
206
|
+
if (passport.folder !== folder) refuse('descriptor-invalid', `The descriptor places ${passportId} in ${String(passport.folder)}, and a passport's folder is named by the digest of its identifier.`)
|
|
207
|
+
const record = json<PassportRecord>(`${folder}/journal.json`, `the journal of ${passportId}`)
|
|
208
|
+
accounted.add(`${folder}/journal.json`)
|
|
209
|
+
if (!isObject(record) || record.passportId !== passportId || !Array.isArray(record.states) || record.states.length === 0 || !Array.isArray(record.acceptanceRecords)) refuse('record-invalid', `The journal of ${passportId} is not a journal of that passport.`, { passportId })
|
|
210
|
+
if (record.states.length !== passport.states || record.states[0]!.txid !== passport.genesis || record.states.at(-1)!.txid !== passport.tip || record.profile !== passport.profile) {
|
|
211
|
+
refuse('records-inconsistent', `The journal of ${passportId} is not the one the descriptor describes: its states, its first and newest transaction or its profile differ.`, { passportId })
|
|
212
|
+
}
|
|
213
|
+
// Every state is the transaction it says it is, about this passport, and its BEEF carries that transaction.
|
|
214
|
+
const lineage: Transaction[] = []
|
|
215
|
+
for (const state of record.states) {
|
|
216
|
+
let tx: Transaction
|
|
217
|
+
let carried: Transaction
|
|
218
|
+
try {
|
|
219
|
+
tx = Transaction.fromHex(state.rawTx)
|
|
220
|
+
carried = Transaction.fromAtomicBEEF(Utils.toArray(state.beef, 'base64') as number[])
|
|
221
|
+
} catch {
|
|
222
|
+
return refuse('record-invalid', `A state of ${passportId} does not hold a transaction that parses.`, { passportId, txid: state.txid })
|
|
223
|
+
}
|
|
224
|
+
const held = findDppOutputs(tx).find((output) => output.outputIndex === state.outputIndex)?.state
|
|
225
|
+
if (tx.id('hex') !== state.txid || carried.id('hex') !== state.txid || held == null || held.passportId !== passportId || held.payloadPublic !== state.payloadPublic) {
|
|
226
|
+
refuse('records-inconsistent', `The state ${state.txid} of ${passportId} is not the transaction its journal entry describes.`, { passportId, txid: state.txid })
|
|
227
|
+
}
|
|
228
|
+
try {
|
|
229
|
+
if (state.sentBeef != null && Transaction.fromAtomicBEEF(Utils.toArray(state.sentBeef, 'base64')).id('hex') !== state.txid) throw new Error('the original announcement carries a different transaction')
|
|
230
|
+
if (state.proof != null) {
|
|
231
|
+
const path = MerklePath.fromHex(state.proof.merklePath)
|
|
232
|
+
const root = path.computeRoot(state.txid)
|
|
233
|
+
if (path.blockHeight !== state.proof.blockHeight) throw new Error('the retained proof gives a different block height')
|
|
234
|
+
const embedded = carried.merklePath
|
|
235
|
+
if (embedded != null && (embedded.blockHeight !== path.blockHeight || embedded.computeRoot(state.txid) !== root)) throw new Error('the BEEF and the retained proof disagree')
|
|
236
|
+
}
|
|
237
|
+
} catch (cause) {
|
|
238
|
+
refuse('records-inconsistent', `The replay evidence for ${state.txid} of ${passportId} is inconsistent (${cause instanceof Error ? cause.message : String(cause)}).`, { passportId, txid: state.txid })
|
|
239
|
+
}
|
|
240
|
+
const tier = state.ownerTier
|
|
241
|
+
if (tier != null && (typeof tier.ciphertext !== 'string' || tier.hash !== held!.payloadOwnerHash || !verifyOwnerBlob(Utils.toArray(tier.ciphertext, 'base64'), held!.payloadOwnerHash))) {
|
|
242
|
+
refuse('records-inconsistent', `The retained owner tier of ${state.txid} differs from its signed commitment.`, { passportId, txid: state.txid })
|
|
243
|
+
}
|
|
244
|
+
if (custodyV3) {
|
|
245
|
+
if (held?.version === '2' && held.op === 'TRANSFER') {
|
|
246
|
+
if (state.op !== held.op) refuse('records-inconsistent', `The journal misidentifies transfer ${state.txid}.`, { passportId, txid: state.txid })
|
|
247
|
+
if (state.network === 'accepted' || state.network === 'dry-run') {
|
|
248
|
+
transfersByCommitment.set(held.authorisationCommitment, held)
|
|
249
|
+
transfersByTxid.set(state.txid, held)
|
|
250
|
+
} else if (isInterrupted(state)) {
|
|
251
|
+
interruptedTransfers.add(held.authorisationCommitment)
|
|
252
|
+
} else {
|
|
253
|
+
refuse('records-inconsistent', `Transfer ${state.txid} has an unknown send outcome.`, { passportId, txid: state.txid })
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (state.acceptance != null) {
|
|
257
|
+
const checked = inspectManagedAcceptance(state.acceptance, { custodians: [trust.exporterKey] })
|
|
258
|
+
if (checked.failures.length > 0 || checked.commitment == null || held?.version !== '2' || bindAcceptanceToState(state.acceptance, held).length > 0) {
|
|
259
|
+
return refuse('records-inconsistent', `The retained acceptance in ${state.txid} does not bind to its transfer.`, { passportId, txid: state.txid })
|
|
260
|
+
}
|
|
261
|
+
heldAcceptances.add(checked.commitment)
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
lineage.push(tx)
|
|
265
|
+
const digest = declaredBindingDigest(state.payloadPublic)
|
|
266
|
+
if (digest != null) {
|
|
267
|
+
const before = declaredDigests.get(record.profile)
|
|
268
|
+
if (before != null && before !== digest) refuse('records-inconsistent', `The states of the carried passports declare ${record.profile} under two binding digests, ${before} and ${digest}. A profile version has one binding.`, { profile: record.profile })
|
|
269
|
+
declaredDigests.set(record.profile, digest)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// The writer's own check, on the lineage as carried: every link, every signature and the publisher's countersignature. No inclusion is checked here.
|
|
273
|
+
const chain = await verifyChain(lineage, { chainTracker: 'scripts only', serverIdentityKey: trust.exporterKey, managedAcceptance: true })
|
|
274
|
+
if (!chain.valid) refuse('journal-invalid', `The lineage the journal of ${passportId} carries does not verify: ${chain.error ?? 'no reason given'}.`, { passportId })
|
|
275
|
+
|
|
276
|
+
// Each acceptance record a hand-on commits to is carried once more as the authority entry a reader of the package finds, and the two agree.
|
|
277
|
+
for (const acceptance of record.acceptanceRecords as ManagedAcceptanceRecord[]) {
|
|
278
|
+
const commitment = acceptanceCommitment(acceptance)
|
|
279
|
+
if (custodyV3) {
|
|
280
|
+
const transfer = transfersByCommitment.get(commitment)
|
|
281
|
+
const checked = inspectManagedAcceptance(acceptance, { custodians: [trust.exporterKey] })
|
|
282
|
+
if (authority.has(commitment) || transfer?.passportId !== passportId || checked.failures.length > 0 || bindAcceptanceToState(acceptance, transfer).length > 0) {
|
|
283
|
+
refuse('records-inconsistent', `The authority record ${commitment} for ${passportId} must uniquely bind to a completed transfer.`, { passportId, commitment })
|
|
284
|
+
}
|
|
285
|
+
authority.add(commitment)
|
|
286
|
+
}
|
|
287
|
+
const path = `${folder}/authority/${commitment}.json`
|
|
288
|
+
const bytes = need(path, `the acceptance record ${commitment} of ${passportId}`)
|
|
289
|
+
const entry = listed.get(path)!
|
|
290
|
+
if (!sameBytes(bytes, recordBytes(acceptance)) || entry.category !== 'authority' || entry.representation !== acceptance.acceptanceFormat || entry.represents !== `sha256:${commitment}`) {
|
|
291
|
+
refuse('records-inconsistent', `The acceptance record ${commitment} of ${passportId} does not match its authority inventory entry.`, { passportId })
|
|
292
|
+
}
|
|
293
|
+
accounted.add(path)
|
|
294
|
+
}
|
|
295
|
+
if (record.acceptanceRecords.length !== passport.acceptanceRecords) refuse('records-inconsistent', `The descriptor counts ${passport.acceptanceRecords} acceptance records for ${passportId} and its journal holds ${record.acceptanceRecords.length}.`, { passportId })
|
|
296
|
+
|
|
297
|
+
await verifyIndexEvidence({
|
|
298
|
+
passportId, folder, form: passport.index?.form, files, listed, trust, journal: record, accounted, refuse,
|
|
299
|
+
custody: custodyV3 ? { transfersByCommitment, heldAcceptances } : undefined,
|
|
300
|
+
})
|
|
301
|
+
|
|
302
|
+
if (listed.has(`${folder}/reading.json`)) {
|
|
303
|
+
readings.set(passportId, json<ExportedReading>(`${folder}/reading.json`, `the reading of ${passportId}`))
|
|
304
|
+
accounted.add(`${folder}/reading.json`)
|
|
305
|
+
}
|
|
306
|
+
journals.push(record)
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/* ---- this application's other records ---- */
|
|
310
|
+
|
|
311
|
+
const recordsUnder = <T>(prefix: string, representation: string, what: string): T[] => {
|
|
312
|
+
const out: T[] = []
|
|
313
|
+
for (const entry of manifest.inventory) {
|
|
314
|
+
if (!entry.path.startsWith(prefix)) continue
|
|
315
|
+
if (entry.representation !== representation) refuse('record-invalid', `${entry.path} is listed as ${String(entry.representation)}, and a file there is ${what}.`, { path: entry.path })
|
|
316
|
+
out.push(json<T>(entry.path, what))
|
|
317
|
+
accounted.add(entry.path)
|
|
318
|
+
}
|
|
319
|
+
return out
|
|
320
|
+
}
|
|
321
|
+
const brands = recordsUnder<BrandRecord>('application/brands/', APPLICATION_REPRESENTATIONS.brand, 'a brand record')
|
|
322
|
+
const offers = recordsUnder<OfferRecord>('application/offers/', APPLICATION_REPRESENTATIONS.offer, 'a hand-on offer')
|
|
323
|
+
const claims = recordsUnder<ClaimRecord>('application/claims/', APPLICATION_REPRESENTATIONS.claim, 'a lifecycle claim')
|
|
324
|
+
if (brands.length !== descriptor.records.brands || offers.length !== descriptor.records.offers || claims.length !== descriptor.records.claims) {
|
|
325
|
+
refuse('package-incomplete', `The package is incomplete: the descriptor counts ${descriptor.records.brands} brands, ${descriptor.records.offers} offers and ${descriptor.records.claims} claims, and the package carries ${brands.length}, ${offers.length} and ${claims.length}.`)
|
|
326
|
+
}
|
|
327
|
+
for (const record of journals) {
|
|
328
|
+
// A brand the exporting deployment held no record of is said to be absent, by name. One that is neither carried nor declared was left out.
|
|
329
|
+
const declaredAbsent = manifest.completeness.absent.some((line) => line.startsWith(`brand:${record.brandId} `))
|
|
330
|
+
if (!brands.some((brand) => brand.id === record.brandId) && !declaredAbsent) refuse('package-incomplete', `The package is incomplete: it does not carry the brand record of ${record.brandId}, which holds ${record.passportId}.`, { brandId: record.brandId })
|
|
331
|
+
}
|
|
332
|
+
for (const offer of offers) {
|
|
333
|
+
const passport = journals.find(record => record.passportId === offer.passportId)
|
|
334
|
+
if (passport == null) return refuse('records-inconsistent', `The offer ${offer.requestId} is about a passport the package does not carry.`)
|
|
335
|
+
const accepted = offer.status === 'accepted' || offer.status === 'transferred'
|
|
336
|
+
let missingCompletedRecord = false
|
|
337
|
+
if (custodyV3) {
|
|
338
|
+
if (offer.record != null) {
|
|
339
|
+
const commitment = acceptanceCommitment(offer.record)
|
|
340
|
+
heldAcceptances.add(commitment)
|
|
341
|
+
if (offer.status === 'accepted') interruptedTransfers.delete(commitment)
|
|
342
|
+
}
|
|
343
|
+
if (offer.status === 'transferred') {
|
|
344
|
+
const transfer = offer.transferTxid == null ? undefined : transfersByTxid.get(offer.transferTxid)
|
|
345
|
+
if (transfer?.passportId !== offer.passportId || transfer.previousTxid !== offer.expectedPredecessor?.txid || transfer.previousOutputIndex !== offer.expectedPredecessor?.outputIndex ||
|
|
346
|
+
transfer.actorIdentityKey !== offer.holderIdentityKey || (offer.record != null && transfer.authorisationCommitment !== acceptanceCommitment(offer.record))) {
|
|
347
|
+
refuse('records-inconsistent', `The completed offer ${offer.requestId} does not match its retained transfer.`, { requestId: offer.requestId })
|
|
348
|
+
} else {
|
|
349
|
+
missingCompletedRecord = offer.record == null && !authority.has(transfer.authorisationCommitment)
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if ((accepted !== (offer.record != null) && !missingCompletedRecord) || (offer.record != null && !acceptanceMatchesOffer(offer, offer.record, passport, trust.exporterKey))) {
|
|
354
|
+
refuse('records-inconsistent', `The status or signed acceptance of offer ${offer.requestId} does not agree with the retained offer.`, { requestId: offer.requestId })
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
if (custodyV3) {
|
|
358
|
+
if (interruptedTransfers.size > 0) refuse('records-inconsistent', 'An interrupted transfer lacks its retained signed offer.')
|
|
359
|
+
const absent = manifest.completeness.absent.filter(line => line.startsWith('acceptance:'))
|
|
360
|
+
const expected = new Set<string>()
|
|
361
|
+
for (const commitment of transfersByCommitment.keys()) {
|
|
362
|
+
if (authority.has(commitment)) continue
|
|
363
|
+
if (heldAcceptances.has(commitment)) refuse('records-inconsistent', `The package holds the acceptance ${commitment} of a completed transfer but omits its authority entry.`, { commitment })
|
|
364
|
+
expected.add(`acceptance:sha256:${commitment}`)
|
|
365
|
+
}
|
|
366
|
+
for (const reference of absent) {
|
|
367
|
+
if (!expected.delete(reference)) refuse('records-inconsistent', `The recovery manifest declares an unexpected or duplicate absent acceptance ${reference}.`)
|
|
368
|
+
}
|
|
369
|
+
if (expected.size > 0) refuse('records-inconsistent', 'The manifest omits a missing completed acceptance.', { missing: [...expected] })
|
|
370
|
+
if (manifest.completeness.withheld.some(line => line.startsWith('acceptance:'))) refuse('records-inconsistent', 'An authorised recovery manifest withholds a signed acceptance.')
|
|
371
|
+
}
|
|
372
|
+
for (const claim of claims) {
|
|
373
|
+
const about = isEpcisLifecycleRecord(claim) ? claim.boundPassports : [claim.passportId]
|
|
374
|
+
if (!journals.some((record) => about.includes(record.passportId))) refuse('records-inconsistent', `The claim ${claim.id} is about a passport the package does not carry.`)
|
|
375
|
+
if (!isEpcisLifecycleRecord(claim)) continue
|
|
376
|
+
// An EPCIS lifecycle claim travels as its exact signed bytes, and is restored only when those bytes verify as the claim the record names.
|
|
377
|
+
const path = `application/lifecycle-claims/${sha256Hex(claim.id)}.json`
|
|
378
|
+
if (listed.get(path)?.representation !== EPCIS_LIFECYCLE_REPRESENTATION) refuse('package-incomplete', `The package is incomplete: it does not carry the signed bytes of the claim ${claim.id} (${path}).`, { missing: [path] })
|
|
379
|
+
const carried = decoder.decode(need(path, `the signed bytes of the claim ${claim.id}`))
|
|
380
|
+
accounted.add(path)
|
|
381
|
+
const verified = await verifyEpcisLifecycleClaim(carried)
|
|
382
|
+
if (carried !== claim.bytes || verified.attestationId !== claim.attestationId || verified.findings.signature.status !== 'pass' || verified.findings.eventStructure.status === 'fail') {
|
|
383
|
+
refuse('claim-invalid', `The claim ${claim.id} does not verify from the bytes the package carries: ${carried !== claim.bytes ? 'the record and the signed bytes differ' : verified.findings.signature.status !== 'pass' ? 'its signature does not hold' : verified.attestationId !== claim.attestationId ? 'the bytes are not the claim the record names' : 'its event is refused'}.`, { claim: claim.id })
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
for (const entry of manifest.inventory) {
|
|
387
|
+
if (entry.path.startsWith('application/lifecycle-claims/') && !accounted.has(entry.path)) refuse('records-inconsistent', `${entry.path} carries the bytes of a claim no record of the package names.`, { path: entry.path })
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/* ---- the profiles, under this deployment's trust ---- */
|
|
391
|
+
|
|
392
|
+
const profiles: VerifiedApplicationPackage['profiles'] = []
|
|
393
|
+
const carried = Array.isArray(descriptor.profiles.carried) ? descriptor.profiles.carried : []
|
|
394
|
+
for (const record of journals) {
|
|
395
|
+
const declares = declaredDigests.has(record.profile)
|
|
396
|
+
if (declares && !carried.includes(record.profile)) refuse('package-incomplete', `The package is incomplete: ${record.passportId} declares ${record.profile} under a binding, and the package does not carry that profile.`, { profile: record.profile })
|
|
397
|
+
if (!declares && !carried.includes(record.profile) && !isProfileId(record.profile) && !isRetiredProfile(record.profile)) refuse('profile-not-available', `${record.passportId} is under ${record.profile}, which the package does not carry and this deployment's profiles package does not define.`, { profile: record.profile })
|
|
398
|
+
}
|
|
399
|
+
if (carried.length > 0) {
|
|
400
|
+
const root = descriptor.profiles.root ?? 'profiles'
|
|
401
|
+
const opened = await openProfileBundle(profileBundleFiles(files), { root })
|
|
402
|
+
if (!opened.ok) return refuse('profile-refused', `The profile bundle is refused (${opened.code}): ${opened.detail}`, { code: opened.code })
|
|
403
|
+
const missingFromBundle = carried.filter((profile) => !opened.bundle.profiles.includes(profile))
|
|
404
|
+
if (missingFromBundle.length > 0) refuse('package-incomplete', `The package is incomplete: its bundle does not cover ${missingFromBundle.join(', ')}, which its records declare.`, { profiles: missingFromBundle })
|
|
405
|
+
// What this deployment expects each name to be: the digest its installed profiles package publishes for a sector profile, and the digest the carried states declare.
|
|
406
|
+
const expected = new Map<string, string>(BUNDLED_BINDINGS.map((entry) => [entry.profile, entry.bindingDigest]))
|
|
407
|
+
for (const [profile, digest] of declaredDigests) {
|
|
408
|
+
const known = expected.get(profile)
|
|
409
|
+
if (known != null && known !== digest) refuse('profile-binding-conflict', `The carried states declare ${profile} under binding ${digest}, and this deployment's profiles package knows ${profile} under ${known}. They are different definitions under one name.`, { profile })
|
|
410
|
+
expected.set(profile, digest)
|
|
411
|
+
}
|
|
412
|
+
// A registry of its own, with this deployment's trusted digests, so that the answer is the one start-up will give and nothing is registered yet.
|
|
413
|
+
const registry = createProfileRegistry({ trustedBindingDigests: [...BUNDLED_BINDING_DIGESTS, ...trust.trustedBindingDigests] })
|
|
414
|
+
const results = await registerProfileBundle(registry, opened.bundle, { profiles: opened.bundle.profiles, expected: [...expected].map(([profile, bindingDigest]) => ({ profile, bindingDigest })) })
|
|
415
|
+
for (const result of results) {
|
|
416
|
+
if (!result.ok) {
|
|
417
|
+
return refuse('profile-refused', `The profile ${result.profile ?? ''} in the package is refused (${result.code}): ${result.detail}`, { code: result.code, ...(result.profile == null ? {} : { profile: result.profile }), ...(result.bindingDigest == null ? {} : { bindingDigest: result.bindingDigest }) })
|
|
418
|
+
}
|
|
419
|
+
profiles.push({ profile: result.profile.profile, bindingDigest: result.profile.bindingDigest })
|
|
420
|
+
}
|
|
421
|
+
for (const entry of manifest.inventory) if (entry.path.startsWith(`${root}/`)) accounted.add(entry.path)
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/* ---- the EPCIS exchange, by the module's own checks ---- */
|
|
425
|
+
|
|
426
|
+
let epcis: VerifiedEpcisRecovery | undefined
|
|
427
|
+
if (descriptor.epcis.root != null) {
|
|
428
|
+
const root = descriptor.epcis.root
|
|
429
|
+
const verified = await verifyEpcisRecovery(epcisRecoveryFiles(files), { inventory: manifest.inventory, root })
|
|
430
|
+
if (!verified.ok) return refuse('epcis-refused', `The EPCIS snapshot is refused (${verified.code}): ${verified.detail}`, { code: verified.code, ...(verified.path == null ? {} : { path: verified.path }), ...(verified.breaches == null ? {} : { breaches: verified.breaches }) })
|
|
431
|
+
if (verified.descriptor.snapshot.snapshotId !== descriptor.epcis.snapshotId) refuse('records-inconsistent', 'The EPCIS snapshot in the package is not the one the descriptor names.')
|
|
432
|
+
epcis = verified
|
|
433
|
+
for (const entry of manifest.inventory) if (entry.path.startsWith(`${root}/`)) accounted.add(entry.path)
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// Every file is part of something this restore understands. One that is not is never carried along unread.
|
|
437
|
+
const stray = manifest.inventory.map((entry) => entry.path).filter((path) => !accounted.has(path))
|
|
438
|
+
if (stray.length > 0) refuse('file-unaccounted', `The package lists ${stray.length === 1 ? 'a file' : 'files'} that belong to no part of an export this application reads: ${stray.slice(0, 8).join(', ')}${stray.length > 8 ? ` and ${stray.length - 8} more` : ''}.`, { paths: stray })
|
|
439
|
+
|
|
440
|
+
return { manifest, descriptor, files, journals, brands, offers, claims, readings, profiles, ...(epcis == null ? {} : { epcis }) }
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** The index's signed evidence for one passport: inspected under the index's exporter key, and held against the journal. */
|
|
444
|
+
async function verifyIndexEvidence(args: {
|
|
445
|
+
passportId: string
|
|
446
|
+
folder: string
|
|
447
|
+
form: string | undefined
|
|
448
|
+
custody?: { transfersByCommitment: Map<string, DppStateV2>; heldAcceptances: Set<string> }
|
|
449
|
+
files: Map<string, Uint8Array>
|
|
450
|
+
listed: Map<string, InventoryEntry>
|
|
451
|
+
trust: RestoreTrust
|
|
452
|
+
journal: PassportRecord
|
|
453
|
+
accounted: Set<string>
|
|
454
|
+
refuse: (code: string, detail: string, data?: Record<string, unknown>) => never
|
|
455
|
+
}): Promise<void> {
|
|
456
|
+
const { passportId, folder, form, files, listed, trust, journal, custody, accounted, refuse } = args
|
|
457
|
+
const base = `${folder}/index/`
|
|
458
|
+
const under = [...listed.keys()].filter((path) => path.startsWith(base))
|
|
459
|
+
if (form === 'none') {
|
|
460
|
+
if (under.length > 0) refuse('records-inconsistent', `The descriptor says no index evidence is carried for ${passportId}, and the package holds some.`, { passportId })
|
|
461
|
+
return
|
|
462
|
+
}
|
|
463
|
+
if (form !== 'package' && form !== 'bounded-package' && form !== 'export-parts') refuse('descriptor-invalid', `The descriptor does not say how the index's evidence for ${passportId} is carried.`)
|
|
464
|
+
for (const path of under) accounted.add(path)
|
|
465
|
+
|
|
466
|
+
const signerFor = (nested: EvidencePackageManifest): string => {
|
|
467
|
+
const key = trust.indexExporterKey ?? nested.exporter?.id
|
|
468
|
+
// An index on an earlier release signed with its raw export key and names it as both.
|
|
469
|
+
return nested.exporter?.id === key && nested.signature?.signer === key ? key : evidencePackageSigner(String(key), passportId)
|
|
470
|
+
}
|
|
471
|
+
const read = (at: string): { nested: EvidencePackageManifest; nestedFiles: Map<string, Uint8Array> } => {
|
|
472
|
+
const bytes = listed.has(`${at}manifest.json`) ? files.get(`${at}manifest.json`) : undefined
|
|
473
|
+
if (bytes == null) return refuse('package-incomplete', `The package is incomplete: it does not carry the manifest of the index's evidence for ${passportId} (${at}manifest.json).`, { missing: [`${at}manifest.json`] })
|
|
474
|
+
let nested: EvidencePackageManifest
|
|
475
|
+
try {
|
|
476
|
+
nested = JSON.parse(decoder.decode(bytes)) as EvidencePackageManifest
|
|
477
|
+
} catch {
|
|
478
|
+
return refuse('index-evidence-refused', `The manifest of the index's evidence for ${passportId} is not JSON.`, { passportId })
|
|
479
|
+
}
|
|
480
|
+
const nestedFiles = new Map<string, Uint8Array>()
|
|
481
|
+
for (const entry of Array.isArray(nested?.inventory) ? nested.inventory : []) {
|
|
482
|
+
const held = listed.has(`${at}${entry.path}`) ? files.get(`${at}${entry.path}`) : undefined
|
|
483
|
+
if (held != null) nestedFiles.set(entry.path, held)
|
|
484
|
+
}
|
|
485
|
+
return { nested, nestedFiles }
|
|
486
|
+
}
|
|
487
|
+
const transactions = new Map<string, Uint8Array>()
|
|
488
|
+
const scopedAuthority = new Set<string>()
|
|
489
|
+
const collect = (at: string, nested: EvidencePackageManifest, nestedFiles: Map<string, Uint8Array>): void => {
|
|
490
|
+
for (const entry of nested.inventory) {
|
|
491
|
+
const bytes = nestedFiles.get(entry.path)
|
|
492
|
+
if (bytes == null) return refuse('index-evidence-refused', 'The index inventory names a missing file.', { passportId, path: at + entry.path })
|
|
493
|
+
if (entry.category === 'transactions' && entry.path.endsWith('.tx')) transactions.set(entry.path.slice(entry.path.lastIndexOf('/') + 1, -3), bytes)
|
|
494
|
+
if (custody == null) continue
|
|
495
|
+
const record = readNestedAcceptance(entry, bytes, passportId, trust.exporterKey)
|
|
496
|
+
if (record == null) continue
|
|
497
|
+
const path = at + entry.path
|
|
498
|
+
const outer = listed.get(path)!
|
|
499
|
+
if (outer.representation !== APPLICATION_REPRESENTATIONS.nestedAuthority || outer.category !== entry.category || outer.represents !== entry.represents || outer.mediaType !== entry.mediaType) {
|
|
500
|
+
refuse('index-evidence-refused', 'The scoped authority entry differs from the signed index inventory.', { passportId, path })
|
|
501
|
+
}
|
|
502
|
+
const commitment = acceptanceCommitment(record)
|
|
503
|
+
const transfer = custody.transfersByCommitment.get(commitment)
|
|
504
|
+
if (transfer?.passportId !== passportId || bindAcceptanceToState(record, transfer).length > 0) {
|
|
505
|
+
refuse('index-evidence-refused', 'An index acceptance does not bind to a completed transfer in the supplied journal.', { passportId, path, commitment })
|
|
506
|
+
}
|
|
507
|
+
scopedAuthority.add(path)
|
|
508
|
+
custody.heldAcceptances.add(commitment)
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
if (form === 'export-parts') {
|
|
513
|
+
const { joinEvidenceExport } = await import('@bsv/dpp-overlay')
|
|
514
|
+
const parts: Array<Record<string, unknown>> = []
|
|
515
|
+
for (let at = 1; listed.has(`${base}part-${at}/manifest.json`); at += 1) {
|
|
516
|
+
const { nested, nestedFiles } = read(`${base}part-${at}/`)
|
|
517
|
+
const coverageBytes = files.get(`${base}part-${at}/coverage.json`)
|
|
518
|
+
if (coverageBytes == null) return refuse('package-incomplete', `The package is incomplete: part ${at} of the index's evidence for ${passportId} has no coverage record.`, { passportId })
|
|
519
|
+
const coverage = JSON.parse(decoder.decode(coverageBytes)) as Record<string, unknown>
|
|
520
|
+
// The cursor is not part of what the index signed and was not carried. It only has to agree with the signed final flag.
|
|
521
|
+
parts.push({ ...coverage, nextCursor: coverage.final === true ? null : 'not-carried', package: { manifest: nested, files: Object.fromEntries([...nestedFiles].map(([path, bytes]) => [path, Buffer.from(bytes).toString('base64')])) } })
|
|
522
|
+
collect(`${base}part-${at}/`, nested, nestedFiles)
|
|
523
|
+
}
|
|
524
|
+
if (parts.length === 0) refuse('package-incomplete', `The package is incomplete: it carries no part of the index's evidence for ${passportId}.`, { passportId })
|
|
525
|
+
const first = (parts[0] as { package: { manifest: EvidencePackageManifest } }).package.manifest
|
|
526
|
+
const joined = joinEvidenceExport(parts as never, { expectedPassportId: passportId, expectedSigner: signerFor(first) })
|
|
527
|
+
if (!joined.complete) refuse('index-evidence-refused', `The index's evidence for ${passportId} is refused: ${joined.problems.join('; ')}.`, { passportId, problems: joined.problems })
|
|
528
|
+
} else {
|
|
529
|
+
const { nested, nestedFiles } = read(base)
|
|
530
|
+
const inspection = inspectEvidencePackage(nested, asNumberArrays(nestedFiles), { expectedPassportId: passportId, expectedSigner: signerFor(nested) })
|
|
531
|
+
if (!inspection.structureValid || !inspection.inventoryVerified || inspection.signatureValid !== true || inspection.failures.length > 0) {
|
|
532
|
+
refuse('index-evidence-refused', `The index's evidence for ${passportId} is refused: ${inspection.failures.map((failure) => failure.detail).join('; ')}.`, { passportId, failures: inspection.failures.map((failure) => failure.reason) })
|
|
533
|
+
}
|
|
534
|
+
if (form === 'package' && !nested.completeness.snapshots.every((snapshot) => snapshot.completeForSnapshot)) refuse('records-inconsistent', `The descriptor says the index's package for ${passportId} is complete for its snapshot, and the package does not say so.`, { passportId })
|
|
535
|
+
collect(base, nested, nestedFiles)
|
|
536
|
+
// A file under the folder that the index's own manifest does not list was not vouched for by the index.
|
|
537
|
+
const extra = under.filter((path) => path !== `${base}manifest.json` && !nested.inventory.some((entry) => `${base}${entry.path}` === path))
|
|
538
|
+
if (extra.length > 0) refuse('index-evidence-refused', `The folder of the index's evidence for ${passportId} holds files its manifest does not list: ${extra.join(', ')}.`, { passportId })
|
|
539
|
+
}
|
|
540
|
+
if (custody != null) {
|
|
541
|
+
for (const path of under) {
|
|
542
|
+
const representation = listed.get(path)!.representation
|
|
543
|
+
if (ACCEPTANCE_RECORD_REPRESENTATIONS.some(format => representation === format) || (representation === APPLICATION_REPRESENTATIONS.nestedAuthority && !scopedAuthority.has(path))) {
|
|
544
|
+
refuse('index-evidence-refused', 'A nested authority label has no corresponding scoped entry in the signed index evidence.', { passportId, path })
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
// The index and the journal describe one lineage: a transaction the index holds for the passport is a state of the journal, in the same bytes.
|
|
549
|
+
for (const [txid, raw] of transactions) {
|
|
550
|
+
const state = journal.states.find((candidate) => candidate.txid === txid)
|
|
551
|
+
if (state == null || state.rawTx !== Buffer.from(raw).toString('hex')) refuse('records-inconsistent', `The index's evidence for ${passportId} holds the transaction ${txid}, which the journal does not hold in those bytes.`, { passportId, txid })
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/* --------------------------------- restore ------------------------------- */
|
|
556
|
+
|
|
557
|
+
export interface RestoreApplicationInput {
|
|
558
|
+
verified: VerifiedApplicationPackage
|
|
559
|
+
platform: Platform
|
|
560
|
+
/** The exchange's store at this deployment, whichever adapter the configuration chose, the sources it is configured with, and the folder its GS1 files are read from, as the configuration names it. */
|
|
561
|
+
epcis: { storage: EpcisExchangeStorage; sources: EpcisSourceConfig[]; artefactsDir?: string }
|
|
562
|
+
/**
|
|
563
|
+
* Whether each state is announced to this deployment's index again. True
|
|
564
|
+
* for an index that persists. An index that runs inside a development
|
|
565
|
+
* process forgets everything when that process ends, so a command line
|
|
566
|
+
* that is about to exit passes false and says so.
|
|
567
|
+
*/
|
|
568
|
+
rebuildIndex: boolean
|
|
569
|
+
now?: () => string
|
|
570
|
+
log?: (line: string) => void
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export interface RestoreReport {
|
|
574
|
+
/** The outcome for recovered records and profile files. The index also reports its own replay results. */
|
|
575
|
+
outcome: 'restored' | 'unchanged'
|
|
576
|
+
exportId: string
|
|
577
|
+
exportedAt: string
|
|
578
|
+
exporter: string
|
|
579
|
+
passports: { written: string[]; unchanged: string[] }
|
|
580
|
+
records: { brands: { written: number; unchanged: number }; offers: { written: number; unchanged: number }; claims: { written: number; unchanged: number } }
|
|
581
|
+
profiles: {
|
|
582
|
+
/** Where this deployment resolves bound profiles from. */
|
|
583
|
+
resolver: 'package' | 'bundle'
|
|
584
|
+
/** The folder the bundle was installed into, for the bundle resolver. */
|
|
585
|
+
folder?: string
|
|
586
|
+
filesWritten: number
|
|
587
|
+
filesUnchanged: number
|
|
588
|
+
/** Each carried profile as this deployment now holds it. */
|
|
589
|
+
registered: Array<{ profile: string; bindingDigest: string }>
|
|
590
|
+
/** Carried profiles this deployment does not hold after the restore, by name. */
|
|
591
|
+
notRegistered: string[]
|
|
592
|
+
}
|
|
593
|
+
epcis?: { outcome: 'restored' | 'resumed' | 'unchanged'; snapshotId: string; sourceIds: string[]; written: EpcisRestoreCounts; unchanged: EpcisRestoreCounts; relocations: number; associationsRebuilt?: number }
|
|
594
|
+
/** What became of the index's records of each passport. */
|
|
595
|
+
index: {
|
|
596
|
+
rebuilt: boolean; reason?: string; announced: number; admitted: number; duplicate: number
|
|
597
|
+
notAnnounced: Array<{ passportId: string; txid: string; answer: string; detail?: string }>
|
|
598
|
+
proofsApplied: number
|
|
599
|
+
proofsNotApplied: Array<{ passportId: string; txid: string; detail: string }>
|
|
600
|
+
}
|
|
601
|
+
/** Each passport read again here, as any reader reads it, and held against how it read where it was exported. */
|
|
602
|
+
readings: { compared: number; same: number; different: Array<{ passportId: string; differences: string[] }>; notCompared: Array<{ passportId: string; reason: string }> }
|
|
603
|
+
/** What no export carries, and so what the operator provides at this deployment before it carries on. */
|
|
604
|
+
provisionSeparately: string[]
|
|
605
|
+
/** What needs a person's attention. Empty when the restore left nothing open. */
|
|
606
|
+
attention: string[]
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** An index's admission and proof receipts belong to the deployment that supplied them. */
|
|
610
|
+
const awaitingIndex = ({ refusal: _refusal, proofPushed: _pushed, ...state }: StateEntry): StateEntry => ({ ...state, index: 'not-asked' })
|
|
611
|
+
const withoutIndexAnswers = (record: PassportRecord): unknown => ({ ...record, states: record.states.map(awaitingIndex) })
|
|
612
|
+
|
|
613
|
+
/** Where two readings differ, as short sentences. Empty when they are the same reading. */
|
|
614
|
+
function readingDifferences(exported: ExportedReading, here: ExportedReading): string[] {
|
|
615
|
+
const differences: string[] = []
|
|
616
|
+
if (JSON.stringify(exported.lineage) !== JSON.stringify(here.lineage)) differences.push('the lineage differs')
|
|
617
|
+
const names = new Set([...exported.checks, ...here.checks].map((check) => check.name))
|
|
618
|
+
for (const name of names) {
|
|
619
|
+
const a = exported.checks.find((check) => check.name === name)
|
|
620
|
+
const b = here.checks.find((check) => check.name === name)
|
|
621
|
+
if (a?.status !== b?.status || a?.reasonCode !== b?.reasonCode) differences.push(`${name}: ${a == null ? 'absent' : `${a.status}${a.reasonCode == null ? '' : ` (${a.reasonCode})`}`} where it was exported, ${b == null ? 'absent' : `${b.status}${b.reasonCode == null ? '' : ` (${b.reasonCode})`}`} here`)
|
|
622
|
+
}
|
|
623
|
+
if (exported.payloadChecks.length !== here.payloadChecks.length) differences.push(`${exported.payloadChecks.length} payload checks where it was exported, ${here.payloadChecks.length} here`)
|
|
624
|
+
exported.payloadChecks.forEach((check, at) => {
|
|
625
|
+
const other = here.payloadChecks[at]
|
|
626
|
+
if (other != null && sha256Hex(recordBytes(check)) !== sha256Hex(recordBytes(other))) differences.push(`the payload check of state ${check.stateIndex} under ${check.profile}: ${check.status}${check.cause == null ? '' : ` (${check.cause})`} where it was exported, ${other.status}${other.cause == null ? '' : ` (${other.cause})`} here, or its steps or findings differ`)
|
|
627
|
+
})
|
|
628
|
+
if (exported.chainTracker !== here.chainTracker) differences.push(`inclusion was read against ${exported.chainTracker} where it was exported and ${here.chainTracker} here`)
|
|
629
|
+
return differences
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
export async function restoreApplication(input: RestoreApplicationInput): Promise<RestoreReport> {
|
|
633
|
+
const { verified, platform } = input
|
|
634
|
+
const { manifest, descriptor, files } = verified
|
|
635
|
+
const { store, index, profiles, config } = platform
|
|
636
|
+
const log = input.log ?? (() => {})
|
|
637
|
+
const refuse = (code: string, detail: string, data: Record<string, unknown> = {}): never => {
|
|
638
|
+
throw new PortabilityRefused(code, detail, data)
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/* ---- compare with what is here, before anything is written ---- */
|
|
642
|
+
|
|
643
|
+
const collisions: Array<{ kind: string; identity: string }> = []
|
|
644
|
+
const plan = { passports: [] as PassportRecord[], passportsUnchanged: [] as string[], brands: [] as BrandRecord[], brandsUnchanged: 0, offers: [] as OfferRecord[], offersUnchanged: 0, claims: [] as ClaimRecord[], claimsUnchanged: 0 }
|
|
645
|
+
const same = (a: unknown, b: unknown): boolean => sha256Hex(recordBytes(a)) === sha256Hex(recordBytes(b))
|
|
646
|
+
for (const record of verified.journals) {
|
|
647
|
+
const held = await store.getPassport(record.passportId)
|
|
648
|
+
if (held == null) plan.passports.push(record)
|
|
649
|
+
else if (same(withoutIndexAnswers(held), withoutIndexAnswers(record))) plan.passportsUnchanged.push(record.passportId)
|
|
650
|
+
else collisions.push({ kind: 'passport', identity: record.passportId })
|
|
651
|
+
}
|
|
652
|
+
for (const brand of verified.brands) {
|
|
653
|
+
const held = await store.getBrand(brand.id)
|
|
654
|
+
if (held == null) plan.brands.push(brand)
|
|
655
|
+
else if (same(held, brand)) plan.brandsUnchanged += 1
|
|
656
|
+
else collisions.push({ kind: 'brand', identity: brand.id })
|
|
657
|
+
}
|
|
658
|
+
for (const offer of verified.offers) {
|
|
659
|
+
const held = await store.getOffer(offer.requestId)
|
|
660
|
+
if (held == null) plan.offers.push(offer)
|
|
661
|
+
else if (same(held, offer)) plan.offersUnchanged += 1
|
|
662
|
+
else collisions.push({ kind: 'offer', identity: offer.requestId })
|
|
663
|
+
}
|
|
664
|
+
for (const claim of verified.claims) {
|
|
665
|
+
const held = (await store.listClaims({ passportId: claim.passportId })).find((candidate) => candidate.id === claim.id)
|
|
666
|
+
if (held == null) plan.claims.push(claim)
|
|
667
|
+
else if (same(held, claim)) plan.claimsUnchanged += 1
|
|
668
|
+
else collisions.push({ kind: 'claim', identity: claim.id })
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// The bundle folder holds one bundle. An empty one takes this bundle; one that holds exactly this bundle is left; any other is not written over.
|
|
672
|
+
const bundleRoot = descriptor.profiles.root
|
|
673
|
+
const bundleFiles = bundleRoot == null ? [] : [...files].filter(([path]) => path.startsWith(`${bundleRoot}/`))
|
|
674
|
+
const bundleDir = config.profileBundleDir == null ? undefined : isAbsolute(config.profileBundleDir) ? config.profileBundleDir : resolve(PROJECT_ROOT, config.profileBundleDir)
|
|
675
|
+
const toInstall: Array<[string, Uint8Array]> = []
|
|
676
|
+
let bundleUnchanged = 0
|
|
677
|
+
if (bundleDir != null && bundleFiles.length > 0) {
|
|
678
|
+
const target = (path: string): string => join(bundleDir, ...path.split('/'))
|
|
679
|
+
for (const [path, bytes] of bundleFiles) {
|
|
680
|
+
if (!existsSync(target(path))) toInstall.push([path, bytes])
|
|
681
|
+
else if (sameBytes(new Uint8Array(readFileSync(target(path))), bytes)) bundleUnchanged += 1
|
|
682
|
+
else collisions.push({ kind: 'profile-bundle-file', identity: path })
|
|
683
|
+
}
|
|
684
|
+
const occupied = existsSync(join(bundleDir, ...String(bundleRoot).split('/'))) && bundleUnchanged === 0 && readdirSync(join(bundleDir, ...String(bundleRoot).split('/'))).length > 0
|
|
685
|
+
if (occupied) collisions.push({ kind: 'profile-bundle', identity: `${bundleDir} already holds another bundle` })
|
|
686
|
+
}
|
|
687
|
+
if (collisions.length > 0) {
|
|
688
|
+
refuse('reconciliation-required', `This deployment already holds ${collisions.length === 1 ? 'a record' : `${collisions.length} records`} that differ from the package's under the same identity: ${collisions.slice(0, 8).map((collision) => `${collision.kind} ${collision.identity}`).join('; ')}${collisions.length > 8 ? ` and ${collisions.length - 8} more` : ''}. Nothing was written. A restore never overwrites: decide which stands, by hand.`, { collisions })
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
/* ---- write ---- */
|
|
692
|
+
|
|
693
|
+
// The exchange first. The module compares its destination before it writes, so a refusal here has still written nothing anywhere.
|
|
694
|
+
let epcis: RestoreReport['epcis']
|
|
695
|
+
if (verified.epcis != null) {
|
|
696
|
+
const restored = await restoreEpcisRecovery({ storage: input.epcis.storage, source: epcisRecoveryFiles(files), inventory: manifest.inventory, root: verified.epcis.root, ...(input.now == null ? {} : { now: input.now }) })
|
|
697
|
+
if (!restored.ok) {
|
|
698
|
+
// Two of the module's refusals come after it began to write. Every other one is made before anything is written, here or anywhere else.
|
|
699
|
+
const begun = restored.code === 'destination-original-unverified' || restored.code === 'destination-inconsistent'
|
|
700
|
+
return refuse('epcis-refused', `The EPCIS snapshot was not restored (${restored.code}): ${restored.detail} ${begun ? 'The exchange\'s store holds part of the snapshot and says its restore is unfinished. No passport, brand, offer, claim or profile was written.' : 'Nothing was written.'}`, { code: restored.code, ...(restored.collisions == null ? {} : { collisions: restored.collisions }), ...(restored.breaches == null ? {} : { breaches: restored.breaches }) })
|
|
701
|
+
}
|
|
702
|
+
epcis = { outcome: restored.outcome, snapshotId: restored.snapshotId, sourceIds: restored.sourceIds, written: restored.written, unchanged: restored.unchanged, relocations: restored.relocations.length, ...(restored.associations == null ? {} : { associationsRebuilt: restored.associations.associationsWritten }) }
|
|
703
|
+
log(`EPCIS exchange: ${restored.outcome}; ${restored.written.imports} imports and ${restored.written.originals} originals written.`)
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// The profiles next, where this deployment resolves them from a bundle of its own. They are registered again from the folder, under this deployment's trust.
|
|
707
|
+
if (bundleDir != null && toInstall.length > 0) {
|
|
708
|
+
for (const [path, bytes] of toInstall) {
|
|
709
|
+
const target = join(bundleDir, ...path.split('/'))
|
|
710
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
711
|
+
writeFileSync(target, bytes)
|
|
712
|
+
}
|
|
713
|
+
await profiles.reload()
|
|
714
|
+
log(`Profiles: ${toInstall.length} files of the bundle installed into ${bundleDir}.`)
|
|
715
|
+
}
|
|
716
|
+
const registered: RestoreReport['profiles']['registered'] = []
|
|
717
|
+
const notRegistered: string[] = []
|
|
718
|
+
for (const carried of verified.profiles) {
|
|
719
|
+
const held = profiles.get(carried.profile)
|
|
720
|
+
if (held != null && held.bindingDigest === carried.bindingDigest) registered.push({ profile: carried.profile, bindingDigest: held.bindingDigest })
|
|
721
|
+
else notRegistered.push(carried.profile)
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
for (const brand of plan.brands) await store.saveBrand(brand)
|
|
725
|
+
const existing = new Set(plan.passportsUnchanged)
|
|
726
|
+
for (const record of input.rebuildIndex ? verified.journals : plan.passports) {
|
|
727
|
+
// An earlier restore may have copied receipts from the source. Keep a receipt on repeat
|
|
728
|
+
// only when the destination actually supplies the transaction and any acknowledged path.
|
|
729
|
+
const lineage = input.rebuildIndex && existing.has(record.passportId) ? await index.lineage(record.passportId).catch(() => []) : []
|
|
730
|
+
const atDestination = new Map(lineage.map(tx => [tx.id('hex'), tx]))
|
|
731
|
+
await store.changePassport(record.passportId, held => {
|
|
732
|
+
if (held != null && !same(withoutIndexAnswers(held), withoutIndexAnswers(record))) refuse('reconciliation-required', 'the destination journal changed during restore', { passportId: record.passportId })
|
|
733
|
+
if (held != null && !input.rebuildIndex) return held
|
|
734
|
+
const journal = held ?? record
|
|
735
|
+
return { ...journal, states: journal.states.map(state => {
|
|
736
|
+
// An interrupted draft can still require withdrawal from the original index.
|
|
737
|
+
if (isInterrupted(state)) return state
|
|
738
|
+
const tx = atDestination.get(state.txid)
|
|
739
|
+
if (tx && (state.proofPushed !== true || (state.proof != null && tx.merklePath?.toHex() === state.proof.merklePath))) return state
|
|
740
|
+
return awaitingIndex(state)
|
|
741
|
+
}) }
|
|
742
|
+
})
|
|
743
|
+
}
|
|
744
|
+
for (const offer of plan.offers) await store.saveOffer(offer)
|
|
745
|
+
for (const claim of plan.claims) await store.saveClaim(claim)
|
|
746
|
+
|
|
747
|
+
/* ---- rebuild what is derived: this deployment's index is given each state again ---- */
|
|
748
|
+
|
|
749
|
+
const indexReport: RestoreReport['index'] = { rebuilt: input.rebuildIndex, announced: 0, admitted: 0, duplicate: 0, notAnnounced: [], proofsApplied: 0, proofsNotApplied: [] }
|
|
750
|
+
if (!input.rebuildIndex) {
|
|
751
|
+
indexReport.reason = 'Connect a persistent index and run the restore again to deliver the retained states and proofs.'
|
|
752
|
+
} else {
|
|
753
|
+
for (const exported of verified.journals) {
|
|
754
|
+
const record = (await store.getPassport(exported.passportId))!
|
|
755
|
+
for (const state of record.states) {
|
|
756
|
+
// A state whose send was never answered for is the operator's to resolve. It is not announced as if it had been written.
|
|
757
|
+
if (isInterrupted(state)) {
|
|
758
|
+
indexReport.notAnnounced.push({ passportId: record.passportId, txid: state.txid, answer: 'not-announced', detail: `its journal entry says the network answer is ${state.network}` })
|
|
759
|
+
continue
|
|
760
|
+
}
|
|
761
|
+
const answer = await index.announce(Utils.toArray(state.sentBeef ?? state.beef, 'base64') as number[])
|
|
762
|
+
indexReport.announced += 1
|
|
763
|
+
const refusal = index.lastRefusal
|
|
764
|
+
const admitted = answer === 'admitted' || answer === 'duplicate'
|
|
765
|
+
if (admitted) {
|
|
766
|
+
await platform.writer.recordAnnouncement(record.passportId, state.txid, answer)
|
|
767
|
+
if (answer === 'admitted') indexReport.admitted += 1
|
|
768
|
+
else indexReport.duplicate += 1
|
|
769
|
+
} else {
|
|
770
|
+
await store.changePassport(record.passportId, latest => {
|
|
771
|
+
const entry = latest?.states.find(item => item.txid === state.txid)
|
|
772
|
+
if (entry != null && entry.index === state.index && entry.refusal === state.refusal) Object.assign(entry, { index: answer, refusal })
|
|
773
|
+
return latest
|
|
774
|
+
})
|
|
775
|
+
indexReport.notAnnounced.push({ passportId: record.passportId, txid: state.txid, answer, ...(refusal == null ? {} : { detail: refusal }) })
|
|
776
|
+
break
|
|
777
|
+
}
|
|
778
|
+
const proof = state.proof
|
|
779
|
+
if (proof != null) {
|
|
780
|
+
const pushed = await index.pushProof(state.txid, MerklePath.fromHex(proof.merklePath))
|
|
781
|
+
await store.changePassport(record.passportId, latest => {
|
|
782
|
+
const entry = latest?.states.find(item => item.txid === state.txid)
|
|
783
|
+
if (entry?.proof?.merklePath === proof.merklePath) {
|
|
784
|
+
if (pushed.ok) entry.proofPushed = true
|
|
785
|
+
else if (entry.proofPushed === state.proofPushed) delete entry.proofPushed
|
|
786
|
+
}
|
|
787
|
+
return latest
|
|
788
|
+
})
|
|
789
|
+
if (pushed.ok) indexReport.proofsApplied += 1
|
|
790
|
+
else indexReport.proofsNotApplied.push({ passportId: record.passportId, txid: state.txid, detail: pushed.detail })
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
/* ---- read each passport here, and hold it against how it read where it was exported ---- */
|
|
797
|
+
|
|
798
|
+
const readings: RestoreReport['readings'] = { compared: 0, same: 0, different: [], notCompared: [] }
|
|
799
|
+
for (const record of verified.journals) {
|
|
800
|
+
const exported = verified.readings.get(record.passportId)
|
|
801
|
+
if (exported == null) {
|
|
802
|
+
readings.notCompared.push({ passportId: record.passportId, reason: 'the package carries no reading of it' })
|
|
803
|
+
continue
|
|
804
|
+
}
|
|
805
|
+
if (!input.rebuildIndex) {
|
|
806
|
+
readings.notCompared.push({ passportId: record.passportId, reason: 'this deployment\'s index was not given its states' })
|
|
807
|
+
continue
|
|
808
|
+
}
|
|
809
|
+
let here: ExportedReading
|
|
810
|
+
try {
|
|
811
|
+
here = summariseReading(await platform.read(record.passportId), platform.chainTracker)
|
|
812
|
+
} catch (cause) {
|
|
813
|
+
readings.notCompared.push({ passportId: record.passportId, reason: cause instanceof Error ? cause.message : String(cause) })
|
|
814
|
+
continue
|
|
815
|
+
}
|
|
816
|
+
readings.compared += 1
|
|
817
|
+
const differences = readingDifferences(exported, here)
|
|
818
|
+
if (differences.length === 0) readings.same += 1
|
|
819
|
+
else readings.different.push({ passportId: record.passportId, differences })
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/* ---- what is the operator's to provide, and what needs attention ---- */
|
|
823
|
+
|
|
824
|
+
const gs1 = verifyGs1Artefacts(input.epcis.artefactsDir == null ? {} : { dir: isAbsolute(input.epcis.artefactsDir) ? input.epcis.artefactsDir : resolve(PROJECT_ROOT, input.epcis.artefactsDir) })
|
|
825
|
+
const provisionSeparately = [
|
|
826
|
+
'The wallet\'s root key and file, by the wallet\'s own recovery, and BRAND_ROOT_SECRET and MANAGED_IDENTITY_SECRET as they were: without them this deployment reads every passport and can write none of them.',
|
|
827
|
+
'The index: its address and this application\'s tokens (npm run connect-index or go-live), and the index must admit this application\'s publisher key.',
|
|
828
|
+
'Sign-in accounts and the membership of each brand.',
|
|
829
|
+
...(descriptor.epcis.sources ?? []).map((source) => {
|
|
830
|
+
const configured = input.epcis.sources.find((candidate) => candidate.sourceId === source.sourceId)
|
|
831
|
+
const credential = !source.credentialConfigured ? 'It had no credential.' : configured?.credentials != null ? 'Its credential is configured here.' : `Its ${source.credentialScheme ?? ''} credential is not configured here: set it before a pull.`
|
|
832
|
+
return `The EPCIS source ${source.sourceId}: ${configured == null ? `it is not configured here. It was reached at ${source.baseUrl}.` : configured.baseUrl === source.baseUrl ? 'it is configured here at the address it had.' : `it is configured here at another address than ${source.baseUrl}: declare the move (npm run epcis-remap -- --source ${source.sourceId}) before a pull.`} ${credential}`
|
|
833
|
+
}),
|
|
834
|
+
gs1.ok ? `The GS1 files for EPCIS validation are present in ${gs1.dir}.` : `The GS1 files for EPCIS validation are not in ${gs1.dir}: this deployment obtains them from GS1 at start, or the operator places them. Until then every import and pull is refused.`,
|
|
835
|
+
]
|
|
836
|
+
const attention: string[] = []
|
|
837
|
+
if (Array.isArray(manifest.profiles) && manifest.profiles.includes(MANAGED_CUSTODY_EXPORT_PROFILE)) {
|
|
838
|
+
for (const reference of manifest.completeness.absent) {
|
|
839
|
+
if (reference.startsWith('acceptance:sha256:')) attention.push(`The signed acceptance for a completed transfer identified by ${reference} was unavailable at recovery.`)
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
if (notRegistered.length > 0) attention.push(`This deployment does not hold ${notRegistered.join(', ')} under the binding the records declare. ${bundleDir == null ? 'It resolves profiles from the installed package and its own folders: set PROFILE_BUNDLE_DIR to resolve them from the package\'s bundle, or add the profile\'s folder and trust its digest.' : 'Its trusted digests do not admit the bundle\'s binding.'} Until then those passports read as "not checked" and cannot be written.`)
|
|
843
|
+
for (const entry of indexReport.notAnnounced) attention.push(`The state ${entry.txid} of ${entry.passportId} was not taken by this deployment's index: ${entry.answer}${entry.detail == null ? '' : ` (${entry.detail})`}.`)
|
|
844
|
+
for (const entry of indexReport.proofsNotApplied) attention.push(`The index has yet to acknowledge the proof for ${entry.txid} of ${entry.passportId} (${entry.detail}). The worker will retry it.`)
|
|
845
|
+
for (const entry of readings.different) attention.push(`${entry.passportId} reads differently here: ${entry.differences.join('; ')}.`)
|
|
846
|
+
if (!gs1.ok) attention.push('The GS1 files are not provisioned here yet.')
|
|
847
|
+
|
|
848
|
+
const wrote = plan.passports.length + plan.brands.length + plan.offers.length + plan.claims.length + toInstall.length > 0 || (epcis != null && epcis.outcome !== 'unchanged')
|
|
849
|
+
return {
|
|
850
|
+
outcome: wrote ? 'restored' : 'unchanged',
|
|
851
|
+
exportId: descriptor.exportId,
|
|
852
|
+
exportedAt: descriptor.exportedAt,
|
|
853
|
+
exporter: manifest.exporter.id,
|
|
854
|
+
passports: { written: plan.passports.map((record) => record.passportId), unchanged: plan.passportsUnchanged },
|
|
855
|
+
records: { brands: { written: plan.brands.length, unchanged: plan.brandsUnchanged }, offers: { written: plan.offers.length, unchanged: plan.offersUnchanged }, claims: { written: plan.claims.length, unchanged: plan.claimsUnchanged } },
|
|
856
|
+
profiles: { resolver: profiles.source, ...(bundleDir == null ? {} : { folder: bundleDir }), filesWritten: toInstall.length, filesUnchanged: bundleUnchanged, registered, notRegistered },
|
|
857
|
+
...(epcis == null ? {} : { epcis }),
|
|
858
|
+
index: indexReport,
|
|
859
|
+
readings,
|
|
860
|
+
provisionSeparately,
|
|
861
|
+
attention,
|
|
862
|
+
}
|
|
863
|
+
}
|