-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproperty.ts
432 lines (394 loc) · 13.6 KB
/
property.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
import { Simnet } from "@hirosystems/clarinet-sdk";
import { EventEmitter } from "events";
import fc from "fast-check";
import { cvToJSON } from "@stacks/transactions";
import { reporter } from "./heatstroke";
import {
argsToCV,
functionToArbitrary,
getContractNameFromContractId,
getFunctionsListForContract,
isTraitReferenceFunction,
} from "./shared";
import { dim, green, red, underline, yellow } from "ansicolor";
import { ContractInterfaceFunction } from "@hirosystems/clarinet-sdk-wasm";
export const checkProperties = (
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 test contract identifiers and the values are
// arrays of their test functions. This map will be used to access the test
// functions for each test contract in the property-based testing routine.
const testContractsTestFunctions = filterTestFunctions(
rendezvousAllFunctions
);
radio.emit(
"logMessage",
`\nStarting property testing type for the ${sutContractName} contract...\n`
);
// Search for discard functions, for each test function. This map will
// be used to pair the test functions with their corresponding discard
// functions.
const testContractsDiscardFunctions = new Map(
Array.from(rendezvousAllFunctions, ([contractId, functions]) => [
contractId,
functions.filter(
(f) => f.access === "read_only" && f.name.startsWith("can-")
),
])
);
// Pair each test function with its corresponding discard function. When a
// test function is selected, Rendezvous will first call its discard
// function, to allow or prevent the property test from running.
const testContractsPairedFunctions = new Map(
Array.from(testContractsTestFunctions, ([contractId, functions]) => [
contractId,
new Map(
functions.map((f) => {
const discardFunction = testContractsDiscardFunctions
.get(contractId)
?.find((pf) => pf.name === `can-${f.name}`);
return [f.name, discardFunction?.name];
})
),
])
);
const hasDiscardFunctionErrors = Array.from(
testContractsPairedFunctions
).some(([contractId, pairedMap]) =>
Array.from(pairedMap).some(([testFunctionName, discardFunctionName]) =>
discardFunctionName
? !validateDiscardFunction(
contractId,
discardFunctionName,
testFunctionName,
testContractsDiscardFunctions,
testContractsTestFunctions,
radio
)
: false
)
);
if (hasDiscardFunctionErrors) {
return;
}
const simnetAccounts = simnet.getAccounts();
const eligibleAccounts = new Map(
[...simnetAccounts].filter(([key]) => key !== "faucet")
);
const simnetAddresses = Array.from(simnetAccounts.values());
const testContractId = rendezvousList[0];
const testFunctions = getFunctionsListForContract(
testContractsTestFunctions,
testContractId
);
if (testFunctions?.length === 0) {
radio.emit(
"logMessage",
red(`No test functions found for the "${sutContractName}" contract.\n`)
);
return;
}
const eligibleTestFunctions = testFunctions.filter(
(fn) => !isTraitReferenceFunction(fn)
);
if (eligibleTestFunctions.length === 0) {
radio.emit(
"logMessage",
red(
`No eligible test functions found for the "${sutContractName}" contract. Note: trait references are not supported.\n`
)
);
return;
}
const radioReporter = (runDetails: any) => {
reporter(runDetails, radio, "test");
};
fc.assert(
fc.property(
fc
.record({
testContractId: fc.constant(testContractId),
testCaller: fc.constantFrom(...eligibleAccounts.entries()),
canMineBlocks: fc.boolean(),
})
.chain((r) =>
fc
.record({
selectedTestFunction: fc.constantFrom(
...(eligibleTestFunctions as ContractInterfaceFunction[])
),
})
.map((selectedTestFunction) => ({
...r,
...selectedTestFunction,
}))
)
.chain((r) =>
fc
.record({
functionArgsArb: fc.tuple(
...functionToArbitrary(r.selectedTestFunction, 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 selectedTestFunctionArgs = argsToCV(
r.selectedTestFunction,
r.functionArgsArb
);
const printedTestFunctionArgs = r.functionArgsArb
.map((arg) => {
try {
return typeof arg === "object"
? JSON.stringify(arg)
: arg.toString();
} catch {
return "[Circular]";
}
})
.join(" ");
const [testCallerWallet, testCallerAddress] = r.testCaller;
const discardFunctionName = testContractsPairedFunctions
.get(r.testContractId)!
.get(r.selectedTestFunction.name);
const discarded = isTestDiscarded(
discardFunctionName,
selectedTestFunctionArgs,
r.testContractId,
simnet,
testCallerAddress
);
if (discarded) {
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${dim(testCallerWallet)} ` +
`${yellow("[WARN]")} ` +
`${sutContractName} ` +
`${underline(r.selectedTestFunction.name)} ` +
dim(printedTestFunctionArgs)
);
} else {
try {
// If the function call results in a runtime error, the error will
// be caught and logged as a test failure in the catch block.
const { result: testFunctionCallResult } = simnet.callPublicFn(
r.testContractId,
r.selectedTestFunction.name,
selectedTestFunctionArgs,
testCallerAddress
);
const testFunctionCallResultJson = cvToJSON(testFunctionCallResult);
const discardedInPlace = isTestDiscardedInPlace(
testFunctionCallResultJson
);
if (discardedInPlace) {
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${dim(testCallerWallet)} ` +
`${yellow("[WARN]")} ` +
`${sutContractName} ` +
`${underline(r.selectedTestFunction.name)} ` +
dim(printedTestFunctionArgs)
);
} else if (
!discardedInPlace &&
testFunctionCallResultJson.success &&
testFunctionCallResultJson.value.value === true
) {
radio.emit(
"logMessage",
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${dim(testCallerWallet)} ` +
`${green("[PASS]")} ` +
`${sutContractName} ` +
`${underline(r.selectedTestFunction.name)} ` +
printedTestFunctionArgs
);
if (r.canMineBlocks) {
simnet.mineEmptyBurnBlocks(r.burnBlocks);
}
} else {
throw new Error(
`Test failed for ${sutContractName} contract: "${r.selectedTestFunction.name}" returned ${testFunctionCallResultJson.value.value}`
);
}
} catch (error: any) {
// Capture the error and log the test failure.
radio.emit(
"logMessage",
red(
`₿ ${simnet.burnBlockHeight.toString().padStart(8)} ` +
`Ӿ ${simnet.blockHeight.toString().padStart(8)} ` +
`${testCallerWallet} ` +
`[FAIL] ` +
`${sutContractName} ` +
`${underline(r.selectedTestFunction.name)} ` +
printedTestFunctionArgs
)
);
// Re-throw the error for fast-check to catch and process.
throw error;
}
}
}
),
{
verbose: true,
reporter: radioReporter,
seed: seed,
path: path,
numRuns: runs,
}
);
};
const filterTestFunctions = (
allFunctionsMap: Map<string, ContractInterfaceFunction[]>
) =>
new Map(
Array.from(allFunctionsMap, ([contractId, functions]) => [
contractId,
functions.filter(
(f) => f.access === "public" && f.name.startsWith("test-")
),
])
);
export const isTestDiscardedInPlace = (testFunctionCallResultJson: any) =>
testFunctionCallResultJson.success === true &&
testFunctionCallResultJson.value.value === false;
/**
* Check if the test function has to be discarded.
* @param discardFunctionName The discard function name.
* @param selectedTestFunctionArgs The generated test function arguments.
* @param contractId The contract identifier.
* @param simnet The simnet instance.
* @param selectedCaller The selected caller.
* @returns A boolean indicating if the test function has to be discarded.
*/
const isTestDiscarded = (
discardFunctionName: string | undefined,
selectedTestFunctionArgs: any[],
contractId: string,
simnet: Simnet,
selectedCaller: string
) => {
if (!discardFunctionName) return false;
const { result: discardFunctionCallResult } = simnet.callReadOnlyFn(
contractId,
discardFunctionName,
selectedTestFunctionArgs,
selectedCaller
);
const jsonDiscardFunctionCallResult = cvToJSON(discardFunctionCallResult);
return jsonDiscardFunctionCallResult.value === false;
};
/**
* Validate the discard function, ensuring that its parameters match the test
* function's parameters and that its return type is boolean.
* @param contractId The contract identifier.
* @param discardFunctionName The discard function name.
* @param testFunctionName The test function name.
* @param testContractsDiscardFunctions The discard functions map.
* @param testContractsTestFunctions The test functions map.
* @param radio The radio event emitter.
* @returns A boolean indicating if the discard function passes the checks.
*/
const validateDiscardFunction = (
contractId: string,
discardFunctionName: string,
testFunctionName: string,
testContractsDiscardFunctions: Map<string, ContractInterfaceFunction[]>,
testContractsTestFunctions: Map<string, ContractInterfaceFunction[]>,
radio: EventEmitter
) => {
const testFunction = testContractsTestFunctions
.get(contractId)
?.find((f) => f.name === testFunctionName);
const discardFunction = testContractsDiscardFunctions
.get(contractId)
?.find((f) => f.name === discardFunctionName);
if (!testFunction || !discardFunction) return false;
if (!isParamsMatch(testFunction, discardFunction)) {
radio.emit(
"logMessage",
red(
`\nError: Parameter mismatch for discard function "${discardFunctionName}" in contract "${getContractNameFromContractId(
contractId
)}".\n`
)
);
return false;
}
if (!isReturnTypeBoolean(discardFunction)) {
radio.emit(
"logMessage",
red(
`\nError: Return type must be boolean for discard function "${discardFunctionName}" in contract "${getContractNameFromContractId(
contractId
)}".\n`
)
);
return false;
}
return true;
};
/**
* Verify if the test function parameters match the discard function
* parameters.
* @param testFunction The test function's interface.
* @param discardFunction The discard function's interface.
* @returns A boolean indicating if the parameters match.
*/
export const isParamsMatch = (
testFunction: ContractInterfaceFunction,
discardFunction: ContractInterfaceFunction
) => {
const sortedTestFunctionArgs = [...testFunction.args].sort((a, b) =>
a.name.localeCompare(b.name)
);
const sortedDiscardFunctionArgs = [...discardFunction.args].sort((a, b) =>
a.name.localeCompare(b.name)
);
return (
JSON.stringify(sortedTestFunctionArgs) ===
JSON.stringify(sortedDiscardFunctionArgs)
);
};
/**
* Verify if the discard function's return type is boolean.
* @param discardFunction The discard function's interface.
* @returns A boolean indicating if the return type is boolean.
*/
export const isReturnTypeBoolean = (
discardFunction: ContractInterfaceFunction
) => discardFunction.outputs.type === "bool";