@midnightntwrk/mnkit-sim 0.0.1 → 0.2.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +46 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -0
- package/dist/privacy.d.ts +25 -0
- package/dist/privacy.js +87 -0
- package/dist/sim.d.ts +68 -0
- package/dist/sim.js +96 -0
- package/package.json +35 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,48 @@
|
|
|
1
1
|
# @midnightntwrk/mnkit-sim
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An in-memory harness for testing a compiled Compact contract: deploy it and
|
|
4
|
+
call its circuits with `@midnight-ntwrk/midnight-js-protocol`'s compact
|
|
5
|
+
runtime, with no network and no proofs. Part of
|
|
6
|
+
[mnkit](https://www.npmjs.com/package/mnkit), whose projects use it in
|
|
7
|
+
`src/test/*.sim.test.ts`.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { Sim, assertNotInPublicState, expectRejects } from '@midnightntwrk/mnkit-sim';
|
|
11
|
+
import { Contract, ledger } from '../../contract/managed/calculator/contract/index.js';
|
|
12
|
+
import { createCalculatorPrivateState, witnesses } from '../../contract/witnesses.js';
|
|
13
|
+
|
|
14
|
+
const deploy = (w = witnesses) =>
|
|
15
|
+
Sim.deploy({ contract: new Contract(w), ledger, privateState: createCalculatorPrivateState() });
|
|
16
|
+
|
|
17
|
+
expect(deploy().call('add', 2n, 3n).ledger.result).toBe(5n);
|
|
18
|
+
|
|
19
|
+
// A witness that lies about the division is caught by the circuit's assert.
|
|
20
|
+
const lying = deploy({ ...witnesses, divMod: ({ privateState }) => [privateState, [4n, 0n]] });
|
|
21
|
+
expectRejects(() => lying.call('divide', 17n, 5n), 'incorrect division');
|
|
22
|
+
|
|
23
|
+
assertNotInPublicState(lying.ledger(), { secret: mySecretBytes });
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
- `Sim.deploy` / `.call` / `.as(coinPublicKey)` / `.ledger()`: run the
|
|
27
|
+
constructor and circuits, switch caller, read the public ledger.
|
|
28
|
+
- `expectRejects`: a circuit call fails, optionally with a message.
|
|
29
|
+
- `assertNotInPublicState`, `findInPublicState`, `collectPublicBytes`: check
|
|
30
|
+
that a secret never reaches public state.
|
|
31
|
+
|
|
32
|
+
## Install outside mnkit
|
|
33
|
+
|
|
34
|
+
An mnkit project already has these. Anywhere else, add the peer and these
|
|
35
|
+
`overrides` to your `package.json`:
|
|
36
|
+
|
|
37
|
+
```json
|
|
38
|
+
"overrides": {
|
|
39
|
+
"@midnightntwrk/ledger-v9": "1.0.2",
|
|
40
|
+
"@midnightntwrk/onchain-runtime-v4": "4.0.2"
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
midnight-js-protocol 5.0.1 pins these at these versions today, but
|
|
45
|
+
compact-runtime 0.21.0 asks for `onchain-runtime-v4` `^4.0.0-rc.3`. The
|
|
46
|
+
overrides keep a later release, which mnkit doesn't test, out of your tree.
|
|
47
|
+
|
|
48
|
+
Apache-2.0. Source: [midnight-examples/packages/sim](https://github.com/midnightntwrk/midnight-examples/tree/main/packages/sim).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { Sim, SIM_COIN_PUBLIC_KEY, expectRejects, type CircuitArgs, type CircuitResult, type ConstructorArgs, type DeployOptions, type SimContract, } from './sim.js';
|
|
2
|
+
export { assertNotInPublicState, collectPublicBytes, findInPublicState, type PublicBytes } from './privacy.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// In-memory contract harness for the examples' *.sim.test.ts files.
|
|
2
|
+
// See AGENTS.md at the repo root ("In-memory tests") for the conventions.
|
|
3
|
+
export { Sim, SIM_COIN_PUBLIC_KEY, expectRejects, } from './sim.js';
|
|
4
|
+
export { assertNotInPublicState, collectPublicBytes, findInPublicState } from './privacy.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** One byte string found in public state, with the path it was found at. */
|
|
2
|
+
export interface PublicBytes {
|
|
3
|
+
label: string;
|
|
4
|
+
bytes: Uint8Array;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Collects every byte string in a decoded ledger (the object `ledger(state)`
|
|
8
|
+
* returns, or anything shaped like it): plain fields, struct fields, and the
|
|
9
|
+
* entries of Map, Set and List ADTs. Map entries are labelled
|
|
10
|
+
* `field[i].key` / `field[i].value`; Set and List entries `field[i]`.
|
|
11
|
+
*/
|
|
12
|
+
export declare function collectPublicBytes(ledger: unknown, root?: string): PublicBytes[];
|
|
13
|
+
/**
|
|
14
|
+
* Returns the label of the first public byte string that contains `secret`,
|
|
15
|
+
* or null. Containment, not equality: a secret embedded in a larger field
|
|
16
|
+
* (a struct encoded as bytes, a padded value) still counts as a leak.
|
|
17
|
+
*/
|
|
18
|
+
export declare function findInPublicState(ledger: unknown, secret: Uint8Array): string | null;
|
|
19
|
+
/**
|
|
20
|
+
* Throws if any secret appears anywhere in the decoded ledger, naming the
|
|
21
|
+
* secret and the field it was found in. `secrets` maps a name (used in the
|
|
22
|
+
* message) to its bytes; write one entry per "never on chain" line of the
|
|
23
|
+
* example's SPEC.md.
|
|
24
|
+
*/
|
|
25
|
+
export declare function assertNotInPublicState(ledger: unknown, secrets: Record<string, Uint8Array>): void;
|
package/dist/privacy.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Privacy checks over a decoded public ledger.
|
|
2
|
+
//
|
|
3
|
+
// Replaces the hand-written collect…Bytes / findLeak pairs that were in
|
|
4
|
+
// examples/shielded-chips/src/test/privacy.test.ts and
|
|
5
|
+
// examples/private-tip-jar/src/test/private-tip-jar.test.ts. The walker
|
|
6
|
+
// follows the ledger itself, so a new ledger field is covered without
|
|
7
|
+
// editing a list.
|
|
8
|
+
const hex = (u) => Buffer.from(u).toString('hex');
|
|
9
|
+
const isIterable = (v) => typeof v[Symbol.iterator] === 'function';
|
|
10
|
+
/**
|
|
11
|
+
* Collects every byte string in a decoded ledger (the object `ledger(state)`
|
|
12
|
+
* returns, or anything shaped like it): plain fields, struct fields, and the
|
|
13
|
+
* entries of Map, Set and List ADTs. Map entries are labelled
|
|
14
|
+
* `field[i].key` / `field[i].value`; Set and List entries `field[i]`.
|
|
15
|
+
*/
|
|
16
|
+
export function collectPublicBytes(ledger, root = '') {
|
|
17
|
+
const out = [];
|
|
18
|
+
const seen = new Set();
|
|
19
|
+
const walk = (v, label) => {
|
|
20
|
+
if (v instanceof Uint8Array) {
|
|
21
|
+
out.push({ label, bytes: v });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (v === null || typeof v !== 'object' || seen.has(v))
|
|
25
|
+
return;
|
|
26
|
+
seen.add(v);
|
|
27
|
+
if (Array.isArray(v)) {
|
|
28
|
+
v.forEach((x, i) => walk(x, `${label}[${i}]`));
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (isIterable(v)) {
|
|
32
|
+
// A Map ADT has lookup() and yields [key, value] pairs.
|
|
33
|
+
const isMap = typeof v.lookup === 'function';
|
|
34
|
+
let i = 0;
|
|
35
|
+
for (const entry of v) {
|
|
36
|
+
if (isMap && Array.isArray(entry) && entry.length === 2) {
|
|
37
|
+
walk(entry[0], `${label}[${i}].key`);
|
|
38
|
+
walk(entry[1], `${label}[${i}].value`);
|
|
39
|
+
}
|
|
40
|
+
else {
|
|
41
|
+
walk(entry, `${label}[${i}]`);
|
|
42
|
+
}
|
|
43
|
+
i++;
|
|
44
|
+
}
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
for (const key of Object.keys(v)) {
|
|
48
|
+
const field = v[key];
|
|
49
|
+
if (typeof field === 'function')
|
|
50
|
+
continue;
|
|
51
|
+
walk(field, label ? `${label}.${key}` : key);
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
walk(ledger, root);
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Returns the label of the first public byte string that contains `secret`,
|
|
59
|
+
* or null. Containment, not equality: a secret embedded in a larger field
|
|
60
|
+
* (a struct encoded as bytes, a padded value) still counts as a leak.
|
|
61
|
+
*/
|
|
62
|
+
export function findInPublicState(ledger, secret) {
|
|
63
|
+
const target = hex(secret);
|
|
64
|
+
if (target.length === 0)
|
|
65
|
+
return null;
|
|
66
|
+
for (const { label, bytes } of collectPublicBytes(ledger)) {
|
|
67
|
+
if (hex(bytes).includes(target))
|
|
68
|
+
return label;
|
|
69
|
+
}
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Throws if any secret appears anywhere in the decoded ledger, naming the
|
|
74
|
+
* secret and the field it was found in. `secrets` maps a name (used in the
|
|
75
|
+
* message) to its bytes; write one entry per "never on chain" line of the
|
|
76
|
+
* example's SPEC.md.
|
|
77
|
+
*/
|
|
78
|
+
export function assertNotInPublicState(ledger, secrets) {
|
|
79
|
+
const leaks = [];
|
|
80
|
+
for (const [name, bytes] of Object.entries(secrets)) {
|
|
81
|
+
const field = findInPublicState(ledger, bytes);
|
|
82
|
+
if (field !== null)
|
|
83
|
+
leaks.push(`${name} found in public state at ${field}`);
|
|
84
|
+
}
|
|
85
|
+
if (leaks.length > 0)
|
|
86
|
+
throw new Error(`privacy invariant broken:\n ${leaks.join('\n ')}`);
|
|
87
|
+
}
|
package/dist/sim.d.ts
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { type ChargedState, type CircuitContext, type CircuitResults, type ConstructorContext, type ConstructorResult } from '@midnight-ntwrk/midnight-js-protocol/v9/compact-runtime';
|
|
2
|
+
/** Coin public key used when the test doesn't pick one (hex, 32 bytes). */
|
|
3
|
+
export declare const SIM_COIN_PUBLIC_KEY: string;
|
|
4
|
+
/** The parts of a compiler-generated `Contract<PS>` the harness uses. */
|
|
5
|
+
export interface SimContract<PS> {
|
|
6
|
+
initialState(context: ConstructorContext<PS>, ...args: never[]): Promise<ConstructorResult<PS>>;
|
|
7
|
+
impureCircuits: object;
|
|
8
|
+
}
|
|
9
|
+
type ImpureOf<C> = C extends {
|
|
10
|
+
impureCircuits: infer I;
|
|
11
|
+
} ? I : never;
|
|
12
|
+
type CircuitName<C> = keyof ImpureOf<C> & string;
|
|
13
|
+
type CircuitFn<C, K extends CircuitName<C>> = ImpureOf<C>[K] extends (...a: infer A) => infer R ? (...a: A) => R : never;
|
|
14
|
+
/** A circuit's arguments, without the leading context. */
|
|
15
|
+
export type CircuitArgs<C, K extends CircuitName<C>> = Parameters<CircuitFn<C, K>> extends [unknown, ...infer Rest] ? Rest : never;
|
|
16
|
+
/** What a circuit returns in Compact. */
|
|
17
|
+
export type CircuitResult<C, K extends CircuitName<C>> = Awaited<ReturnType<CircuitFn<C, K>>> extends CircuitResults<unknown, infer R> ? R : never;
|
|
18
|
+
/** The constructor's arguments, without the leading context. */
|
|
19
|
+
export type ConstructorArgs<C> = C extends {
|
|
20
|
+
initialState(context: never, ...args: infer A): unknown;
|
|
21
|
+
} ? A : never;
|
|
22
|
+
export interface DeployOptions<C, PS, L> {
|
|
23
|
+
/** The compiled contract, e.g. `new Contract(witnesses)`. */
|
|
24
|
+
contract: C;
|
|
25
|
+
/** The compiled `ledger` function, which decodes public state. */
|
|
26
|
+
ledger: (state: ChargedState) => L;
|
|
27
|
+
privateState: PS;
|
|
28
|
+
/** Constructor arguments, in declaration order. */
|
|
29
|
+
args?: ConstructorArgs<C>;
|
|
30
|
+
/** Hex coin public key of the deployer (and of later callers until as()). */
|
|
31
|
+
coinPublicKey?: string;
|
|
32
|
+
}
|
|
33
|
+
export declare class Sim<C extends SimContract<PS>, PS, L> {
|
|
34
|
+
readonly contract: C;
|
|
35
|
+
private readonly decode;
|
|
36
|
+
/** The contract's address in this simulation (kernel.self()). */
|
|
37
|
+
readonly address: string;
|
|
38
|
+
/** Coin public key of the caller for the next call(); change with as(). */
|
|
39
|
+
coinPublicKey: string;
|
|
40
|
+
/** The private state the next call's witnesses see. Assign to swap it. */
|
|
41
|
+
privateState: PS;
|
|
42
|
+
/** The context the last call returned: zswap inputs/outputs, gas, etc. */
|
|
43
|
+
lastContext: CircuitContext<PS> | undefined;
|
|
44
|
+
private state;
|
|
45
|
+
private constructor();
|
|
46
|
+
/** Runs the constructor and returns a simulation of the deployed contract. */
|
|
47
|
+
static deploy<C extends SimContract<PS>, PS, L>(opts: DeployOptions<C, PS, L>): Promise<Sim<C, PS, L>>;
|
|
48
|
+
/** Makes later calls come from this coin public key (hex). */
|
|
49
|
+
as(coinPublicKey: string): this;
|
|
50
|
+
/**
|
|
51
|
+
* Calls an impure circuit as one transaction. On success the public and
|
|
52
|
+
* private state move forward; if the circuit throws (a failed assert), the
|
|
53
|
+
* error propagates and neither changes.
|
|
54
|
+
*/
|
|
55
|
+
call<K extends CircuitName<C>>(circuit: K, ...args: CircuitArgs<C, K>): Promise<{
|
|
56
|
+
result: CircuitResult<C, K>;
|
|
57
|
+
ledger: L;
|
|
58
|
+
}>;
|
|
59
|
+
/** The decoded public ledger, as an indexer would show it. */
|
|
60
|
+
ledger(): L;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Runs `fn` and returns the error it throws. Fails if it doesn't throw, or if
|
|
64
|
+
* `message` is given and the error message doesn't contain it. Use it for
|
|
65
|
+
* every guard: `await expectRejects(() => sim.call('withdraw', ...), 'not the owner')`.
|
|
66
|
+
*/
|
|
67
|
+
export declare function expectRejects(fn: () => unknown, message?: string): Promise<Error>;
|
|
68
|
+
export {};
|
package/dist/sim.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// In-memory deploy-and-call harness for a compiled Compact contract.
|
|
2
|
+
//
|
|
3
|
+
// Runs the compiler's JS output (contract/managed/<c>/contract/index.js) with
|
|
4
|
+
// compact-runtime, so it needs no proof server, node or indexer. Proving keys
|
|
5
|
+
// aren't used either: `npm run compile:fast` (--skip-zk) output is enough.
|
|
6
|
+
//
|
|
7
|
+
// Each call() is its own transaction: a fresh circuit context built from the
|
|
8
|
+
// current public state, the current private state and the caller's coin
|
|
9
|
+
// public key, the way examples/calculator/ui/src/__tests__/
|
|
10
|
+
// calculator-circuits.test.ts does it.
|
|
11
|
+
//
|
|
12
|
+
// From compact-runtime 0.20 (Compact 0.35) the constructor and circuits are
|
|
13
|
+
// async, and createCircuitContext takes one options object; so deploy(),
|
|
14
|
+
// call() and expectRejects() here are async too.
|
|
15
|
+
import { createCircuitContext, createConstructorContext, sampleContractAddress, } from '@midnight-ntwrk/midnight-js-protocol/v9/compact-runtime';
|
|
16
|
+
/** Coin public key used when the test doesn't pick one (hex, 32 bytes). */
|
|
17
|
+
export const SIM_COIN_PUBLIC_KEY = '00'.repeat(32);
|
|
18
|
+
export class Sim {
|
|
19
|
+
contract;
|
|
20
|
+
decode;
|
|
21
|
+
/** The contract's address in this simulation (kernel.self()). */
|
|
22
|
+
address = sampleContractAddress();
|
|
23
|
+
/** Coin public key of the caller for the next call(); change with as(). */
|
|
24
|
+
coinPublicKey;
|
|
25
|
+
/** The private state the next call's witnesses see. Assign to swap it. */
|
|
26
|
+
privateState;
|
|
27
|
+
/** The context the last call returned: zswap inputs/outputs, gas, etc. */
|
|
28
|
+
lastContext;
|
|
29
|
+
state;
|
|
30
|
+
constructor(contract, decode, state, privateState, coinPublicKey) {
|
|
31
|
+
this.contract = contract;
|
|
32
|
+
this.decode = decode;
|
|
33
|
+
this.state = state;
|
|
34
|
+
this.privateState = privateState;
|
|
35
|
+
this.coinPublicKey = coinPublicKey;
|
|
36
|
+
}
|
|
37
|
+
/** Runs the constructor and returns a simulation of the deployed contract. */
|
|
38
|
+
static async deploy(opts) {
|
|
39
|
+
const coinPublicKey = opts.coinPublicKey ?? SIM_COIN_PUBLIC_KEY;
|
|
40
|
+
const args = (opts.args ?? []);
|
|
41
|
+
const result = await opts.contract.initialState(createConstructorContext(opts.privateState, coinPublicKey), ...args);
|
|
42
|
+
return new Sim(opts.contract, opts.ledger, result.currentContractState.data, result.currentPrivateState, coinPublicKey);
|
|
43
|
+
}
|
|
44
|
+
/** Makes later calls come from this coin public key (hex). */
|
|
45
|
+
as(coinPublicKey) {
|
|
46
|
+
this.coinPublicKey = coinPublicKey;
|
|
47
|
+
return this;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Calls an impure circuit as one transaction. On success the public and
|
|
51
|
+
* private state move forward; if the circuit throws (a failed assert), the
|
|
52
|
+
* error propagates and neither changes.
|
|
53
|
+
*/
|
|
54
|
+
async call(circuit, ...args) {
|
|
55
|
+
const fn = this.contract.impureCircuits[circuit];
|
|
56
|
+
if (typeof fn !== 'function')
|
|
57
|
+
throw new Error(`${circuit} is not an impure circuit of this contract`);
|
|
58
|
+
const context = createCircuitContext({
|
|
59
|
+
circuitId: circuit,
|
|
60
|
+
contractAddress: this.address,
|
|
61
|
+
coinPublicKeyOrZswapState: this.coinPublicKey,
|
|
62
|
+
contractState: this.state,
|
|
63
|
+
privateState: this.privateState,
|
|
64
|
+
});
|
|
65
|
+
const out = await fn.call(this.contract.impureCircuits, context, ...args);
|
|
66
|
+
this.state = out.context.callContext.currentQueryContext.state;
|
|
67
|
+
this.privateState = out.context.callContext.currentPrivateState;
|
|
68
|
+
this.lastContext = out.context;
|
|
69
|
+
return { result: out.result, ledger: this.decode(this.state) };
|
|
70
|
+
}
|
|
71
|
+
/** The decoded public ledger, as an indexer would show it. */
|
|
72
|
+
ledger() {
|
|
73
|
+
return this.decode(this.state);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Runs `fn` and returns the error it throws. Fails if it doesn't throw, or if
|
|
78
|
+
* `message` is given and the error message doesn't contain it. Use it for
|
|
79
|
+
* every guard: `await expectRejects(() => sim.call('withdraw', ...), 'not the owner')`.
|
|
80
|
+
*/
|
|
81
|
+
export async function expectRejects(fn, message) {
|
|
82
|
+
let thrown;
|
|
83
|
+
try {
|
|
84
|
+
await fn();
|
|
85
|
+
}
|
|
86
|
+
catch (e) {
|
|
87
|
+
thrown = e;
|
|
88
|
+
}
|
|
89
|
+
if (thrown === undefined)
|
|
90
|
+
throw new Error(`expected a rejection${message ? ` containing "${message}"` : ''}, but the call succeeded`);
|
|
91
|
+
const err = thrown instanceof Error ? thrown : new Error(String(thrown));
|
|
92
|
+
if (message !== undefined && !err.message.includes(message)) {
|
|
93
|
+
throw new Error(`expected a rejection containing "${message}", got: ${err.message}`);
|
|
94
|
+
}
|
|
95
|
+
return err;
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,14 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@midnightntwrk/mnkit-sim",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
3
|
+
"version": "0.2.0-rc.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "In-memory contract harness for Midnight tests: deploy and call a compiled Compact contract without a network, expect rejections, and check that no secret reaches public state. Part of mnkit.",
|
|
5
6
|
"license": "Apache-2.0",
|
|
6
7
|
"repository": {
|
|
7
8
|
"type": "git",
|
|
8
9
|
"url": "git+https://github.com/midnightntwrk/midnight-examples.git",
|
|
9
10
|
"directory": "packages/sim"
|
|
10
11
|
},
|
|
12
|
+
"homepage": "https://github.com/midnightntwrk/midnight-examples/tree/main/packages/sim#readme",
|
|
13
|
+
"bugs": "https://github.com/midnightntwrk/midnight-examples/issues",
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=22.0.0"
|
|
16
|
+
},
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
11
25
|
"files": [
|
|
12
|
-
"
|
|
13
|
-
]
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"build": "tsc -p tsconfig.build.json",
|
|
30
|
+
"prepack": "tsc -p tsconfig.build.json && node ../../scripts/pack-extras.mjs add LICENSE",
|
|
31
|
+
"postpack": "node ../../scripts/pack-extras.mjs remove LICENSE",
|
|
32
|
+
"typecheck": "tsc --noEmit -p .",
|
|
33
|
+
"test:sim": "vitest run"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@midnight-ntwrk/midnight-js-protocol": "~5.0.1"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@midnight-ntwrk/midnight-js-protocol": "5.0.1",
|
|
40
|
+
"@types/node": "^22.0.0",
|
|
41
|
+
"typescript": "^5.7.0",
|
|
42
|
+
"vite": "6.4.5",
|
|
43
|
+
"vitest": "^5.0.4"
|
|
44
|
+
}
|
|
14
45
|
}
|