-
Notifications
You must be signed in to change notification settings - Fork 215
/
Copy pathlaunch-chain.js
1220 lines (1078 loc) · 38.6 KB
/
launch-chain.js
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
/* eslint-env node */
// XXX the JSON configs specify that launching the chain requires @agoric/builders,
// so let the JS tooling know about it by importing it here.
import '@agoric/builders';
import anylogger from 'anylogger';
import { assert, Fail } from '@endo/errors';
import { E } from '@endo/far';
import bundleSource from '@endo/bundle-source';
import {
buildMailbox,
buildMailboxStateMap,
buildTimer,
buildBridge,
swingsetIsInitialized,
initializeSwingset,
makeSwingsetController,
loadBasedir,
loadSwingsetConfigFile,
normalizeConfig,
upgradeSwingset,
} from '@agoric/swingset-vat';
import { waitUntilQuiescent } from '@agoric/internal/src/lib-nodejs/waitUntilQuiescent.js';
import { openSwingStore } from '@agoric/swing-store';
import { BridgeId as BRIDGE_ID } from '@agoric/internal';
import { makeWithQueue } from '@agoric/internal/src/queue.js';
import * as ActionType from '@agoric/internal/src/action-types.js';
import {
extractCoreProposalBundles,
mergeCoreProposals,
} from '@agoric/deploy-script-support/src/extract-proposal.js';
import { fileURLToPath } from 'url';
import {
makeDefaultMeterProvider,
makeInboundQueueMetrics,
exportKernelStats,
makeSlogCallbacks,
} from './kernel-stats.js';
import { parseParams } from './params.js';
import { makeQueue, makeQueueStorageMock } from './helpers/make-queue.js';
import { exportStorage } from './export-storage.js';
import { parseLocatedJson } from './helpers/json.js';
import { computronCounter } from './computron-counter.js';
/** @import { BlockInfo } from '@agoric/internal/src/chain-utils.js' */
/** @import { Mailbox, RunPolicy, SwingSetConfig } from '@agoric/swingset-vat' */
/** @import { KVStore, BufferedKVStore } from './helpers/bufferedStorage.js' */
/** @typedef {ReturnType<typeof makeQueue<{context: any, action: any}>>} InboundQueue */
const console = anylogger('launch-chain');
const blockManagerConsole = anylogger('block-manager');
/**
* @param {{ info: string } | null | undefined} upgradePlan
* @param {string} prefix
*/
const parseUpgradePlanInfo = (upgradePlan, prefix = '') => {
const { info: upgradeInfoJson = null } = upgradePlan || {};
const upgradePlanInfo =
upgradeInfoJson &&
parseLocatedJson(
upgradeInfoJson,
`${prefix && `${prefix} `}upgradePlan.info`,
);
return harden(upgradePlanInfo || {});
};
/**
* @typedef {object} CosmicSwingsetConfig
* @property {import('@agoric/deploy-script-support/src/extract-proposal.js').ConfigProposal[]} [coreProposals]
* @property {string[]} [clearStorageSubtrees] chain storage paths identifying
* roots of subtrees for which data should be deleted (including overlaps with
* exportStorageSubtrees, which are *not* preserved).
* @property {string[]} [exportStorageSubtrees] chain storage paths identifying roots of subtrees
* for which data should be exported into bootstrap vat parameter `chainStorageEntries`
* (e.g., `exportStorageSubtrees: ['c.o']` might result in vatParameters including
* `chainStorageEntries: [ ['c.o', '"top"'], ['c.o.i'], ['c.o.i.n', '42'], ['c.o.w', '"moo"'] ]`).
*/
/**
* @typedef {'leftover' | 'forced' | 'high-priority' | 'timer' | 'queued' | 'cleanup'} CrankerPhase
* - leftover: work from a previous block
* - forced: work that claims the entirety of the current block
* - high-priority: queued work the precedes timer advancement
* - intermission: needed to note state exports and update consistency hashes
* - queued: queued work the follows timer advancement
* - cleanup: for dealing with data from terminated vats
*/
/** @type {CrankerPhase} */
const CLEANUP = 'cleanup';
/**
* @typedef {(phase: CrankerPhase) => Promise<boolean>} Cranker runs the kernel
* and reports if it is time to stop
*/
/**
* Return the key in the reserved "host.*" section of the swing-store
*
* @param {string} path
*/
const getHostKey = path => `host.${path}`;
/**
* @param {KVStore<Mailbox>} mailboxStorage
* @param {((destPort: string, msg: unknown) => unknown)} bridgeOutbound
* @param {SwingStoreKernelStorage} kernelStorage
* @param {import('@endo/far').ERef<string | SwingSetConfig> | (() => ERef<string | SwingSetConfig>)} getVatConfig
* @param {unknown} bootstrapArgs JSON-serializable data
* @param {{}} env
* @param {*} options
*/
export async function buildSwingset(
mailboxStorage,
bridgeOutbound,
kernelStorage,
getVatConfig,
bootstrapArgs,
env,
{
callerWillEvaluateCoreProposals = !!bridgeOutbound,
debugName = undefined,
slogCallbacks,
slogSender,
verbose,
profileVats,
debugVats,
warehousePolicy,
},
) {
const debugPrefix = debugName === undefined ? '' : `${debugName}:`;
const mbs = buildMailboxStateMap(mailboxStorage);
const bridgeDevice = buildBridge(bridgeOutbound);
const mailboxDevice = buildMailbox(mbs);
const timerDevice = buildTimer();
const deviceEndowments = {
mailbox: { ...mailboxDevice.endowments },
timer: { ...timerDevice.endowments },
bridge: { ...bridgeDevice.endowments },
};
async function ensureSwingsetInitialized() {
if (swingsetIsInitialized(kernelStorage)) {
return;
}
const { config, configLocation } = await (async () => {
const objOrPath = await (typeof getVatConfig === 'function'
? getVatConfig()
: getVatConfig);
if (typeof objOrPath === 'string') {
const path = objOrPath;
const configFromFile = await loadSwingsetConfigFile(path);
const obj = configFromFile || loadBasedir(path);
return { config: obj, configLocation: path };
}
await normalizeConfig(objOrPath);
return { config: objOrPath, configLocation: undefined };
})();
config.devices = {
mailbox: {
sourceSpec: mailboxDevice.srcPath,
},
timer: {
sourceSpec: timerDevice.srcPath,
},
};
if (bridgeDevice) {
config.devices.bridge = {
sourceSpec: bridgeDevice.srcPath,
};
}
const {
coreProposals,
clearStorageSubtrees,
exportStorageSubtrees = [],
...swingsetConfig
} = /** @type {SwingSetConfig & CosmicSwingsetConfig} */ (config);
// XXX `initializeSwingset` does not have a default for the `bootstrap` property;
// should we universally ensure its presence above?
const bootVat =
swingsetConfig.vats[swingsetConfig.bootstrap || 'bootstrap'];
const batchChainStorage = (method, args) =>
bridgeOutbound(BRIDGE_ID.STORAGE, { method, args });
// Extract data from chain storage as [path, value?] pairs.
const chainStorageEntries = exportStorage(
batchChainStorage,
exportStorageSubtrees,
clearStorageSubtrees,
);
bootVat.parameters = { ...bootVat.parameters, chainStorageEntries };
// Since only on-chain swingsets like `agd` have a bridge (and thereby
// `CORE_EVAL` support), things like `ag-solo` will need to do the
// coreProposals in the bootstrap vat.
let bridgedCoreProposals;
if (callerWillEvaluateCoreProposals) {
// We have a bridge to run the coreProposals, so do it in the caller.
bridgedCoreProposals = coreProposals;
} else if (coreProposals) {
// We don't have a bridge to run the coreProposals, so do it in the bootVat.
const { bundles, codeSteps } = await extractCoreProposalBundles(
coreProposals,
configLocation, // for path resolution
);
swingsetConfig.bundles = { ...swingsetConfig.bundles, ...bundles };
bootVat.parameters = {
...bootVat.parameters,
coreProposalCodeSteps: codeSteps,
};
}
swingsetConfig.pinBootstrapRoot = true;
await initializeSwingset(swingsetConfig, bootstrapArgs, kernelStorage, {
// @ts-expect-error debugPrefix? what's that?
debugPrefix,
});
// Let our caller schedule our core proposals.
return bridgedCoreProposals;
}
const pendingCoreProposals = await ensureSwingsetInitialized();
const { modified } = upgradeSwingset(kernelStorage);
const controller = await makeSwingsetController(
kernelStorage,
deviceEndowments,
{
env,
slogCallbacks,
slogSender,
verbose,
profileVats,
debugVats,
warehousePolicy,
},
);
// We DON'T want to run the kernel yet, only when the application decides
// (either on bootstrap block (0) or in endBlock).
return {
coreProposals: pendingCoreProposals,
controller,
kernelHasUpgradeEvents: modified,
mb: mailboxDevice,
bridgeInbound: bridgeDevice.deliverInbound,
timer: timerDevice,
};
}
/**
* @typedef {RunPolicy & {
* shouldRun(): boolean;
* remainingBeans(): bigint | undefined;
* totalBeans(): bigint;
* startCleanup(): boolean;
* }} ChainRunPolicy
*/
/**
* @template [T=unknown]
* @typedef {object} LaunchOptions
* @property {import('./helpers/make-queue.js').QueueStorage} actionQueueStorage
* @property {import('./helpers/make-queue.js').QueueStorage} highPriorityQueueStorage
* @property {string} [kernelStateDBDir]
* @property {import('@agoric/swing-store').SwingStore} [swingStore]
* @property {BufferedKVStore<Mailbox>} mailboxStorage
* TODO: Merge together BufferedKVStore and QueueStorage (get/set/delete/commit/abort)
* @property {() => Promise<unknown>} clearChainSends
* @property {() => void} replayChainSends
* @property {((destPort: string, msg: unknown) => unknown)} bridgeOutbound
* @property {() => ({publish: (value: unknown) => Promise<void>})} [makeInstallationPublisher]
* @property {import('@endo/far').ERef<string | SwingSetConfig> | (() => ERef<string | SwingSetConfig>)} vatconfig
* either an object or a path to a file which JSON-decodes into an object,
* provided directly or through a thunk and/or promise. If the result is an
* object, it may be mutated to normalize and/or extend it.
* @property {unknown} argv for the bootstrap vat (and despite the name, usually
* an object rather than an array)
* @property {typeof process['env']} [env]
* @property {string} [debugName]
* @property {boolean} [verboseBlocks]
* @property {ReturnType<typeof import('./kernel-stats.js').makeDefaultMeterProvider>} [metricsProvider]
* @property {import('@agoric/telemetry').SlogSender} [slogSender]
* @property {string} [swingStoreTraceFile]
* @property {(...args: unknown[]) => void} [swingStoreExportCallback]
* @property {boolean} [keepSnapshots]
* @property {boolean} [keepTranscripts]
* @property {ReturnType<typeof import('@agoric/swing-store').makeArchiveSnapshot>} [archiveSnapshot]
* @property {ReturnType<typeof import('@agoric/swing-store').makeArchiveTranscript>} [archiveTranscript]
* @property {() => object | Promise<object>} [afterCommitCallback]
* @property {import('./chain-main.js').CosmosSwingsetConfig} swingsetConfig
* TODO refactor to clarify relationship vs. import('@agoric/swingset-vat').SwingSetConfig
* --- maybe partition into in-consensus "config" vs. consensus-independent "options"?
* (which would mostly just require `bundleCachePath` to become a `buildSwingset` input)
*/
/**
* @param {LaunchOptions} options
*/
export async function launch({
actionQueueStorage,
highPriorityQueueStorage,
kernelStateDBDir,
swingStore,
mailboxStorage,
clearChainSends,
replayChainSends,
bridgeOutbound,
makeInstallationPublisher,
vatconfig,
argv,
env = process.env,
debugName = undefined,
verboseBlocks = false,
metricsProvider = makeDefaultMeterProvider(),
slogSender,
swingStoreTraceFile,
swingStoreExportCallback,
keepSnapshots,
keepTranscripts,
archiveSnapshot,
archiveTranscript,
afterCommitCallback = async () => ({}),
swingsetConfig,
}) {
console.info('Launching SwingSet kernel');
// The swingstore export-data callback gives us export-data records,
// which must be written into IAVL by sending them over to the
// golang side with swingStoreExportCallback . However, that
// callback isn't ready right away, so if e.g. openSwingStore() were
// to invoke it, we might lose those records. Likewise
// saveOutsideState() gathers the chainSends just before calling
// commit, so if the callback were invoked during commit(), those
// records would be left for a subsequent block, which would break
// consensus if the node crashed before the next commit. So this
// `allowExportCallback` flag serves to catch these two cases.
//
// Note that swingstore is within its rights to call exportCallback
// during openSwingStore() or commit(), it just happens to not do so
// right now. If that changes under maintenance, this guard should
// turn a corruption bug into a crash bug. See
// https://github.com/Agoric/agoric-sdk/issues/9655 for details
let allowExportCallback = false;
// The swingStore's exportCallback is synchronous, however we allow the
// callback provided to launch-chain to be asynchronous. The callbacks are
// invoked sequentially like if they were awaited, and the block manager
// synchronizes before finishing END_BLOCK
let pendingSwingStoreExport = Promise.resolve();
const swingStoreExportSyncCallback = (() => {
if (!swingStoreExportCallback) return undefined;
const enqueueSwingStoreExportCallback = makeWithQueue()(
swingStoreExportCallback,
);
return updates => {
assert(allowExportCallback, 'export-data callback called at bad time');
pendingSwingStoreExport = enqueueSwingStoreExportCallback(updates);
};
})();
if (swingStore) {
!swingStoreExportCallback ||
Fail`swingStoreExportCallback is not compatible with a provided swingStore; either drop the former or allow launch to open the latter`;
kernelStateDBDir === undefined ||
kernelStateDBDir === swingStore.internal.dirPath ||
Fail`provided kernelStateDBDir does not match provided swingStore`;
}
const { kernelStorage, hostStorage } =
swingStore ||
openSwingStore(/** @type {string} */ (kernelStateDBDir), {
traceFile: swingStoreTraceFile,
exportCallback: swingStoreExportSyncCallback,
keepSnapshots,
keepTranscripts,
archiveSnapshot,
archiveTranscript,
});
const { kvStore, commit } = hostStorage;
/** @type {InboundQueue} */
const actionQueue = makeQueue(actionQueueStorage);
/** @type {InboundQueue} */
const highPriorityQueue = makeQueue(highPriorityQueueStorage);
/**
* In memory queue holding actions that must be consumed entirely
* during the block. If it's not drained, we open the gates to
* hangover hell.
*
* @type {InboundQueue}
*/
const runThisBlock = makeQueue(makeQueueStorageMock().storage);
// Not to be confused with the gas model, this meter is for OpenTelemetry.
const metricMeter = metricsProvider.getMeter('ag-chain-cosmos');
const slogCallbacks = makeSlogCallbacks({
metricMeter,
});
console.debug(`buildSwingset`);
const warehousePolicy = {
maxVatsOnline: swingsetConfig.maxVatsOnline,
};
const {
coreProposals: bootstrapCoreProposals,
controller,
kernelHasUpgradeEvents,
mb,
bridgeInbound,
timer,
} = await buildSwingset(
mailboxStorage,
bridgeOutbound,
kernelStorage,
vatconfig,
argv,
env,
{
debugName,
slogCallbacks,
slogSender,
warehousePolicy,
},
);
/** @type {{publish: (value: unknown) => Promise<void>} | undefined} */
let installationPublisher;
// Artificially create load if set.
const END_BLOCK_SPIN_MS = env.END_BLOCK_SPIN_MS
? parseInt(env.END_BLOCK_SPIN_MS, 10)
: 0;
const inboundQueueMetrics = makeInboundQueueMetrics(
actionQueue.size() + highPriorityQueue.size(),
);
const { crankScheduler } = exportKernelStats({
controller,
metricMeter,
// @ts-expect-error Type 'Logger<BaseLevels>' is not assignable to type 'Console'.
log: console,
inboundQueueMetrics,
});
/**
* @param {number} blockHeight
* @param {ChainRunPolicy} runPolicy
* @returns {Cranker}
*/
function makeRunSwingset(blockHeight, runPolicy) {
let runNum = 0;
async function runSwingset(phase) {
if (phase === CLEANUP) {
const allowCleanup = runPolicy.startCleanup();
if (!allowCleanup) return false;
}
const startBeans = runPolicy.totalBeans();
controller.writeSlogObject({
type: 'cosmic-swingset-run-start',
blockHeight,
runNum,
phase,
startBeans,
remainingBeans: runPolicy.remainingBeans(),
});
// TODO: crankScheduler does a schedulerBlockTimeHistogram thing
// that needs to be revisited, it used to be called once per
// block, now it's once per processed inbound queue item
await crankScheduler(runPolicy);
const finishBeans = runPolicy.totalBeans();
controller.writeSlogObject({
type: 'kernel-stats',
stats: controller.getStats(),
});
controller.writeSlogObject({
type: 'cosmic-swingset-run-finish',
blockHeight,
runNum,
phase,
startBeans,
finishBeans,
usedBeans: finishBeans - startBeans,
remainingBeans: runPolicy.remainingBeans(),
});
runNum += 1;
return runPolicy.shouldRun();
}
return runSwingset;
}
async function bootstrapBlock(blockHeight, blockTime, params) {
// We need to let bootstrap know of the chain time. The time of the first
// block may be the genesis time, or the block time of the upgrade block.
timer.poll(blockTime);
// This is before the initial block, we need to finish processing the
// entire bootstrap before opening for business.
const runPolicy = computronCounter(params, true);
const runSwingset = makeRunSwingset(blockHeight, runPolicy);
await runSwingset('forced');
}
async function saveChainState() {
// Save the mailbox state.
await mailboxStorage.commit();
}
async function saveOutsideState(blockHeight) {
allowExportCallback = false;
const chainSends = await clearChainSends();
kvStore.set(getHostKey('height'), `${blockHeight}`);
kvStore.set(getHostKey('chainSends'), JSON.stringify(chainSends));
await commit();
}
async function doKernelUpgradeEvents(inboundNum) {
controller.writeSlogObject({
type: 'cosmic-swingset-inject-kernel-upgrade-events',
inboundNum,
});
controller.injectQueuedUpgradeEvents();
}
async function deliverInbound(sender, messages, ack, inboundNum) {
Array.isArray(messages) || Fail`inbound given non-Array: ${messages}`;
controller.writeSlogObject({
type: 'cosmic-swingset-deliver-inbound',
inboundNum,
sender,
count: messages.length,
messages,
ack,
});
if (!mb.deliverInbound(sender, messages, ack)) {
return;
}
console.debug(`mboxDeliver: ADDED messages`);
}
async function doBridgeInbound(source, body, inboundNum) {
controller.writeSlogObject({
type: 'cosmic-swingset-bridge-inbound',
inboundNum,
source,
body,
});
if (!bridgeInbound) throw Fail`bridgeInbound undefined`;
// console.log(`doBridgeInbound`);
// the inbound bridge will push messages onto the kernel run-queue for
// delivery+dispatch to some handler vat
bridgeInbound(source, body);
}
async function installBundle(bundleJson, inboundNum) {
let bundle;
try {
bundle = JSON.parse(bundleJson);
} catch (e) {
blockManagerConsole.warn('INSTALL_BUNDLE warn:', e);
return;
}
harden(bundle);
const error = await controller.validateAndInstallBundle(bundle).then(
() => null,
(/** @type {unknown} */ errorValue) => errorValue,
);
const { endoZipBase64Sha512 } = bundle;
controller.writeSlogObject({
type: 'cosmic-swingset-install-bundle',
inboundNum,
endoZipBase64Sha512,
error,
});
if (installationPublisher === undefined) {
return;
}
await installationPublisher.publish(
harden({
endoZipBase64Sha512,
installed: error === null,
error,
}),
);
}
function provideInstallationPublisher() {
if (
installationPublisher === undefined &&
makeInstallationPublisher !== undefined
) {
installationPublisher = makeInstallationPublisher();
}
}
let savedHeight = Number(kvStore.get(getHostKey('height')) || 0);
let savedBeginHeight = Number(
kvStore.get(getHostKey('beginHeight')) || savedHeight,
);
/**
* duration of the latest swingset execution in either END_BLOCK or
* once-per-chain bootstrap (the latter excluding "bridged" core proposals
* that run outside the bootstrap vat)
*/
let runTime = 0;
/** duration of the latest saveChainState(), which commits mailbox data to chain storage */
let chainTime;
/** duration of the latest saveOutsideState(), which commits to swing-store host storage */
let saveTime = 0;
let endBlockFinish = 0;
let blockParams;
let decohered;
let afterCommitWorkDone = Promise.resolve();
async function performAction(action, inboundNum) {
// blockManagerConsole.error('Performing action', action);
let p;
switch (action.type) {
case ActionType.DELIVER_INBOUND: {
p = deliverInbound(
action.peer,
action.messages,
action.ack,
inboundNum,
);
break;
}
case ActionType.VBANK_BALANCE_UPDATE: {
p = doBridgeInbound(BRIDGE_ID.BANK, action, inboundNum);
break;
}
case ActionType.IBC_EVENT: {
p = doBridgeInbound(BRIDGE_ID.DIBC, action, inboundNum);
break;
}
case ActionType.VTRANSFER_IBC_EVENT: {
p = doBridgeInbound(BRIDGE_ID.VTRANSFER, action, inboundNum);
break;
}
case ActionType.PLEASE_PROVISION: {
p = doBridgeInbound(BRIDGE_ID.PROVISION, action, inboundNum);
break;
}
case ActionType.KERNEL_UPGRADE_EVENTS: {
p = doKernelUpgradeEvents(inboundNum);
break;
}
case ActionType.INSTALL_BUNDLE: {
p = installBundle(action.bundle, inboundNum);
break;
}
case ActionType.CORE_EVAL: {
p = doBridgeInbound(BRIDGE_ID.CORE, action, inboundNum);
break;
}
case ActionType.WALLET_ACTION: {
p = doBridgeInbound(BRIDGE_ID.WALLET, action, inboundNum);
break;
}
case ActionType.WALLET_SPEND_ACTION: {
p = doBridgeInbound(BRIDGE_ID.WALLET, action, inboundNum);
break;
}
default: {
Fail`${action.type} not recognized`;
}
}
return p;
}
/**
* Process as much as we can from an inbound queue, which contains
* first the old actions not previously processed, followed by actions
* newly added, running the kernel to completion after each.
*
* @param {InboundQueue} inboundQueue
* @param {Cranker} runSwingset
* @param {CrankerPhase} phase
*/
async function processActions(inboundQueue, runSwingset, phase) {
let keepGoing = true;
for await (const { action, context } of inboundQueue.consumeAll()) {
const inboundNum = `${context.blockHeight}-${context.txHash}-${context.msgIdx}`;
inboundQueueMetrics.decStat();
await performAction(action, inboundNum);
keepGoing = await runSwingset(phase);
if (!keepGoing) {
// any leftover actions will remain on the inbound queue for possible
// processing in the next block
break;
}
}
return keepGoing;
}
/**
* Trigger the Swingset runs for this block, stopping when out of relevant
* work or when instructed to (whichever comes first).
*
* @param {Cranker} runSwingset
* @param {BlockInfo['blockHeight']} blockHeight
* @param {BlockInfo['blockTime']} blockTime
*/
async function processBlockActions(runSwingset, blockHeight, blockTime) {
// First, complete leftover work, if any
let keepGoing = await runSwingset('leftover');
if (!keepGoing) return;
// Then, if we have anything in the special runThisBlock queue, process
// it and do no further work.
if (runThisBlock.size()) {
await processActions(runThisBlock, runSwingset, 'forced');
return;
}
// Then, process as much as we can from the priorityQueue.
keepGoing = await processActions(
highPriorityQueue,
runSwingset,
'high-priority',
);
if (!keepGoing) return;
// Then, update the timer device with the new external time, which might
// push work onto the kernel run-queue (if any timers were ready to wake).
const addedToQueue = timer.poll(blockTime);
controller.writeSlogObject({
type: 'cosmic-swingset-timer-poll',
blockHeight,
blockTime,
added: addedToQueue,
});
console.debug(
`polled; blockTime:${blockTime}, h:${blockHeight}; ADDED =`,
addedToQueue,
);
// We must run the kernel even if nothing was added since the kernel
// only notes state exports and updates consistency hashes when attempting
// to perform a crank.
keepGoing = await runSwingset('timer');
if (!keepGoing) return;
// Finally, process as much as we can from the actionQueue.
await processActions(actionQueue, runSwingset, 'queued');
// Cleanup after terminated vats as allowed.
await runSwingset('cleanup');
}
async function endBlock(blockHeight, blockTime, params) {
// This is called once per block, during the END_BLOCK event, and
// only when we know that cosmos is in sync (else we'd skip kernel
// execution).
// First, record new actions (bridge/mailbox/etc events that cosmos
// added up for delivery to swingset) into our inboundQueue metrics
inboundQueueMetrics.updateLength(
actionQueue.size() + highPriorityQueue.size() + runThisBlock.size(),
);
// If we have work to complete this block, it needs to run to completion.
// It will also run to completion any work that swingset still had pending.
const neverStop = runThisBlock.size() > 0;
// Process the work for this block using a dedicated Cranker with a stateful
// run policy.
const runPolicy = computronCounter(params, neverStop);
const runSwingset = makeRunSwingset(blockHeight, runPolicy);
await processBlockActions(runSwingset, blockHeight, blockTime);
if (END_BLOCK_SPIN_MS) {
// Introduce a busy-wait to artificially put load on the chain.
const startTime = Date.now();
while (Date.now() - startTime < END_BLOCK_SPIN_MS);
}
}
/**
* @template T
* @param {string} label
* @param {() => Promise<T>} fn
* @param {() => void} onSettled
*/
function withErrorLogging(label, fn, onSettled) {
const p = fn();
void E.when(p, onSettled, err => {
blockManagerConsole.error(label, 'error:', err);
onSettled();
});
return p;
}
function blockNeedsExecution(blockHeight) {
if (savedHeight === 0) {
// 0 is the default we use when the DB is empty, so we've only executed
// the bootstrap block but no others. The first non-bootstrap block can
// have an arbitrary height (the chain may not start at 1), but since the
// bootstrap block doesn't commit (and doesn't have a begin/end) there is
// no risk of hangover inconsistency for the first block, and it can
// always be executed.
return true;
}
if (blockHeight === savedHeight + 1) {
// execute the next block
return true;
}
if (blockHeight === savedHeight) {
// we have already committed this block, so "replay" by not executing
// (but returning all the results from the last time)
return false;
}
// we're being asked to rewind by more than one block, or execute something
// more than one block in the future, neither of which we can accommodate.
// Keep throwing forever.
decohered = Error(
// TODO unimplemented
`Unimplemented reset state from ${savedHeight} to ${blockHeight}`,
);
throw decohered;
}
function saveBeginHeight(blockHeight) {
savedBeginHeight = blockHeight;
kvStore.set(getHostKey('beginHeight'), `${savedBeginHeight}`);
}
async function afterCommit(blockHeight, blockTime) {
await waitUntilQuiescent()
.then(afterCommitCallback)
.then((afterCommitStats = {}) => {
controller.writeSlogObject({
type: 'cosmic-swingset-after-commit-stats',
blockHeight,
blockTime,
...afterCommitStats,
});
});
}
const doBootstrap = async action => {
const { blockTime, blockHeight, params } = action;
controller.writeSlogObject({
type: 'cosmic-swingset-bootstrap-block-start',
blockTime,
});
await null;
try {
verboseBlocks && blockManagerConsole.info('block bootstrap');
(savedHeight === 0 && savedBeginHeight === 0) ||
Fail`Cannot run a bootstrap block at height ${savedHeight}`;
const bootstrapBlockParams = parseParams(params);
// Start a block transaction, but without changing state
// for the upcoming begin block check
saveBeginHeight(savedBeginHeight);
const start = Date.now();
await withErrorLogging(
action.type,
() => bootstrapBlock(blockHeight, blockTime, bootstrapBlockParams),
() => {
runTime += Date.now() - start;
},
);
} finally {
controller.writeSlogObject({
type: 'cosmic-swingset-bootstrap-block-finish',
blockTime,
});
}
};
const doCoreProposals = async ({ blockHeight, blockTime }, coreProposals) => {
controller.writeSlogObject({
type: 'cosmic-swingset-upgrade-start',
blockHeight,
blockTime,
coreProposals,
});
await null;
try {
// Start a block transaction, but without changing state
// for the upcoming begin block check
saveBeginHeight(savedBeginHeight);
// Find scripts relative to our location.
const myFilename = fileURLToPath(import.meta.url);
const { bundles, codeSteps: coreEvalCodeSteps } =
await extractCoreProposalBundles(coreProposals, myFilename, {
handleToBundleSpec: async (handle, source, _sequence, _piece) => {
const bundle = await bundleSource(source);
const { endoZipBase64Sha512: hash } = bundle;
const bundleID = `b1-${hash}`;
handle.bundleID = bundleID;
harden(handle);
return harden([`${bundleID}: ${source}`, bundle]);
},
});
for (const [meta, bundle] of Object.entries(bundles)) {
await controller
.validateAndInstallBundle(bundle)
.catch(e => Fail`Cannot validate and install ${meta}: ${e}`);
}
// Now queue each step's code for evaluation.
for (const [key, coreEvalCode] of Object.entries(coreEvalCodeSteps)) {
const coreEvalAction = {
type: ActionType.CORE_EVAL,
blockHeight,
blockTime,
evals: [
{
json_permits: 'true',
js_code: coreEvalCode,
},
],
};
runThisBlock.push({
context: {
blockHeight,
txHash: 'x/upgrade',
msgIdx: key,
},
action: coreEvalAction,
});
}
} finally {
controller.writeSlogObject({
type: 'cosmic-swingset-upgrade-finish',
blockHeight,
blockTime,
});
}
};
// Handle block related actions
// Some actions that are integration specific may be handled by the caller
// For example SWING_STORE_EXPORT is handled in chain-main.js
async function doBlockingSend(action) {
await null;
// blockManagerConsole.warn(
// 'FIGME: blockHeight',
// action.blockHeight,
// 'received',
// action.type,
// );
switch (action.type) {
case ActionType.AG_COSMOS_INIT: {
allowExportCallback = true; // cleared by saveOutsideState in COMMIT_BLOCK
const { blockHeight, isBootstrap, upgradeDetails } = action;
// TODO: parseParams(action.params), for validation?
if (!blockNeedsExecution(blockHeight)) {
return true;
}
const softwareUpgradeCoreProposals = upgradeDetails?.coreProposals;
const { coreProposals: upgradeInfoCoreProposals } =
parseUpgradePlanInfo(upgradeDetails?.plan, ActionType.AG_COSMOS_INIT);