-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathlaunch-chain.js
More file actions
163 lines (146 loc) · 4.72 KB
/
launch-chain.js
File metadata and controls
163 lines (146 loc) · 4.72 KB
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
import fs from 'fs';
import djson from 'deterministic-json';
import readlines from 'n-readlines';
import {
buildMailbox,
buildMailboxStateMap,
buildTimer,
buildVatController,
getCommsSourcePath,
getTimerWrapperSourcePath,
getVatTPSourcePath,
} from '@agoric/swingset-vat';
import { buildStorageInMemory } from '@agoric/swingset-vat/src/hostStorage';
async function buildSwingset(withSES, mailboxState, storage, vatsDir, argv) {
const config = {};
const mbs = buildMailboxStateMap();
mbs.populateFromData(mailboxState);
const timer = buildTimer();
const mb = buildMailbox(mbs);
config.devices = [
['mailbox', mb.srcPath, mb.endowments],
['timer', timer.srcPath, timer.endowments],
];
config.vats = new Map();
for (const fname of fs.readdirSync(vatsDir)) {
const match = fname.match(/^vat-(.*)\.js$/);
if (match) {
config.vats.set(match[1], {
sourcepath: require.resolve(`${vatsDir}/${fname}`),
});
}
}
config.vats.set('vattp', { sourcepath: getVatTPSourcePath() });
config.vats.set('comms', {
sourcepath: getCommsSourcePath(),
options: { enablePipelining: true },
});
config.vats.set('timer', { sourcepath: getTimerWrapperSourcePath() });
config.bootstrapIndexJS = require.resolve(`${vatsDir}/bootstrap.js`);
config.hostStorage = storage;
const controller = await buildVatController(config, withSES, argv);
await controller.run();
return { controller, mb, mbs, timer };
}
export async function launch(mailboxStorage, stateFile, vatsDir, argv) {
const withSES = true;
console.log(
`launch: checking for saved mailbox state`,
mailboxStorage.has('mailbox'),
);
const mailboxState = mailboxStorage.has('mailbox')
? JSON.parse(mailboxStorage.get('mailbox'))
: {};
const storage = buildStorageInMemory();
let l;
try {
// stateFile will be missing the first time we launch
l = new readlines(stateFile);
} catch (e) {
console.log(`initializing empty swingset state`);
}
if (l) {
let line;
while ((line = l.next())) {
const [key, value] = JSON.parse(line);
storage.storage.set(key, value);
}
}
console.log(`buildSwingset`);
const { controller, mb, mbs, timer } = await buildSwingset(
withSES,
mailboxState,
storage.storage,
vatsDir,
argv,
);
function saveKernelState() {
const tmpfn = `${stateFile}.tmp`;
const fd = fs.openSync(tmpfn, 'w');
let size = 0;
for (let [key, value] of storage.map.entries()) {
const line = JSON.stringify([key, value]);
fs.writeSync(fd, line);
fs.writeSync(fd, '\n');
size += line.length + 1;
}
fs.closeSync(fd);
fs.renameSync(tmpfn, stateFile);
return size;
}
function saveState() {
// save kernel state to the stateFile, and the mailbox state to a cosmos
// kvstore where it can be queried externally
const kernelStateSize = saveKernelState();
const mailboxStateData = djson.stringify(mbs.exportToData());
mailboxStorage.set(`mailbox`, mailboxStateData);
return [kernelStateSize, mailboxStateData.length];
}
// save the initial state immediately
saveState();
// then arrange for inbound messages to be processed, after which we save
async function turnCrank() {
const oldData = djson.stringify(mbs.exportToData());
let start = Date.now();
await controller.run();
const runTime = Date.now() - start;
// now check mbs
start = Date.now();
const newState = mbs.exportToData();
const newData = djson.stringify(newState);
if (newData !== oldData) {
console.log(`outbox changed`);
for (const peer of Object.getOwnPropertyNames(newState)) {
const data = {
outbox: newState[peer].outbox,
ack: newState[peer].inboundAck,
};
mailboxStorage.set(`mailbox.${peer}`, djson.stringify(data));
}
}
const mbTime = Date.now() - start;
start = Date.now();
const [kernelSize, mailboxSize] = saveState();
const saveTime = Date.now() - start;
console.log(
`wrote SwingSet checkpoint (kernel=${kernelSize}, mailbox=${mailboxSize}), [run=${runTime}ms, mb=${mbTime}ms, save=${saveTime}ms]`,
);
}
async function deliverInbound(sender, messages, ack) {
if (!(messages instanceof Array)) {
throw new Error(`inbound given non-Array: ${messages}`);
}
if (mb.deliverInbound(sender, messages, ack)) {
console.log(`mboxDeliver: ADDED messages`);
await turnCrank();
}
}
async function deliverStartBlock(blockHeight, blockTime) {
const addedToQueue = timer.poll(blockTime);
console.log(
`polled; blockTime:${blockTime}, h:${blockHeight} ADDED: ${addedToQueue}`,
);
await turnCrank();
}
return { deliverInbound, deliverStartBlock };
}