@midnightntwrk/midnight-js-protocol 0.0.0-stage → 5.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +291 -2
- package/dist/compact-js-v8-effect.d.ts +1 -0
- package/dist/compact-js-v8-effect.js +2 -0
- package/dist/compact-js-v8-effect.js.map +1 -0
- package/dist/engine.d.ts +420 -0
- package/dist/engine.js +832 -0
- package/dist/engine.js.map +1 -0
- package/dist/errors.d.ts +601 -0
- package/dist/errors.js +810 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +1471 -0
- package/dist/index.js +799 -0
- package/dist/index.js.map +1 -0
- package/dist/platform-effect-configuration.d.ts +1 -0
- package/dist/platform-effect-configuration.js +2 -0
- package/dist/platform-effect-configuration.js.map +1 -0
- package/dist/platform-effect-contract-address.d.ts +1 -0
- package/dist/platform-effect-contract-address.js +2 -0
- package/dist/platform-effect-contract-address.js.map +1 -0
- package/dist/platform.d.ts +1 -0
- package/dist/platform.js +2 -0
- package/dist/platform.js.map +1 -0
- package/dist/prove.d.ts +45 -0
- package/dist/prove.js +61 -0
- package/dist/prove.js.map +1 -0
- package/dist/shared/compose-options-BFA09u9q.js +468 -0
- package/dist/shared/compose-options-BFA09u9q.js.map +1 -0
- package/dist/shared/ledger-transaction-DQP8J8tv.js +134 -0
- package/dist/shared/ledger-transaction-DQP8J8tv.js.map +1 -0
- package/dist/shared/load-BMVWoBo6.js +49 -0
- package/dist/shared/load-BMVWoBo6.js.map +1 -0
- package/dist/shared/transaction-tags-I3J_Hh8r.js +82 -0
- package/dist/shared/transaction-tags-I3J_Hh8r.js.map +1 -0
- package/dist/transaction.d.ts +92 -0
- package/dist/transaction.js +6 -0
- package/dist/transaction.js.map +1 -0
- package/dist/v8.d.ts +1 -0
- package/dist/v8.js +3 -0
- package/dist/v8.js.map +1 -0
- package/dist/v9-compact-js-effect-contract.d.ts +1 -0
- package/dist/v9-compact-js-effect-contract.js +2 -0
- package/dist/v9-compact-js-effect-contract.js.map +1 -0
- package/dist/v9-compact-js-effect.d.ts +1 -0
- package/dist/v9-compact-js-effect.js +2 -0
- package/dist/v9-compact-js-effect.js.map +1 -0
- package/dist/v9-compact-js.d.ts +1 -0
- package/dist/v9-compact-js.js +2 -0
- package/dist/v9-compact-js.js.map +1 -0
- package/dist/v9-compact-runtime.d.ts +1 -0
- package/dist/v9-compact-runtime.js +2 -0
- package/dist/v9-compact-runtime.js.map +1 -0
- package/dist/v9-onchain-runtime.d.ts +1 -0
- package/dist/v9-onchain-runtime.js +2 -0
- package/dist/v9-onchain-runtime.js.map +1 -0
- package/dist/v9.d.ts +1 -0
- package/dist/v9.js +2 -0
- package/dist/v9.js.map +1 -0
- package/dist/version.d.ts +173 -0
- package/dist/version.js +125 -0
- package/dist/version.js.map +1 -0
- package/package.json +122 -3
package/dist/engine.js
ADDED
|
@@ -0,0 +1,832 @@
|
|
|
1
|
+
import * as ledgerV9 from '@midnightntwrk/ledger-v9';
|
|
2
|
+
import { ComposeOptionError, findCodedCause, ContractExecutionError, ComposeFailedError, InvalidArgumentError, StateConversionFailedError, InvariantViolationError, MaintenanceAuthorityMismatchError, NO_CIRCUIT } from './errors.js';
|
|
3
|
+
import { a as assembleCallPrototype, i as isContractBalance, d as describeValue, b as assertComposeEnvelope } from './shared/compose-options-BFA09u9q.js';
|
|
4
|
+
import * as Contract from '@midnight-ntwrk/compact-js/effect/Contract';
|
|
5
|
+
import * as ContractConfigurationError from '@midnight-ntwrk/compact-js/effect/ContractConfigurationError';
|
|
6
|
+
import { ContractExecutable, CompiledContract, ZKConfiguration, ZKConfigurationReadError, Ledger } from '@midnight-ntwrk/compact-js/v8/effect';
|
|
7
|
+
import * as CoinPublicKey from '@midnight-ntwrk/platform-js/effect/CoinPublicKey';
|
|
8
|
+
import * as Configuration from '@midnight-ntwrk/platform-js/effect/Configuration';
|
|
9
|
+
import * as PlatformContractAddress from '@midnight-ntwrk/platform-js/effect/ContractAddress';
|
|
10
|
+
import * as SigningKey from '@midnight-ntwrk/platform-js/effect/SigningKey';
|
|
11
|
+
import * as glue from 'compact-runtime-ledger8';
|
|
12
|
+
import { Effect, Layer, Exit, Cause, Option, Clock } from 'effect';
|
|
13
|
+
import '@midnight-ntwrk/compact-js';
|
|
14
|
+
|
|
15
|
+
/*
|
|
16
|
+
* This file is part of midnight-js.
|
|
17
|
+
* Copyright (C) Midnight Foundation
|
|
18
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
19
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
20
|
+
* You may not use this file except in compliance with the License.
|
|
21
|
+
* You may obtain a copy of the License at
|
|
22
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
23
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
24
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
25
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
26
|
+
* See the License for the specific language governing permissions and
|
|
27
|
+
* limitations under the License.
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* Re-expresses a ledger 8 contract's entry points as a ledger 9 contract state.
|
|
31
|
+
*
|
|
32
|
+
* What crosses the era boundary here is the OPERATION REGISTRY, not the state. The primary state is
|
|
33
|
+
* deliberately left at its default: a caller that needs the state itself reads it from
|
|
34
|
+
* {@link ContractStatePojo.state}.
|
|
35
|
+
*
|
|
36
|
+
* @param entryPoints The entry points a ledger 8 contract state declared, as the ledger 8
|
|
37
|
+
* decoder read them.
|
|
38
|
+
* @returns The serialized ledger 9 contract state, carrying those entry points and their keys.
|
|
39
|
+
* @throws ComposeOptionError if no entry point carries a key.
|
|
40
|
+
* @see {@link CrossEraOperationRegistry} for why re-expressing the operations is faithful rather
|
|
41
|
+
* than a substitution, and why the empty registry is refused here rather than one layer down.
|
|
42
|
+
*/
|
|
43
|
+
const reexpressOperationsForLedger9 = (entryPoints) => {
|
|
44
|
+
const state = new ledgerV9.ContractState();
|
|
45
|
+
let registered = 0;
|
|
46
|
+
for (const entryPoint of entryPoints) {
|
|
47
|
+
// A blank slot is carried as `undefined` rather than as empty bytes -- see the fail-closed
|
|
48
|
+
// decoding note on ContractEntryPointPojo. Skipped rather than refused one by one: if the
|
|
49
|
+
// circuit being called is the one missing a key, the composer names it precisely, and a
|
|
50
|
+
// contract may legitimately declare an entry point this call does not touch.
|
|
51
|
+
if (entryPoint.verifierKey === undefined) {
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const operation = new ledgerV9.ContractOperation();
|
|
55
|
+
operation.verifierKey = entryPoint.verifierKey;
|
|
56
|
+
state.setOperation(entryPoint.circuitId, operation);
|
|
57
|
+
registered += 1;
|
|
58
|
+
}
|
|
59
|
+
if (registered === 0) {
|
|
60
|
+
throw new ComposeOptionError('v9', 'contractStateBytes');
|
|
61
|
+
}
|
|
62
|
+
return state.serialize();
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/*
|
|
66
|
+
* This file is part of midnight-js.
|
|
67
|
+
* Copyright (C) Midnight Foundation
|
|
68
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
69
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
70
|
+
* You may not use this file except in compliance with the License.
|
|
71
|
+
* You may obtain a copy of the License at
|
|
72
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
73
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
74
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
75
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
76
|
+
* See the License for the specific language governing permissions and
|
|
77
|
+
* limitations under the License.
|
|
78
|
+
*/
|
|
79
|
+
/**
|
|
80
|
+
* Wraps a {@link TranscriptPojo} — the output of {@link runLedger8Circuit}
|
|
81
|
+
* (`../v8/executable.ts`) — into a v9-native `ContractCallPrototype`, ready for
|
|
82
|
+
* `Intent.new(ttl).addCall(...)`, via {@link assembleCallPrototype}
|
|
83
|
+
* (`./assemble-call.ts`) against the ledger-v9 module.
|
|
84
|
+
*
|
|
85
|
+
* `options.contractState` is the migrated, post-fork v9 `ContractState` —
|
|
86
|
+
* read from chain, or otherwise carrying the contract's real registered
|
|
87
|
+
* operations. It must already carry the operation for the circuit: a
|
|
88
|
+
* keep-state call registers no new verifier key.
|
|
89
|
+
*
|
|
90
|
+
* @param options The transcript to wrap, the contract's address, and the
|
|
91
|
+
* migrated post-fork state to resolve the circuit's operation against.
|
|
92
|
+
* @returns The v9-native call prototype.
|
|
93
|
+
* @throws ComposeFailedError at stage `'wrap-call'` if `contractState`
|
|
94
|
+
* registers no operation for the circuit, and at `'call-verifier-key'` if the
|
|
95
|
+
* registered operation carries no verifier key — rather than falling back to a
|
|
96
|
+
* blank, unverifiable operation.
|
|
97
|
+
* @see {@link RetainedEraExecution}
|
|
98
|
+
*/
|
|
99
|
+
const wrapKeepStateCall = (options) => {
|
|
100
|
+
const { transcript, contractAddress, contractState, ledgerParametersBytes } = options;
|
|
101
|
+
const { prototype } = assembleCallPrototype(ledgerV9, {
|
|
102
|
+
circuitId: transcript.circuitId,
|
|
103
|
+
contractAddress,
|
|
104
|
+
// The retained execution leg partitions nothing: it always submits the raw
|
|
105
|
+
// op sequence as `'unpartitioned'` -- see RetainedEraExecution.
|
|
106
|
+
transcript: {
|
|
107
|
+
kind: 'unpartitioned',
|
|
108
|
+
preState: transcript.preContractState.encode(),
|
|
109
|
+
publicTranscript: transcript.publicTranscript,
|
|
110
|
+
partitionContext: transcript.partitionContext
|
|
111
|
+
},
|
|
112
|
+
privateTranscriptOutputs: transcript.privateTranscriptOutputs,
|
|
113
|
+
input: transcript.input,
|
|
114
|
+
output: transcript.output,
|
|
115
|
+
operations: contractState,
|
|
116
|
+
ledgerParametersBytes,
|
|
117
|
+
stage: 'wrap-call',
|
|
118
|
+
version: 'v9'
|
|
119
|
+
});
|
|
120
|
+
return prototype;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
/*
|
|
124
|
+
* This file is part of midnight-js.
|
|
125
|
+
* Copyright (C) Midnight Foundation
|
|
126
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
127
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
128
|
+
* You may not use this file except in compliance with the License.
|
|
129
|
+
* You may obtain a copy of the License at
|
|
130
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
131
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
132
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
133
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
134
|
+
* See the License for the specific language governing permissions and
|
|
135
|
+
* limitations under the License.
|
|
136
|
+
*/
|
|
137
|
+
/**
|
|
138
|
+
* Retained-era (ledger 8) execution, on compact-js's own era-pinned entries.
|
|
139
|
+
*
|
|
140
|
+
* This module replaced a hand-maintained execution layer — `execute.ts`, which
|
|
141
|
+
* drove `compact-runtime@0.16` directly, and `down-convert.ts`, which built the
|
|
142
|
+
* state it ran against. Both are gone; see
|
|
143
|
+
* `docs/adr/0015-retained-era-execution-on-compact-js.md` for why.
|
|
144
|
+
*
|
|
145
|
+
* Everything crossing this module's surface is PLAIN DATA or an era-tagged
|
|
146
|
+
* handle the caller already holds. No `Effect` value leaves it: the effects
|
|
147
|
+
* compact-js returns are discharged here with `Effect.runPromise`, which is
|
|
148
|
+
* also why every entry point is asynchronous — `ContractExecutable` builds its
|
|
149
|
+
* work on `Effect.tryPromise`, so `runSync` cannot discharge it.
|
|
150
|
+
*
|
|
151
|
+
* @see {@link RetainedEraExecution}
|
|
152
|
+
*/
|
|
153
|
+
/**
|
|
154
|
+
* The shape the retained runtime reads a signing key in: 32 bytes written in
|
|
155
|
+
* hex, either case.
|
|
156
|
+
*
|
|
157
|
+
* MEASURED against the pinned runtime rather than guessed. `sampleSigningKey()`
|
|
158
|
+
* answers 64 lowercase hex characters; an uppercase key of the same length is
|
|
159
|
+
* accepted, a shorter or longer one fails with `failed to fill whole buffer`
|
|
160
|
+
* and a non-hex one with `Invalid character 'z' at position 0`. The value being
|
|
161
|
+
* a valid Schnorr scalar is a cryptographic property this cannot check, and the
|
|
162
|
+
* runtime's own `Malformed Schnorr signing key` already names it.
|
|
163
|
+
*/
|
|
164
|
+
const LEDGER8_SIGNING_KEY_PATTERN = /^[0-9a-fA-F]{64}$/;
|
|
165
|
+
/**
|
|
166
|
+
* The signature kind this era's maintenance authority accepts.
|
|
167
|
+
*
|
|
168
|
+
* MEASURED, not chosen: the era reports `supportsCmaSignatureKind` as
|
|
169
|
+
* `schnorr=true, ecdsa=false`, and `Ledger.fromPlatformSigningKey` answers
|
|
170
|
+
* `Left(ContractConfigurationError)` for an ecdsa key. Naming it here keeps the
|
|
171
|
+
* bare hex string this era's callers hold assignable to platform-js's tagged
|
|
172
|
+
* `SigningKey`, which is what `Configuration.Keys` serves.
|
|
173
|
+
*/
|
|
174
|
+
const LEDGER8_SIGNATURE_KIND = 'schnorr';
|
|
175
|
+
/** A retained-era key as the tagged `SigningKey` compact-js reads. */
|
|
176
|
+
const toPlatformSigningKey = (signingKey) => SigningKey.make(signingKey, LEDGER8_SIGNATURE_KIND);
|
|
177
|
+
/**
|
|
178
|
+
* The tag compact-js reports a retained contract under.
|
|
179
|
+
*
|
|
180
|
+
* It reaches nothing but error messages: the container's tag is chosen by
|
|
181
|
+
* whoever builds it, and this era's callers pass an instance that carries no
|
|
182
|
+
* name of its own.
|
|
183
|
+
*/
|
|
184
|
+
const LEDGER8_CONTRACT_TAG = 'ledger8-contract';
|
|
185
|
+
/**
|
|
186
|
+
* Wraps a constructed retained contract in the container compact-js executes.
|
|
187
|
+
*
|
|
188
|
+
* `ContractExecutable` resolves the contract through `new ctor(witnesses)`, so
|
|
189
|
+
* it needs a constructor. The caller has an instance, and its witnesses are
|
|
190
|
+
* already bound to it — so the constructor hands that same instance back and
|
|
191
|
+
* the witnesses arrive with it. Returning an object from a constructor is
|
|
192
|
+
* ordinary JavaScript; the assertion is needed only because TypeScript types a
|
|
193
|
+
* class expression by its declaration rather than by what it returns.
|
|
194
|
+
*
|
|
195
|
+
* Reusing one instance across calls is what this era already did before
|
|
196
|
+
* compact-js served it, so this is the existing lifetime, not a new one.
|
|
197
|
+
*
|
|
198
|
+
* The compiled-assets path is a placeholder: it is read only by compact-js's
|
|
199
|
+
* own `ZKConfiguration` reader, and {@link zkConfigurationLayer} replaces that
|
|
200
|
+
* service outright, so nothing ever resolves it.
|
|
201
|
+
*/
|
|
202
|
+
const containerFor = (contract) => CompiledContract.make(LEDGER8_CONTRACT_TAG,
|
|
203
|
+
// The single assertion this adapter needs, and it is here rather than at any
|
|
204
|
+
// caller. A retained artifact satisfies compact-js's `Contract` structurally
|
|
205
|
+
// -- same four circuit maps, and a synchronous `initialState` satisfies its
|
|
206
|
+
// `Awaitable` return -- but the two declare their members over different
|
|
207
|
+
// private-state parameters, so TypeScript will not see it. Narrowing what
|
|
208
|
+
// this module ASKS for (see `Ledger8EngineContract`) is what keeps the assertion
|
|
209
|
+
// to one line instead of pushing a cast onto every consumer.
|
|
210
|
+
class {
|
|
211
|
+
constructor() {
|
|
212
|
+
return contract;
|
|
213
|
+
}
|
|
214
|
+
}).pipe(CompiledContract.withVacantWitnesses, CompiledContract.withCompiledFileAssets('.'));
|
|
215
|
+
/**
|
|
216
|
+
* Serves the coin public key and signing key compact-js reads off
|
|
217
|
+
* `Configuration.Keys`.
|
|
218
|
+
*
|
|
219
|
+
* Built with `Layer.succeed` over the values the caller already holds, rather
|
|
220
|
+
* than through platform-js's own `Configuration.layer`, which sources them from
|
|
221
|
+
* a `ConfigProvider`. The service is a plain `Context.Tag` with two members, so
|
|
222
|
+
* there is nothing a config round trip would add except a second place for the
|
|
223
|
+
* values to disagree.
|
|
224
|
+
*/
|
|
225
|
+
const keysLayer = (coinPk, signingKey) => Layer.succeed(Configuration.Keys, Configuration.Keys.of({
|
|
226
|
+
coinPublicKey: CoinPublicKey.make(coinPk),
|
|
227
|
+
getSigningKey: () => signingKey === undefined
|
|
228
|
+
? Option.none()
|
|
229
|
+
: Option.some(toPlatformSigningKey(signingKey))
|
|
230
|
+
}));
|
|
231
|
+
/**
|
|
232
|
+
* Pins the execution clock, or leaves the ambient one in place.
|
|
233
|
+
*
|
|
234
|
+
* `Effect.withClock`, NOT a `Layer` over `Clock.Clock`. The clock is one of
|
|
235
|
+
* Effect's DEFAULT services: it lives on the fiber rather than in the context,
|
|
236
|
+
* so providing a layer for it type-checks, runs, and is silently ignored — the
|
|
237
|
+
* wall clock still wins. That was measured here, by a test that asserted a
|
|
238
|
+
* pinned second and got `Date.now()`.
|
|
239
|
+
*
|
|
240
|
+
* Only `currentTimeMillis` and its unsafe twin reach an execution — compact-js
|
|
241
|
+
* converts to seconds at the call site — but the whole interface is pinned so a
|
|
242
|
+
* future read cannot quietly fall back to the wall clock.
|
|
243
|
+
*/
|
|
244
|
+
const pinnedClock = (nowSeconds) => {
|
|
245
|
+
// BEFORE the rounding, because `Math.round` carries `NaN` and both infinities
|
|
246
|
+
// straight through to `BigInt(millis)`, which refuses them with a bare
|
|
247
|
+
// `RangeError` naming neither the option nor the era. `nowSeconds` is a plain
|
|
248
|
+
// `number` on the published option, and `Number(process.env.X)` with the
|
|
249
|
+
// variable unset is the obvious way to produce one.
|
|
250
|
+
if (!Number.isFinite(nowSeconds)) {
|
|
251
|
+
throw new InvalidArgumentError(`the ledger 8 runtime cannot pin its execution clock to '${String(nowSeconds)}'. ` +
|
|
252
|
+
'`nowSeconds` must be a finite number of seconds since the epoch.');
|
|
253
|
+
}
|
|
254
|
+
// ROUNDED, not used raw. `nowSeconds` is a plain `number` on the published
|
|
255
|
+
// option and `Date.now() / 1000` -- the expression a consumer reaches for --
|
|
256
|
+
// is fractional, which makes `BigInt(millis)` throw `RangeError: ... not an
|
|
257
|
+
// integer` from inside the clock builder, naming neither the option nor the
|
|
258
|
+
// era. The millisecond is the finest unit this interface carries and
|
|
259
|
+
// compact-js divides it back down to seconds, so rounding loses nothing an
|
|
260
|
+
// execution can observe.
|
|
261
|
+
const millis = Math.round(nowSeconds * 1_000);
|
|
262
|
+
const nanos = BigInt(millis) * 1000000n;
|
|
263
|
+
// `Object.assign` onto the real clock, NOT a spread of it. `Clock.make()`
|
|
264
|
+
// returns a class instance whose `sleep` and `scheduler` live on the
|
|
265
|
+
// prototype; a spread copies own enumerable properties only and silently
|
|
266
|
+
// drops both, leaving a `Clock` that throws `clock.sleep is not a function`
|
|
267
|
+
// the first time anything schedules work. TypeScript cannot see it, because a
|
|
268
|
+
// spread type keeps the declared members.
|
|
269
|
+
return Object.assign(Clock.make(), {
|
|
270
|
+
unsafeCurrentTimeMillis: () => millis,
|
|
271
|
+
currentTimeMillis: Effect.succeed(millis),
|
|
272
|
+
unsafeCurrentTimeNanos: () => nanos,
|
|
273
|
+
currentTimeNanos: Effect.succeed(nanos)
|
|
274
|
+
});
|
|
275
|
+
};
|
|
276
|
+
const withPinnedClock = (nowSeconds, effect) => nowSeconds === undefined ? effect : Effect.withClock(pinnedClock(nowSeconds))(effect);
|
|
277
|
+
/**
|
|
278
|
+
* Adapts a {@link VerifierKeyReader} into the service compact-js's
|
|
279
|
+
* `initialize` reads keys through.
|
|
280
|
+
*
|
|
281
|
+
* A key the reader does not answer for becomes `Option.none()`, and compact-js
|
|
282
|
+
* REFUSES it: `initialize` fails with a `ContractConfigurationError` naming the
|
|
283
|
+
* circuit. That is measured, not assumed, and it is stricter than the leg this
|
|
284
|
+
* replaced — a retained-era constructor used to leave every slot blank and the
|
|
285
|
+
* deploy composition was the only thing that checked coverage. It now fails
|
|
286
|
+
* before a state is built at all.
|
|
287
|
+
*/
|
|
288
|
+
const zkConfigurationLayer = (read) => Layer.succeed(ZKConfiguration.ZKConfiguration, ZKConfiguration.ZKConfiguration.of({
|
|
289
|
+
createReader: (compiledContract) => Effect.sync(() => {
|
|
290
|
+
const getVerifierKey = (provableCircuitId) => Effect.tryPromise({
|
|
291
|
+
try: () => read(provableCircuitId).then((key) => key === undefined ? Option.none() : Option.some(Contract.VerifierKey(key))),
|
|
292
|
+
catch: (cause) => ZKConfigurationReadError.make(compiledContract.tag, provableCircuitId, 'verifier-key', cause)
|
|
293
|
+
});
|
|
294
|
+
return {
|
|
295
|
+
getVerifierKey,
|
|
296
|
+
getVerifierKeys: (provableCircuitIds) => Effect.forEach(provableCircuitIds, (provableCircuitId) => getVerifierKey(provableCircuitId).pipe(Effect.map((verifierKey) => [provableCircuitId, verifierKey])), { concurrency: 'unbounded', discard: false })
|
|
297
|
+
};
|
|
298
|
+
})
|
|
299
|
+
}));
|
|
300
|
+
/**
|
|
301
|
+
* The verifier-key reader a CIRCUIT call or a MAINTENANCE update is given.
|
|
302
|
+
*
|
|
303
|
+
* `ContractExecutable` declares `ZKConfiguration` in its context for every
|
|
304
|
+
* method, but only `initialize` reads a key — a circuit call needs none, and a
|
|
305
|
+
* maintenance update is handed the key it inserts, which is measured, not
|
|
306
|
+
* assumed. Providing a reader that refuses keeps that fact enforced: were a
|
|
307
|
+
* future version to read a key there, this fails by name instead of silently
|
|
308
|
+
* serving `Option.none()` and composing a transaction with a blank key slot.
|
|
309
|
+
*/
|
|
310
|
+
const refuseVerifierKeyRead = (provableCircuitId) => Promise.reject(new InvariantViolationError(`a ledger 8 circuit call or maintenance update read the verifier key for '${provableCircuitId}'. ` +
|
|
311
|
+
'Only deployment is supposed to read ZK configuration.'));
|
|
312
|
+
/**
|
|
313
|
+
* Structural equality over the `EncodedStateValue` algebra -- plain objects,
|
|
314
|
+
* arrays, `Map`s, `Uint8Array`s and primitives.
|
|
315
|
+
*
|
|
316
|
+
* `Map`s are compared pairwise in iteration order, deliberately, and that order
|
|
317
|
+
* is not ascending by key -- do not reason about it as sorted. The
|
|
318
|
+
* order-sensitivity is what makes {@link decodeExecutableStateValue}'s
|
|
319
|
+
* comparison exact; a `get()`-based rewrite would silently drop it.
|
|
320
|
+
*
|
|
321
|
+
* @param a One value in the algebra.
|
|
322
|
+
* @param b The value to compare it against.
|
|
323
|
+
* @returns `true` when the two are structurally equal.
|
|
324
|
+
*/
|
|
325
|
+
const structurallyEqual = (a, b) => {
|
|
326
|
+
if (a === b) {
|
|
327
|
+
return true;
|
|
328
|
+
}
|
|
329
|
+
if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
|
|
330
|
+
return false;
|
|
331
|
+
}
|
|
332
|
+
if (a instanceof Uint8Array || b instanceof Uint8Array) {
|
|
333
|
+
return (a instanceof Uint8Array && b instanceof Uint8Array && a.length === b.length && a.every((byte, i) => byte === b[i]));
|
|
334
|
+
}
|
|
335
|
+
if (a instanceof Map || b instanceof Map) {
|
|
336
|
+
if (!(a instanceof Map) || !(b instanceof Map) || a.size !== b.size) {
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
const bEntries = Array.from(b);
|
|
340
|
+
return Array.from(a).every(([key, value], i) => {
|
|
341
|
+
const bEntry = bEntries[i];
|
|
342
|
+
return bEntry !== undefined && structurallyEqual(key, bEntry[0]) && structurallyEqual(value, bEntry[1]);
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
346
|
+
return (Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((item, i) => structurallyEqual(item, b[i])));
|
|
347
|
+
}
|
|
348
|
+
const aRecord = { ...a };
|
|
349
|
+
const bRecord = { ...b };
|
|
350
|
+
const aKeys = Object.keys(aRecord);
|
|
351
|
+
// `key in bRecord`, not just a matching key count: looking each of a's keys
|
|
352
|
+
// up in b without checking it exists reads `undefined` on both sides and
|
|
353
|
+
// short-circuits to equal.
|
|
354
|
+
return (aKeys.length === Object.keys(bRecord).length &&
|
|
355
|
+
aKeys.every((key) => key in bRecord && structurallyEqual(aRecord[key], bRecord[key])));
|
|
356
|
+
};
|
|
357
|
+
/**
|
|
358
|
+
* Decodes the primary state a circuit executes against, refusing a value that
|
|
359
|
+
* does not re-encode to the bytes it came from.
|
|
360
|
+
*
|
|
361
|
+
* The comparison is CROSS-CODEC in production, which is what it is for. A
|
|
362
|
+
* contract the fork translated carries a current-era envelope,
|
|
363
|
+
* so the pipeline reads it with the HEAD era's reader
|
|
364
|
+
* (`readLedger8Snapshot`) -- the state is then encoded by ledger-v9 and
|
|
365
|
+
* decoded here by the retained runtime. A retained-era envelope is encoded by
|
|
366
|
+
* ledger-v8 and decoded by the same retained runtime, which is still a
|
|
367
|
+
* different physical copy. Either way a shape one side writes and the other
|
|
368
|
+
* merely tolerates would decode without complaint and execute a circuit
|
|
369
|
+
* against a state that is not the chain's, with every guard green.
|
|
370
|
+
*
|
|
371
|
+
* Reachable with the REAL decoder, not only an injected one: `runLedger8Circuit` takes a
|
|
372
|
+
* bare {@link EncodedStateValue} a caller can assemble by hand, and the
|
|
373
|
+
* retained runtime canonicalises map order and drops members it does not
|
|
374
|
+
* declare. Both are refused here rather than executed on.
|
|
375
|
+
*
|
|
376
|
+
* @param state The era-neutral encoded primary state.
|
|
377
|
+
* @returns The decoded state value.
|
|
378
|
+
* @throws StateConversionFailedError at stage `'state conversion'` when the
|
|
379
|
+
* decoded value does not re-encode to its source, with the mismatch on
|
|
380
|
+
* `cause`.
|
|
381
|
+
* @see {@link RetainedEraExecution}
|
|
382
|
+
* @see {@link FailClosedDecoding}
|
|
383
|
+
*/
|
|
384
|
+
const decodeExecutableStateValue = (state) => {
|
|
385
|
+
try {
|
|
386
|
+
const decoded = glue.StateValue.decode(state);
|
|
387
|
+
if (!structurallyEqual(decoded.encode(), state)) {
|
|
388
|
+
throw new StateConversionFailedError('state conversion', new Error(`decoded StateValue did not re-encode to its source (source tag '${state.tag}')`));
|
|
389
|
+
}
|
|
390
|
+
return decoded;
|
|
391
|
+
}
|
|
392
|
+
catch (cause) {
|
|
393
|
+
// The decoder and the re-encoder both raise BARE vendor errors -- `missing
|
|
394
|
+
// field \`tag\``, `unknown variant \`x\`` -- carrying neither `code` nor
|
|
395
|
+
// `stage`. Coding them here is what the retired `downConvertForExecution`
|
|
396
|
+
// did, and what `fail-closed-decoding.md` still promises a caller.
|
|
397
|
+
throw cause instanceof StateConversionFailedError ? cause : new StateConversionFailedError('state conversion', cause);
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
/**
|
|
401
|
+
* Builds the retained-era `ContractState` a circuit executes against, from the
|
|
402
|
+
* era-neutral state the envelope's own reader produced.
|
|
403
|
+
*
|
|
404
|
+
* `StateValue` and `ChargedState` come from the retained glue rather than from
|
|
405
|
+
* compact-js: its `CompactRuntime` binding re-exports neither as a VALUE
|
|
406
|
+
* (midnightntwrk/midnight-sdk, spec finding E9), and building them through
|
|
407
|
+
* ledger-v8's own same-named classes instead would be the dual instantiation
|
|
408
|
+
* this era must not perform. `ContractState` is the glue's as well, so all
|
|
409
|
+
* three come from one module.
|
|
410
|
+
*
|
|
411
|
+
* A WHOLE `ContractState` rather than the bare `ChargedState` its predecessor
|
|
412
|
+
* built: the runtime reads `block.balance` off a contract state and substitutes
|
|
413
|
+
* an empty map for anything less, so writing the balance here is what makes it
|
|
414
|
+
* reach the circuit at all. It used to be injected into the query context after
|
|
415
|
+
* the fact, which is what #1345 was.
|
|
416
|
+
*
|
|
417
|
+
* @param contractState The decoded state and the balances beside it.
|
|
418
|
+
* @returns The state the retained runtime executes against.
|
|
419
|
+
*/
|
|
420
|
+
const executableStateFrom = (contractState) => {
|
|
421
|
+
// Read ONCE, then guarded. Not defaulted and not trusted: `new Map(...)`
|
|
422
|
+
// turns an absent balance, a `null`, an empty array and an empty `Set` alike
|
|
423
|
+
// into an EMPTY map, which is indistinguishable from a contract that holds
|
|
424
|
+
// nothing -- the circuit then reads zero where the chain says otherwise and
|
|
425
|
+
// the node refuses the resulting transcript, with every guard green. That is
|
|
426
|
+
// #1345. `tsc` reaches neither an untyped JavaScript caller nor an options
|
|
427
|
+
// object assembled dynamically, and both `Ledger8CircuitOptions` and
|
|
428
|
+
// `ContractStatePojo` are on the published surface.
|
|
429
|
+
// @see FailClosedDecoding
|
|
430
|
+
const { balance } = contractState;
|
|
431
|
+
if (!isContractBalance(balance)) {
|
|
432
|
+
throw new StateConversionFailedError('state conversion', new Error(`a contract state carries no usable balance (received ${describeValue(balance)}), so it cannot be ` +
|
|
433
|
+
'executed against. Read it from a contract-state snapshot rather than assembling one; a contract ' +
|
|
434
|
+
'that holds nothing declares an empty Map.'));
|
|
435
|
+
}
|
|
436
|
+
try {
|
|
437
|
+
const state = new glue.ContractState();
|
|
438
|
+
state.data = new glue.ChargedState(decodeExecutableStateValue(contractState.state));
|
|
439
|
+
// Copied rather than shared, so an entry the caller adds or removes afterwards
|
|
440
|
+
// cannot reach a running circuit.
|
|
441
|
+
state.balance = new Map(balance);
|
|
442
|
+
return state;
|
|
443
|
+
}
|
|
444
|
+
catch (cause) {
|
|
445
|
+
// Both setters are WASM, and both raise bare errors: `balance` refuses a
|
|
446
|
+
// colour `isContractBalance` admits by name but the runtime cannot read,
|
|
447
|
+
// and `data` refuses a `ChargedState` from another physical copy. Neither
|
|
448
|
+
// carries a `code` a caller can branch on.
|
|
449
|
+
throw cause instanceof StateConversionFailedError ? cause : new StateConversionFailedError('state conversion', cause);
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
/**
|
|
453
|
+
* Runs an effect and rethrows its failure without losing the failure's class,
|
|
454
|
+
* message, stack or `cause`.
|
|
455
|
+
*
|
|
456
|
+
* `Effect.runPromise` alone rejects with a `FiberFailure`, which carries neither
|
|
457
|
+
* the failure's class nor its `cause` — so a caller loses both the error it
|
|
458
|
+
* could have discriminated on and the diagnostic it needed. `runPromiseExit`
|
|
459
|
+
* recovers the real failures, which are then rethrown as follows:
|
|
460
|
+
*
|
|
461
|
+
* - A midnight-js coded error raised directly is rethrown unchanged, however
|
|
462
|
+
* many failures arrived beside it.
|
|
463
|
+
* - A lone failure carrying a coded error within eight links of its `cause`
|
|
464
|
+
* chain is rethrown as that coded error.
|
|
465
|
+
* - Otherwise a {@link ContractExecutionError} is thrown. Its message spells out
|
|
466
|
+
* every failure with its whole cause chain, `cause` is the first coded error
|
|
467
|
+
* found or else the first failure, and `errors` holds every failure as the
|
|
468
|
+
* original object.
|
|
469
|
+
*/
|
|
470
|
+
const runOrRethrow = async (effect) => {
|
|
471
|
+
const exit = await Effect.runPromiseExit(effect);
|
|
472
|
+
if (Exit.isSuccess(exit)) {
|
|
473
|
+
return exit.value;
|
|
474
|
+
}
|
|
475
|
+
// EVERY failure, not just the squashed first one. Verifier keys are read with
|
|
476
|
+
// `concurrency: 'unbounded'`, so a deploy missing three circuits' artifacts
|
|
477
|
+
// fails three times at once and `Cause.squash` answers with one -- sending the
|
|
478
|
+
// caller round the fix-and-rerun loop once per missing key.
|
|
479
|
+
const failures = Array.from(Cause.failures(exit.cause));
|
|
480
|
+
const all = failures.length > 0 ? failures : [Cause.squash(exit.cause)];
|
|
481
|
+
// A coded error raised directly leaves with its class intact, however many
|
|
482
|
+
// failures arrived beside it: the `@throws` of the entry points promise it.
|
|
483
|
+
// One found only on a cause chain leaves alone just when it is the only
|
|
484
|
+
// failure; otherwise every failure is reported, the first coded one on `cause`.
|
|
485
|
+
const direct = all.find((failure) => findCodedCause(failure) === failure);
|
|
486
|
+
if (direct !== undefined) {
|
|
487
|
+
throw direct;
|
|
488
|
+
}
|
|
489
|
+
const carried = all.length === 1 ? findCodedCause(all[0]) : undefined;
|
|
490
|
+
if (carried !== undefined) {
|
|
491
|
+
throw carried;
|
|
492
|
+
}
|
|
493
|
+
throw ContractExecutionError.fromFailures(all);
|
|
494
|
+
};
|
|
495
|
+
/**
|
|
496
|
+
* Reads the ONE contract call a retained-era circuit produces.
|
|
497
|
+
*
|
|
498
|
+
* The retained era has no `crossContractCall`, so its execution adapter
|
|
499
|
+
* synthesises a single-entry trace and a one-element list is complete by
|
|
500
|
+
* construction. The list is still typed as a list, so the emptiness this era
|
|
501
|
+
* cannot produce is refused by name rather than read as `undefined` and carried
|
|
502
|
+
* into a composition.
|
|
503
|
+
*
|
|
504
|
+
* @param calls The calls the execution reported.
|
|
505
|
+
* @param circuitId The circuit they were produced for, for the message.
|
|
506
|
+
* @returns The sole call.
|
|
507
|
+
* @throws InvariantViolationError If the list is empty.
|
|
508
|
+
*/
|
|
509
|
+
const soleCall = (calls, circuitId) => {
|
|
510
|
+
const [only] = calls;
|
|
511
|
+
if (only === undefined) {
|
|
512
|
+
throw new InvariantViolationError(`circuit '${circuitId}' produced no contract call. The ledger 8 runtime cannot make a ` +
|
|
513
|
+
'cross-contract call, so exactly one is expected.');
|
|
514
|
+
}
|
|
515
|
+
return only;
|
|
516
|
+
};
|
|
517
|
+
/**
|
|
518
|
+
* Refuses a circuit id the contract does not declare, before compact-js
|
|
519
|
+
* dispatches on it.
|
|
520
|
+
*
|
|
521
|
+
* `Object.hasOwn`, NOT a bare truthiness check. A 0.16 artifact assigns
|
|
522
|
+
* `provableCircuits` a plain object literal, so its prototype is live, and
|
|
523
|
+
* compact-js resolves a circuit with `contract.provableCircuits[id]` guarded
|
|
524
|
+
* only by `if (!circuit)`. `'toString'`, `'valueOf'` and `'constructor'` all
|
|
525
|
+
* satisfy that guard: the prototype member is CALLED with the runtime context
|
|
526
|
+
* and its return value fed to `readExecution`. The id reaches here from the
|
|
527
|
+
* caller, so it is refused by name, the way the retired `executeCircuit` did.
|
|
528
|
+
*
|
|
529
|
+
* @param contract The contract the call names.
|
|
530
|
+
* @param circuitId The circuit the caller asked for.
|
|
531
|
+
* @throws InvalidArgumentError If the contract declares no such circuit.
|
|
532
|
+
*/
|
|
533
|
+
const assertDeclaredCircuit = (contract, circuitId) => {
|
|
534
|
+
const circuit = Object.hasOwn(contract.provableCircuits, circuitId)
|
|
535
|
+
? contract.provableCircuits[circuitId]
|
|
536
|
+
: undefined;
|
|
537
|
+
if (typeof circuit !== 'function') {
|
|
538
|
+
throw new InvalidArgumentError(`No circuit named '${circuitId}' on this ledger 8 contract instance. ` +
|
|
539
|
+
`Available circuits: ${Object.keys(contract.provableCircuits).sort().join(', ')}.`);
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
/**
|
|
543
|
+
* Runs one circuit on a retained-era contract and packages every artifact a
|
|
544
|
+
* v9-native call prototype needs.
|
|
545
|
+
*
|
|
546
|
+
* The balances the contract holds travel on the state it is given — see
|
|
547
|
+
* {@link Ledger8CircuitOptions.contractState}.
|
|
548
|
+
*
|
|
549
|
+
* @param options The retained contract, circuit id, arguments, decoded state,
|
|
550
|
+
* address, coin public key, private state and optional pinned clock.
|
|
551
|
+
* @returns Every artifact a v9-native call prototype needs.
|
|
552
|
+
* @see {@link RetainedEraExecution}
|
|
553
|
+
*/
|
|
554
|
+
const runLedger8Circuit = async (options) => {
|
|
555
|
+
assertDeclaredCircuit(options.contract, options.circuitId);
|
|
556
|
+
const executable = ContractExecutable.make(containerFor(options.contract));
|
|
557
|
+
const contractState = executableStateFrom(options.contractState);
|
|
558
|
+
const program = Effect.gen(function* () {
|
|
559
|
+
return yield* executable.circuit(Contract.ProvableCircuitId(options.circuitId), {
|
|
560
|
+
address: PlatformContractAddress.ContractAddress(options.address),
|
|
561
|
+
contractState,
|
|
562
|
+
privateState: options.privateState
|
|
563
|
+
},
|
|
564
|
+
// Asserted for the same reason `createCallTxOptions` asserts it in
|
|
565
|
+
// `packages/contracts/src/tx-interfaces.ts`: resolved through a GENERIC
|
|
566
|
+
// `C`, `CircuitParameters` degrades to `unknown[]` because TypeScript
|
|
567
|
+
// indexes `provableCircuits` against the constraint rather than the
|
|
568
|
+
// instantiated contract. The tuple is checked where `C` is concrete, at
|
|
569
|
+
// the caller's own call site.
|
|
570
|
+
...options.args);
|
|
571
|
+
});
|
|
572
|
+
const call = await runOrRethrow(withPinnedClock(options.nowSeconds, program.pipe(Effect.provide(Layer.mergeAll(keysLayer(options.coinPk, undefined), zkConfigurationLayer(refuseVerifierKeyRead))))));
|
|
573
|
+
const only = soleCall(call.calls, options.circuitId);
|
|
574
|
+
return {
|
|
575
|
+
circuitId: only.circuitId,
|
|
576
|
+
result: call.result,
|
|
577
|
+
input: only.private.input,
|
|
578
|
+
output: only.private.output,
|
|
579
|
+
publicTranscript: only.public.publicTranscript,
|
|
580
|
+
privateTranscriptOutputs: only.private.privateTranscriptOutputs,
|
|
581
|
+
preContractState: only.public.partitionInputs.state,
|
|
582
|
+
postContractState: only.public.contractState,
|
|
583
|
+
postContractStateEncoded: only.public.contractState.encode(),
|
|
584
|
+
privateStateAfter: call.privateState,
|
|
585
|
+
partitionContext: {
|
|
586
|
+
block: only.public.partitionInputs.block,
|
|
587
|
+
effects: only.public.partitionInputs.effects,
|
|
588
|
+
comIndices: only.public.partitionInputs.comIndices
|
|
589
|
+
},
|
|
590
|
+
zswapLocalState: call.zswapLocalState
|
|
591
|
+
};
|
|
592
|
+
};
|
|
593
|
+
/**
|
|
594
|
+
* Re-codes compact-js's refusal of a verifier-key blob as this package's own
|
|
595
|
+
* {@link ComposeFailedError}.
|
|
596
|
+
*
|
|
597
|
+
* compact-js writes the keys itself inside `initialize`, so it is the first
|
|
598
|
+
* thing to touch the bytes and the retained composer -- which raised the coded
|
|
599
|
+
* refusal before this move -- is never reached. Without this the same fault is
|
|
600
|
+
* reported as a coded error on the current era and an uncoded one on the
|
|
601
|
+
* retained era.
|
|
602
|
+
*
|
|
603
|
+
* The `cause` is what separates a rejected blob from the other configuration
|
|
604
|
+
* refusals: compact-js attaches the ledger's own error only when a key it was
|
|
605
|
+
* handed was refused, and leaves it absent for a key that was never served.
|
|
606
|
+
*
|
|
607
|
+
* @param error The failure compact-js reported.
|
|
608
|
+
* @returns A {@link ComposeFailedError} for a rejected blob; the error
|
|
609
|
+
* unchanged for anything else.
|
|
610
|
+
*/
|
|
611
|
+
const recodeVerifierKeyBlobFailure = (error) => {
|
|
612
|
+
if (!ContractConfigurationError.isConfigurationError(error) || error.cause === undefined) {
|
|
613
|
+
return error;
|
|
614
|
+
}
|
|
615
|
+
const circuitId = /verifier key for circuit '([^']+)'/.exec(error.message)?.[1];
|
|
616
|
+
return circuitId === undefined
|
|
617
|
+
? error
|
|
618
|
+
: new ComposeFailedError('v8', 'deploy-verifier-key-blob', circuitId, error.cause);
|
|
619
|
+
};
|
|
620
|
+
/**
|
|
621
|
+
* Runs a retained-era contract's constructor and packages the result.
|
|
622
|
+
*
|
|
623
|
+
* compact-js's `initialize` also writes the maintenance authority and registers
|
|
624
|
+
* each entry point's verifier key onto the state, both of which this era's
|
|
625
|
+
* deploy leg previously did for itself. The authority matters: the retained
|
|
626
|
+
* constructor leaves an EMPTY committee with a threshold of one — one signature
|
|
627
|
+
* from a set of zero keys, which nothing can satisfy — so a deployment left on
|
|
628
|
+
* it could never have a verifier key inserted, removed or replaced.
|
|
629
|
+
*
|
|
630
|
+
* @param options The compiled contract, constructor arguments, private state,
|
|
631
|
+
* coin public key, optional signing key and verifier-key reader.
|
|
632
|
+
* @throws ComposeOptionError naming option `'signingKey'` when a supplied key
|
|
633
|
+
* is not the 32 bytes of hex the retained runtime reads, raised before the
|
|
634
|
+
* constructor runs.
|
|
635
|
+
* @returns The freshly built state, the resulting private state, the Zswap
|
|
636
|
+
* local state the constructor ended on and the signing key the authority was
|
|
637
|
+
* built from.
|
|
638
|
+
* @see {@link RetainedEraExecution}
|
|
639
|
+
*/
|
|
640
|
+
const runLedger8Constructor = async (options) => {
|
|
641
|
+
// BEFORE the constructor runs, so nothing is executed against a key the
|
|
642
|
+
// maintenance authority could never have been built from, and the refusal
|
|
643
|
+
// names the option rather than leaving the runtime's own buffer message to
|
|
644
|
+
// stand for it.
|
|
645
|
+
if (options.signingKey !== undefined && !LEDGER8_SIGNING_KEY_PATTERN.test(options.signingKey)) {
|
|
646
|
+
throw new ComposeOptionError('v8', 'signingKey');
|
|
647
|
+
}
|
|
648
|
+
const executable = ContractExecutable.make(containerFor(options.contract));
|
|
649
|
+
const deployed = await runOrRethrow(executable
|
|
650
|
+
.initialize(options.privateState, ...options.args)
|
|
651
|
+
.pipe(Effect.mapError(recodeVerifierKeyBlobFailure), Effect.provide(Layer.mergeAll(keysLayer(options.coinPk, options.signingKey), zkConfigurationLayer(options.verifierKeys)))));
|
|
652
|
+
return {
|
|
653
|
+
contractState: deployed.public.contractState,
|
|
654
|
+
privateState: deployed.private.privateState,
|
|
655
|
+
zswapLocalState: deployed.private.zswapLocalState,
|
|
656
|
+
signingKey: deployed.private.signingKey.value
|
|
657
|
+
};
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
/*
|
|
661
|
+
* This file is part of midnight-js.
|
|
662
|
+
* Copyright (C) Midnight Foundation
|
|
663
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
664
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
665
|
+
* You may not use this file except in compliance with the License.
|
|
666
|
+
* You may obtain a copy of the License at
|
|
667
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
668
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
669
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
670
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
671
|
+
* See the License for the specific language governing permissions and
|
|
672
|
+
* limitations under the License.
|
|
673
|
+
*/
|
|
674
|
+
/**
|
|
675
|
+
* Retained-era (ledger 8) contract maintenance: compact-js's own maintenance
|
|
676
|
+
* operations, wrapped into an unproven transaction.
|
|
677
|
+
*
|
|
678
|
+
* @see {@link RetainedEraExecution}
|
|
679
|
+
*/
|
|
680
|
+
/** The committee index compact-js signs every maintenance update at. */
|
|
681
|
+
const COMPACT_JS_SIGNATURE_INDEX = 0;
|
|
682
|
+
/** How many signatures every maintenance update compact-js builds carries. */
|
|
683
|
+
const COMPACT_JS_SIGNATURE_COUNT = 1;
|
|
684
|
+
const readContractState = (contractStateBytes) => {
|
|
685
|
+
try {
|
|
686
|
+
return glue.ContractState.deserialize(contractStateBytes);
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
throw new ComposeOptionError('v8', 'contractStateBytes', error);
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
const circuitOf = (update) => update.kind === 'replace-authority' ? NO_CIRCUIT : update.circuitId;
|
|
693
|
+
const verifyingKeyOf = (signingKey) => {
|
|
694
|
+
try {
|
|
695
|
+
return glue.signatureVerifyingKey(signingKey);
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
throw new ComposeOptionError('v8', 'signingKey', error);
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
const assertSignsForAuthority = (authority, signingKey, contractAddress) => {
|
|
702
|
+
if (authority.committee.length === 0) {
|
|
703
|
+
throw new MaintenanceAuthorityMismatchError('v8', contractAddress, 'empty-committee');
|
|
704
|
+
}
|
|
705
|
+
if (authority.threshold > COMPACT_JS_SIGNATURE_COUNT) {
|
|
706
|
+
throw new MaintenanceAuthorityMismatchError('v8', contractAddress, 'threshold-above-one');
|
|
707
|
+
}
|
|
708
|
+
if (authority.committee[COMPACT_JS_SIGNATURE_INDEX] !== verifyingKeyOf(signingKey)) {
|
|
709
|
+
throw new MaintenanceAuthorityMismatchError('v8', contractAddress, 'not-first-member');
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
const maintenanceOperation = (executable, update, context) => {
|
|
713
|
+
switch (update.kind) {
|
|
714
|
+
case 'insert-verifier-key':
|
|
715
|
+
return executable.addOrReplaceContractOperation(Contract.ProvableCircuitId(update.circuitId), Contract.VerifierKey(update.verifierKey), context);
|
|
716
|
+
case 'remove-verifier-key':
|
|
717
|
+
return executable.removeContractOperation(Contract.ProvableCircuitId(update.circuitId), context);
|
|
718
|
+
case 'replace-authority':
|
|
719
|
+
return executable.replaceContractMaintenanceAuthority(Option.some(toPlatformSigningKey(update.newSigningKey)), context);
|
|
720
|
+
default: {
|
|
721
|
+
const { kind } = update;
|
|
722
|
+
throw new InvalidArgumentError(`Unknown maintenance update kind '${kind}'`);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
};
|
|
726
|
+
const brandedAddress = (contractAddress, update) => {
|
|
727
|
+
try {
|
|
728
|
+
return PlatformContractAddress.ContractAddress(contractAddress);
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
throw new ComposeFailedError('v8', 'maintenance-update', circuitOf(update), error);
|
|
732
|
+
}
|
|
733
|
+
};
|
|
734
|
+
/**
|
|
735
|
+
* Composes an UNPROVEN v8 transaction carrying one maintenance update, built
|
|
736
|
+
* and signed by compact-js's ledger 8 `ContractExecutable`, and serializes it.
|
|
737
|
+
*
|
|
738
|
+
* Checks only what compact-js does not: the envelope, the key formats, and
|
|
739
|
+
* that the authority can be signed for the way compact-js signs — one
|
|
740
|
+
* signature, by the committee member at index 0.
|
|
741
|
+
*
|
|
742
|
+
* Whether the verifier-key slot an insert or a remove targets is occupied is
|
|
743
|
+
* NOT checked here: that is the caller's decision, made against the same state.
|
|
744
|
+
*
|
|
745
|
+
* @param request The contract, its full state, the coin public key, the
|
|
746
|
+
* authority key, the transaction envelope and the update.
|
|
747
|
+
* @returns The UNPROVEN, serialized transaction.
|
|
748
|
+
* @throws ComposeOptionError If `networkId` is empty, `ttl` is not a valid
|
|
749
|
+
* instant, `signingKey` or `newSigningKey` is not 64 hex characters,
|
|
750
|
+
* `signingKey` is not a Schnorr scalar the ledger 8 runtime can read, or the
|
|
751
|
+
* state bytes cannot be read by the ledger 8 runtime.
|
|
752
|
+
* @throws MaintenanceAuthorityMismatchError If the authority has no committee,
|
|
753
|
+
* needs more than one signature, or the signing key is not its first member.
|
|
754
|
+
* @throws InvalidArgumentError If an untyped caller names an update kind that
|
|
755
|
+
* does not exist.
|
|
756
|
+
* @throws ComposeFailedError At stage `'maintenance-update'` if the address,
|
|
757
|
+
* compact-js or the ledger refuses the update, with that failure on `cause`.
|
|
758
|
+
* A failure that already carries a coded midnight-js error is rethrown as
|
|
759
|
+
* that error instead.
|
|
760
|
+
* @see {@link RetainedEraExecution}
|
|
761
|
+
*/
|
|
762
|
+
const composeLedger8MaintenanceTx = async (request) => {
|
|
763
|
+
const { contract, contractAddress, contractStateBytes, coinPublicKey, signingKey, networkId, ttl, update } = request;
|
|
764
|
+
assertComposeEnvelope(request, 'v8');
|
|
765
|
+
if (!LEDGER8_SIGNING_KEY_PATTERN.test(signingKey)) {
|
|
766
|
+
throw new ComposeOptionError('v8', 'signingKey');
|
|
767
|
+
}
|
|
768
|
+
if (update.kind === 'replace-authority' && !LEDGER8_SIGNING_KEY_PATTERN.test(update.newSigningKey)) {
|
|
769
|
+
throw new ComposeOptionError('v8', 'newSigningKey');
|
|
770
|
+
}
|
|
771
|
+
const contractState = readContractState(contractStateBytes);
|
|
772
|
+
assertSignsForAuthority(contractState.maintenanceAuthority, signingKey, contractAddress);
|
|
773
|
+
const executable = ContractExecutable.make(containerFor(contract));
|
|
774
|
+
const context = { address: brandedAddress(contractAddress, update), contractState };
|
|
775
|
+
const result = await runOrRethrow(maintenanceOperation(executable, update, context).pipe(Effect.mapError((error) => findCodedCause(error) === undefined
|
|
776
|
+
? new ComposeFailedError('v8', 'maintenance-update', circuitOf(update), error)
|
|
777
|
+
: error), Effect.provide(Layer.mergeAll(keysLayer(coinPublicKey, signingKey), zkConfigurationLayer(refuseVerifierKeyRead)))));
|
|
778
|
+
try {
|
|
779
|
+
const intent = Ledger.Intent.new(ttl).addMaintenanceUpdate(result.public.maintenanceUpdate);
|
|
780
|
+
return Ledger.Transaction.fromParts(networkId, undefined, undefined, intent).serialize();
|
|
781
|
+
}
|
|
782
|
+
catch (error) {
|
|
783
|
+
throw new ComposeFailedError('v8', 'maintenance-update', circuitOf(update), error);
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
/*
|
|
788
|
+
* This file is part of midnight-js.
|
|
789
|
+
* Copyright (C) Midnight Foundation
|
|
790
|
+
* SPDX-License-Identifier: Apache-2.0
|
|
791
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
792
|
+
* You may not use this file except in compliance with the License.
|
|
793
|
+
* You may obtain a copy of the License at
|
|
794
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
795
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
796
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
797
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
798
|
+
* See the License for the specific language governing permissions and
|
|
799
|
+
* limitations under the License.
|
|
800
|
+
*/
|
|
801
|
+
/**
|
|
802
|
+
* Builds a {@link Ledger8Engine}.
|
|
803
|
+
*
|
|
804
|
+
* The retained toolchain is no longer acquired here: compact-js's era-pinned
|
|
805
|
+
* ledger-8 entries own it, and `lib/v8/executable.ts` reaches them. What this
|
|
806
|
+
* function still does is sit behind the dynamic `import('../../engine.js')` in
|
|
807
|
+
* `lib/v8/load-engine.ts`, so importing the package root never pulls the
|
|
808
|
+
* multi-megabyte retained WASM onto the module graph.
|
|
809
|
+
*
|
|
810
|
+
* It no longer runs a dual-instantiation guard either. That guard compared
|
|
811
|
+
* `onchain-runtime-v3` against the 0.16 glue at construction time. Both
|
|
812
|
+
* acquisition paths are still live — `lib/v8/executable.ts` imports the glue
|
|
813
|
+
* directly, and compact-js resolves the same specifier for itself — so the axis
|
|
814
|
+
* did not go away; only the runtime check did. The invariant is held at install
|
|
815
|
+
* time instead, by `src/test/single-instance.test.ts`, which pins one resolved
|
|
816
|
+
* copy of `onchain-runtime-v3` and of each compact-runtime era line. That is a
|
|
817
|
+
* check on THIS repo's lockfile, not on a consumer's process.
|
|
818
|
+
*
|
|
819
|
+
* @returns The engine surface.
|
|
820
|
+
* @see {@link EraBoundary}
|
|
821
|
+
* @see {@link ModuleGraphAndLazyLoading}
|
|
822
|
+
*/
|
|
823
|
+
const createLedger8Engine = async () => Promise.resolve({
|
|
824
|
+
executeCircuit: runLedger8Circuit,
|
|
825
|
+
executeConstructor: runLedger8Constructor,
|
|
826
|
+
composeMaintenanceTx: composeLedger8MaintenanceTx,
|
|
827
|
+
wrapKeepStateCall,
|
|
828
|
+
reexpressOperationsForLedger9
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
export { createLedger8Engine };
|
|
832
|
+
//# sourceMappingURL=engine.js.map
|