feat: add caching of the last consensus update via leveldb
This commit is contained in:
parent
41704501f8
commit
9f35ea7f9b
31
src/index.ts
31
src/index.ts
|
@ -17,6 +17,7 @@ import {
|
||||||
} from "@lumeweb/libethsync/client";
|
} from "@lumeweb/libethsync/client";
|
||||||
import * as capella from "@lodestar/types/capella";
|
import * as capella from "@lodestar/types/capella";
|
||||||
import defer from "p-defer";
|
import defer from "p-defer";
|
||||||
|
import { Level } from "level";
|
||||||
|
|
||||||
onmessage = handleMessage;
|
onmessage = handleMessage;
|
||||||
|
|
||||||
|
@ -28,6 +29,9 @@ const clientInitDefer = defer();
|
||||||
|
|
||||||
let client: EthClient;
|
let client: EthClient;
|
||||||
let rpc: RpcNetwork;
|
let rpc: RpcNetwork;
|
||||||
|
const db = new Level<number | string, Uint8Array>("consensus", {
|
||||||
|
valueEncoding: "buffer",
|
||||||
|
});
|
||||||
|
|
||||||
addHandler("presentKey", handlePresentKey);
|
addHandler("presentKey", handlePresentKey);
|
||||||
addHandler("register", handleRegister);
|
addHandler("register", handleRegister);
|
||||||
|
@ -131,6 +135,7 @@ async function executionHandler(data: Map<string, string | any>) {
|
||||||
|
|
||||||
async function setup() {
|
async function setup() {
|
||||||
rpc = createRpcClient();
|
rpc = createRpcClient();
|
||||||
|
await db.open();
|
||||||
await rpc.ready;
|
await rpc.ready;
|
||||||
|
|
||||||
client = createEthClient(
|
client = createEthClient(
|
||||||
|
@ -155,13 +160,39 @@ async function setup() {
|
||||||
500,
|
500,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let lastUpdate = 0;
|
||||||
|
|
||||||
|
client.store.on("set", async (period: number, update: Uint8Array) => {
|
||||||
|
if (period < lastUpdate) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await db.put("latest", update);
|
||||||
|
lastUpdate = period;
|
||||||
|
});
|
||||||
|
|
||||||
clientInitDefer.resolve();
|
clientInitDefer.resolve();
|
||||||
|
|
||||||
let synced = false;
|
let synced = false;
|
||||||
|
|
||||||
while (!synced) {
|
while (!synced) {
|
||||||
try {
|
try {
|
||||||
|
let consensus;
|
||||||
|
try {
|
||||||
|
consensus = await db.get("latest");
|
||||||
|
} catch {}
|
||||||
|
|
||||||
|
if (consensus) {
|
||||||
|
try {
|
||||||
|
await client.syncFromCheckpoint(
|
||||||
|
capella.ssz.LightClientUpdate.deserialize(consensus),
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
await client.sync();
|
await client.sync();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await client.sync();
|
||||||
|
}
|
||||||
|
|
||||||
synced = true;
|
synced = true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logErr(e.message);
|
logErr(e.message);
|
||||||
|
|
Loading…
Reference in New Issue