-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathmain.ts
437 lines (409 loc) · 12.3 KB
/
main.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
433
434
435
436
437
import * as fs from 'fs';
import _ from 'underscore';
import timeSpan from 'time-span';
import cloneDeep from 'clone-deep';
import {
BlockHistory,
stakingWithoutSlashing,
bondBasedConsumerVotingPower
} from './properties.js';
import { Sanity as SanityChecker } from './sanity.js';
import { Model } from './model.js';
import {
createSmallSubsetOfCoveringTraces,
dumpTrace,
forceMakeEmptyDir,
logEventData,
} from './util.js';
import {
P,
C,
NUM_VALIDATORS,
BLOCK_SECONDS,
TOKEN_SCALAR,
MAX_BLOCK_ADVANCES,
} from './constants.js';
interface Action {
kind: string;
}
type Delegate = {
kind: string;
val: number;
amt: number;
};
type Undelegate = {
kind: string;
val: number;
amt: number;
};
type JumpNBlocks = {
kind: string;
chains: string[];
n: number;
secondsPerBlock: number;
};
type Deliver = {
kind: string;
chain: string;
numPackets: string;
};
type ConsumerSlash = {
kind: string;
val: number;
infractionHeight: number;
isDowntime: number;
};
/**
* Takes an object where values are probabilities and returns a random
* key based on the distribution.
*/
function weightedRandomKey(distr) {
const scalar = _.reduce(_.values(distr), (sum, y) => sum + y, 0);
const x = Math.random() * scalar;
const pairs = _.pairs(distr);
let i = 0;
let cum = 0;
while (i < pairs.length - 1 && cum + pairs[i][1] < x) {
cum += pairs[i][1];
i += 1;
}
return pairs[i][0];
}
class ActionGenerator {
model;
didSlash = new Array(NUM_VALIDATORS).fill(false);
constructor(model) {
this.model = model;
}
/**
* Get a new model action.
* An action is chosen by a process of generating and then selecting
* template actions based on the current state of the model.
* In this way, only actions which make sense given the current state
* of the model can be returned. Among the possible actions, one is
* chosen based on a probability distribution.
* @returns An executable model action
*/
get = () => {
// Get candidate actions
let templates: Action[] = _.flatten([
this.candidateDelegate(),
this.candidateUndelegate(),
this.candidateJumpNBlocks(),
this.candidateDeliver(),
this.candidateConsumerSlash(),
]);
// Get the names of each possible action
const possibleActions = _.uniq(templates.map((a) => a.kind));
// Build a probability distribution for each possible action
const distr = _.pick(
{
Delegate: 0.03,
Undelegate: 0.03,
JumpNBlocks: 0.37,
Deliver: 0.55,
ConsumerSlash: 0.02,
},
...possibleActions,
);
// Choose an action type (kind) based on the probability distribution
const kind = weightedRandomKey(distr);
templates = templates.filter((a) => a.kind === kind);
const a = _.sample(templates);
if (kind === 'Delegate') {
return this.selectDelegate(a);
}
if (kind === 'Undelegate') {
return this.selectUndelegate(a);
}
if (kind === 'JumpNBlocks') {
return this.selectJumpNBlocks(a);
}
if (kind === 'Deliver') {
return this.selectDeliver(a);
}
if (kind === 'ConsumerSlash') {
return this.selectConsumerSlash(a);
}
throw `kind doesn't match`;
};
// Return templates for possible delegate actions
candidateDelegate = (): Action[] => {
return _.range(NUM_VALIDATORS).map((i) => {
return {
kind: 'Delegate',
val: i,
};
});
};
// Fill out template for a selected Delegate action
selectDelegate = (a): Delegate => {
return { ...a, amt: _.random(1, 5) * TOKEN_SCALAR };
};
// Return templates for possible undelegate actions
candidateUndelegate = (): Action[] => {
return _.range(NUM_VALIDATORS).map((i) => {
return {
kind: 'Undelegate',
val: i,
};
});
};
// Fill out template for a selected Undelegate action
selectUndelegate = (a): Undelegate => {
return { ...a, amt: _.random(1, 4) * TOKEN_SCALAR };
};
// Return templates for possible Consumer initiated slash actions
candidateConsumerSlash = (): Action[] => {
return _.range(NUM_VALIDATORS)
// Filter out absent validators
.filter((i) => this.model.ccvC.power[i] !== undefined)
// Filter out validators if slashing that validator would
// lead to all validators being jailed.
.filter((i) => {
const cntWouldBeNotJailed = this.didSlash.filter(
(slashed, j) => !slashed && j !== i,
).length;
return 1 <= cntWouldBeNotJailed;
})
.map((i) => {
return { kind: 'ConsumerSlash', val: i };
});
};
// Fill out a template for a selected Consumer initiated slash action
selectConsumerSlash = (a): ConsumerSlash => {
this.didSlash[a.val] = true;
return {
...a,
infractionHeight: Math.floor(Math.random() * this.model.h[C]),
isDowntime: _.sample([true, false]),
};
};
// Return templates for possible JumpNBlocks actions
candidateJumpNBlocks = (): Action[] => [{ kind: 'JumpNBlocks' }];
// Fill out a template for a selected JumpNBlocks action
selectJumpNBlocks = (a): JumpNBlocks => {
// A JumpNBlocks action must be chosen to not advance either
// chain too far ahead so that the IBC clients would expire as a result.
const chainCandidates = [];
if (
this.model.sanity.tLastCommit[P] ===
this.model.sanity.tLastCommit[C]
) {
// In case that both chains share the same last commit timestamp
// either chain can be advanced.
chainCandidates.push([P, C]);
}
// Else, choose the chain that advanced furthest in the past.
else if (
this.model.sanity.tLastCommit[P] < this.model.sanity.tLastCommit[C]
) {
chainCandidates.push([P]);
} else {
chainCandidates.push([C]);
}
a = {
...a,
chains: _.sample(chainCandidates),
// Choose the number of blocks from {1, MAX_JUMP}
n: _.sample([1, MAX_BLOCK_ADVANCES]),
secondsPerBlock: BLOCK_SECONDS,
};
return a;
};
// Return templates for possible packet Deliver actions
candidateDeliver = (): Action[] => {
return [P, C]
// Only choose a candidate chain if there are deliverable packets available
// in the network.
.filter((c) => 0 < this.model.outbox[c == P ? C : P].numAvailable())
.map((c) => {
return {
kind: 'Deliver',
chain: c,
};
});
};
// Fill out a selected Deliver action template
selectDeliver = (a): Deliver => {
a = {
...a,
// Randomly choose to deliver 1 or more packets
numPackets: _.random(
1,
this.model.outbox[a.chain == P ? C : P].numAvailable(),
),
};
return a;
};
}
/**
* Executes an action against the model, thereby updating the model state.
* @param model The model instance
* @param action The action to be executed against the model
*/
function doAction(model, action: Action) {
const kind = action.kind;
if (kind === 'Delegate') {
const a = action as Delegate;
model.delegate(a.val, a.amt);
}
if (kind === 'Undelegate') {
const a = action as Undelegate;
model.undelegate(a.val, a.amt);
}
if (kind === 'JumpNBlocks') {
const a = action as JumpNBlocks;
model.jumpNBlocks(a.n, a.chains, a.secondsPerBlock);
}
if (kind === 'Deliver') {
const a = action as Deliver;
model.deliver(a.chain, a.numPackets);
}
if (kind === 'ConsumerSlash') {
const a = action as ConsumerSlash;
model.consumerSlash(a.val, a.infractionHeight, a.isDowntime);
}
}
/**
* Generates traces by repeatedly creating new model instances
* and executing randomly generated actions against them.
* The trace consists of data including the actions taken, and the
* successive model states that result from the actions. Additional
* data is included
* @param minutes The number of minutes to generate traces.
*/
function gen(minutes) {
// Compute millis run time
const runTimeMillis = minutes * 60 * 1000;
let elapsedMillis = 0;
// Number of actions to execute against each model instance
// Free parameter!
const NUM_ACTIONS = 200;
// Directory to output traces in json format
const DIR = 'traces/';
forceMakeEmptyDir(DIR);
let i = 0;
// Track the model events that occur during the generation process
// this data is used to check that all events are emitted by some
// trace.
const allEvents = [];
while (elapsedMillis < runTimeMillis) {
i += 1;
const end = timeSpan();
////////////////////////
const sanity = new SanityChecker();
const hist = new BlockHistory();
// Store all events emitted during trace execution
const events = [];
const model = new Model(sanity, hist, events);
const actionGenerator = new ActionGenerator(model);
const actions = [];
for (let j = 0; j < NUM_ACTIONS; j++) {
const a = actionGenerator.get();
doAction(model, a);
actions.push({
// Store the action taken
action: a,
// Store a snapshot of the model state at the given block commit
// this is used for model comparisons when testing the SUT.
hLastCommit: cloneDeep(hist.hLastCommit),
});
}
// Check properties
if (!bondBasedConsumerVotingPower(hist)) {
throw "bondBasedConsumerVotingPower property failure"
}
if (!stakingWithoutSlashing(hist)) {
throw "stakingWithoutSlashing property failure"
}
// Write the trace to file, along with metadata.
dumpTrace(`${DIR}trace_${i}.json`, events, actions, hist.blocks);
// Accumulate all events
allEvents.push(...events);
////////////////////////
elapsedMillis += end.rounded();
// Log progress stats
if (i % 2000 === 0) {
console.log(
`done ${i}, actions per second ${(i * NUM_ACTIONS) / (elapsedMillis / 1000)
}`,
);
}
}
logEventData(allEvents);
}
/**
* Replays a list of actions against a new model instance.
* This function is best used to debug the model or to debug
* a failing test against the SUT. In this manner it is possible
* to step through the model execution and the SUT execution of trace
* side-by-side.
* The model is deterministic, thus a fixed list of actions always
* results in the same behavior and model states.
* @param actions
*/
function replay(actions: Action[]) {
const sanity = new SanityChecker();
const blocks = new BlockHistory();
const events = [];
const model = new Model(sanity, blocks, events);
for (let i = 0; i < actions.length; i++) {
const a = actions[i];
doAction(model, a);
}
}
/**
* @param fn filename of the file containing the json traces
* @param ix the index of the trace in the json
* @param numActions The number of actions to replay from the trace. If numActions
* is less than the length of the trace, then execution will complete before
* the entire trace has been executed. This helps with debugging because it makes
* logs shorter.
*/
function replayFile(fn: string, ix: number, numActions: number) {
const traces = JSON.parse(fs.readFileSync(fn, 'utf8'));
const trace = ix !== undefined ? traces[ix] : traces[0];
const actions = trace.actions.map((a) => a.action).slice(0, numActions);
replay(actions);
}
console.log(`running main`);
/*
* Generate new traces and write them to files, for <minutes> minutes.
*
* yarn start gen <minutes>
*/
if (process.argv[2] === 'gen') {
console.log(`gen`);
const minutes = parseInt(process.argv[3]);
gen(minutes);
}
/*
* Creates a trace file containing several traces, in a way that ensures
* each interesting model event is emitted by some trace.
*
* yarn start subset <output file abs path> <num event instances (optional)>
*/
else if (process.argv[2] === 'subset') {
console.log(`createSmallSubsetOfCoveringTraces`);
const outFile = process.argv[3]
let eventInstances = 20
if (3 < process.argv.length) {
eventInstances = parseInt(process.argv[4])
}
createSmallSubsetOfCoveringTraces(outFile, eventInstances);
}
/*
* Replay a trace from a a file, up to a given number of actions.
*
* yarn start replay <filename> <list index> <num actions>
*/
else if (process.argv[2] === 'replay') {
console.log(`replay`);
const [fn, traceNum, numActions] = process.argv.slice(3, 6);
replayFile(fn, parseInt(traceNum), parseInt(numActions));
} else {
console.log(`did not execute any function`);
}
console.log(`finished running main`);
export { gen };