-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinvariant.ts
414 lines (376 loc) · 13.2 KB
/
invariant.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import { Simnet } from "@hirosystems/clarinet-sdk";
import { EventEmitter } from "events";
import {
argsToCV,
isTraitReferenceFunction,
functionToArbitrary,
getFunctionsListForContract,
} from "./shared";
import { LocalContext } from "./invariant.types";
import { Cl, cvToJSON } from "@stacks/transactions";
import { reporter } from "./heatstroke";
import fc from "fast-check";
import { dim, green, red, underline } from "ansicolor";
import { ContractInterfaceFunction } from "@hirosystems/clarinet-sdk-wasm";
export const checkInvariants = (
simnet: Simnet,
sutContractName: string,
rendezvousList: string[],
rendezvousAllFunctions: Map<string, ContractInterfaceFunction[]>,
seed: number | undefined,
path: string | undefined,
runs: number | undefined,
radio: EventEmitter
) => {
// A map where the keys are the Rendezvous identifiers and the values are
// arrays of their SUT (System Under Test) functions. This map will be used
// to access the SUT functions for each Rendezvous contract afterwards.
const rendezvousSutFunctions = filterSutFunctions(rendezvousAllFunctions);
// A map where the keys are the Rendezvous identifiers and the values are
// arrays of their invariant functions. This map will be used to access the
// invariant functions for each Rendezvous contract afterwards.
const rendezvousInvariantFunctions = filterInvariantFunctions(
rendezvousAllFunctions
);
// Set up local context to track SUT function call counts.
const localContext = initializeLocalContext(rendezvousSutFunctions);
// Set up context in simnet by initializing state for SUT.
initializeClarityContext(simnet, rendezvousSutFunctions);
radio.emit(
"logMessage",
`\nStarting invariant testing type for the ${sutContractName} contract...\n`
);
const simnetAccounts = simnet.getAccounts();
const eligibleAccounts = new Map(
[...simnetAccounts].filter(([key]) => key !== "faucet")
);
const simnetAddresses = Array.from(simnetAccounts.values());
// The Rendezvous identifier is the first one in the list. Only one contract
// can be fuzzed at a time.
const rendezvousContractId = rendezvousList[0];
const functions = getFunctionsListForContract(
rendezvousSutFunctions,
rendezvousContractId
);
const invariantFunctions = getFunctionsListForContract(
rendezvousInvariantFunctions,
rendezvousContractId
);
if (functions?.length === 0) {
radio.emit(
"logMessage",
red(
`No public functions found for the "${sutContractName}" contract. Without public functions, no state transitions can happen inside the contract, and the invariant test is not meaningful.\n`
)
);
return;
}
if (invariantFunctions?.length === 0) {
radio.emit(
"logMessage",
red(
`No invariant functions found for the "${sutContractName}" contract. Beware, for your contract may be exposed to unforeseen issues.\n`
)
);
return;
}
const eligibleFunctions = functions.filter(
(fn) => !isTraitReferenceFunction(fn)
);
const eligibleInvariants = invariantFunctions.filter(
(fn) => !isTraitReferenceFunction(fn)
);
if (eligibleFunctions.length === 0) {
radio.emit(
"logMessage",
red(
`No eligible public functions found for the "${sutContractName}" contract. Note: trait references are not supported.\n`
)
);
return;
}
if (eligibleInvariants.length === 0) {
radio.emit(
"logMessage",
red(
`No eligible invariant functions found for the "${sutContractName}" contract. Note: trait references are not supported.\n`
)
);
return;
}
const radioReporter = (runDetails: any) => {
reporter(runDetails, radio, "invariant");
};
fc.assert(
fc.property(
fc
.record({
// The target contract identifier. It is a constant value equal
// to the first contract in the list. The arbitrary is still needed,
// being used for reporting purposes in `heatstroke.ts`.
rendezvousContractId: fc.constant(rendezvousContractId),
sutCaller: fc.constantFrom(...eligibleAccounts.entries()),
invariantCaller: fc.constantFrom(...eligibleAccounts.entries()),
canMineBlocks: fc.boolean(),
})
.chain((r) =>
fc
.record({
selectedFunction: fc.constantFrom(...eligibleFunctions),
selectedInvariant: fc.constantFrom(...eligibleInvariants),
})
.map((selectedFunctions) => ({ ...r, ...selectedFunctions }))
)
.chain((r) =>
fc
.record({
functionArgsArb: fc.tuple(
...functionToArbitrary(r.selectedFunction, simnetAddresses)
),
invariantArgsArb: fc.tuple(
...functionToArbitrary(r.selectedInvariant, simnetAddresses)
),
})
.map((args) => ({ ...r, ...args }))
)
.chain((r) =>
fc
.record({
burnBlocks: r.canMineBlocks
? // This arbitrary produces integers with a maximum value
// inversely proportional to the number of runs:
// - Fewer runs result in a higher maximum burn blocks,
// allowing more blocks to be mined.
// - More runs result in a lower maximum burn blocks, as more
// blocks are mined overall.
fc.integer({
min: 1,
max: Math.ceil(100_000 / (runs || 100)),
})
: fc.constant(0),
})
.map((burnBlocks) => ({ ...r, ...burnBlocks }))
),
(r) => {
const selectedFunctionArgs = argsToCV(
r.selectedFunction,
r.functionArgsArb
);
const selectedInvariantArgs = argsToCV(
r.selectedInvariant,
r.invariantArgsArb
);
const printedFunctionArgs = r.functionArgsArb
.map((arg) => {
try {
return typeof arg === "object"
? JSON.stringify(arg)
: arg.toString();
} catch {
return "[Circular]";
}
})
.join(" ");
const [sutCallerWallet, sutCallerAddress] = r.sutCaller;
try {
const { result: functionCallResult } = simnet.callPublicFn(
r.rendezvousContractId,
r.selectedFunction.name,
selectedFunctionArgs,
sutCallerAddress
);
const functionCallResultJson = cvToJSON(functionCallResult);
if (functionCallResultJson.success) {
localContext[r.rendezvousContractId][r.selectedFunction.name]++;
simnet.callPublicFn(
r.rendezvousContractId,
"update-context",
[
Cl.stringAscii(r.selectedFunction.name),
Cl.uint(
localContext[r.rendezvousContractId][r.selectedFunction.name]
),
],
simnet.deployer
);
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
dim(`${sutCallerWallet} `) +
`${sutContractName} ` +
`${underline(r.selectedFunction.name)} ` +
printedFunctionArgs
);
} else {
radio.emit(
"logMessage",
dim(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${sutCallerWallet} ` +
`${sutContractName} ` +
`${underline(r.selectedFunction.name)} ` +
printedFunctionArgs
)
);
}
} catch (error: any) {
// If the function call fails with a runtime error, log a dimmed
// message. Since the public function result is ignored, there's
// no need to throw an error.
radio.emit(
"logMessage",
dim(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${sutCallerWallet} ` +
`${sutContractName} ` +
`${underline(r.selectedFunction.name)} ` +
printedFunctionArgs
)
);
}
const printedInvariantArgs = r.invariantArgsArb
.map((arg) => {
try {
return typeof arg === "object"
? JSON.stringify(arg)
: arg.toString();
} catch {
return "[Circular]";
}
})
.join(" ");
const [invariantCallerWallet, invariantCallerAddress] =
r.invariantCaller;
try {
const { result: invariantCallResult } = simnet.callReadOnlyFn(
r.rendezvousContractId,
r.selectedInvariant.name,
selectedInvariantArgs,
invariantCallerAddress
);
const invariantCallResultJson = cvToJSON(invariantCallResult);
if (invariantCallResultJson.value === true) {
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${dim(invariantCallerWallet)} ` +
`${green("[PASS]")} ` +
`${sutContractName} ` +
`${underline(r.selectedInvariant.name)} ` +
printedInvariantArgs
);
}
if (!invariantCallResultJson.value) {
throw new Error(
`Invariant failed for ${sutContractName} contract: "${r.selectedInvariant.name}" returned ${invariantCallResultJson.value}`
);
}
} catch (error: any) {
// Handle both negative results from the invariant function and
// general runtime failures. Focus is on capturing the invariant
// function's result, including any runtime errors it caused.
radio.emit(
"logMessage",
red(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${invariantCallerWallet} ` +
`[FAIL] ` +
`${sutContractName} ` +
`${underline(r.selectedInvariant.name)} ` +
printedInvariantArgs
)
);
// Re-throw the error for fast-check to catch and process.
throw error;
}
if (r.canMineBlocks) {
simnet.mineEmptyBurnBlocks(r.burnBlocks);
}
}
),
{
verbose: true,
reporter: radioReporter,
seed: seed,
path: path,
numRuns: runs,
}
);
};
/**
* Initialize the local context, setting the number of times each function
* has been called to zero.
* @param rendezvousSutFunctions The Rendezvous functions.
* @returns The initialized local context.
*/
export const initializeLocalContext = (
rendezvousSutFunctions: Map<string, ContractInterfaceFunction[]>
): LocalContext =>
Object.fromEntries(
Array.from(rendezvousSutFunctions.entries()).map(
([contractId, functions]) => [
contractId,
Object.fromEntries(functions.map((f) => [f.name, 0])),
]
)
);
export const initializeClarityContext = (
simnet: Simnet,
rendezvousSutFunctions: Map<string, ContractInterfaceFunction[]>
) =>
rendezvousSutFunctions.forEach((fns, contractId) => {
fns.forEach((fn) => {
const { result: initialize } = simnet.callPublicFn(
contractId,
"update-context",
[Cl.stringAscii(fn.name), Cl.uint(0)],
simnet.deployer
);
const jsonResult = cvToJSON(initialize);
if (!jsonResult.value || !jsonResult.success) {
throw new Error(
`Failed to initialize the context for function: ${fn.name}.`
);
}
});
});
/**
* Filter the System Under Test (`SUT`) functions from the map of all
* contract functions.
*
* The SUT functions are the ones that have `public` access since they are
* capable of changing the contract state, and they are not test functions.
* @param allFunctionsMap The map containing all the functions for each
* contract.
* @returns A map containing only the SUT functions for each contract.
*/
const filterSutFunctions = (
allFunctionsMap: Map<string, ContractInterfaceFunction[]>
) =>
new Map(
Array.from(allFunctionsMap, ([contractId, functions]) => [
contractId,
functions.filter(
(f) =>
f.access === "public" &&
f.name !== "update-context" &&
!f.name.startsWith("test-")
),
])
);
const filterInvariantFunctions = (
allFunctionsMap: Map<string, ContractInterfaceFunction[]>
) =>
new Map(
Array.from(allFunctionsMap, ([contractId, functions]) => [
contractId,
functions.filter(
(f) => f.access === "read_only" && f.name.startsWith("invariant-")
),
])
);