@secondlayer/shared 15.3.3 → 15.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/archive/range-digest.d.ts +7 -0
- package/dist/src/archive/semantic-digest-builder.d.ts +7 -0
- package/dist/src/classify/index.js +16 -2
- package/dist/src/classify/index.js.map +3 -3
- package/dist/src/coverage/index.d.ts +15 -1
- package/dist/src/coverage/index.js +57 -2
- package/dist/src/coverage/index.js.map +4 -4
- package/dist/src/crypto/secondlayer-webhook.js +16 -2
- package/dist/src/crypto/secondlayer-webhook.js.map +3 -3
- package/dist/src/crypto/secrets.d.ts +8 -2
- package/dist/src/crypto/secrets.js +21 -7
- package/dist/src/crypto/secrets.js.map +3 -3
- package/dist/src/db/index.d.ts +15 -1
- package/dist/src/db/index.js +29 -7
- package/dist/src/db/index.js.map +5 -5
- package/dist/src/db/queries/chain-reorgs.d.ts +7 -0
- package/dist/src/db/queries/chain-reorgs.js +27 -7
- package/dist/src/db/queries/chain-reorgs.js.map +5 -5
- package/dist/src/db/queries/contracts.d.ts +21 -1
- package/dist/src/db/queries/contracts.js +23 -1
- package/dist/src/db/queries/contracts.js.map +4 -4
- package/dist/src/db/queries/instance.d.ts +33 -5
- package/dist/src/db/queries/instance.js +224 -14
- package/dist/src/db/queries/instance.js.map +6 -5
- package/dist/src/db/queries/integrity.d.ts +84 -1
- package/dist/src/db/queries/integrity.js +430 -15
- package/dist/src/db/queries/integrity.js.map +8 -6
- package/dist/src/db/queries/subgraph-gaps.d.ts +18 -6
- package/dist/src/db/queries/subgraph-gaps.js +81 -14
- package/dist/src/db/queries/subgraph-gaps.js.map +3 -3
- package/dist/src/db/queries/subgraph-operations.d.ts +10 -1
- package/dist/src/db/queries/subgraph-operations.js +9 -5
- package/dist/src/db/queries/subgraph-operations.js.map +3 -3
- package/dist/src/db/queries/subgraphs.d.ts +11 -4
- package/dist/src/db/queries/subgraphs.js +13 -6
- package/dist/src/db/queries/subgraphs.js.map +4 -4
- package/dist/src/db/queries/sync-scope.d.ts +7 -0
- package/dist/src/db/queries/webhook-replays.d.ts +7 -0
- package/dist/src/db/queries/webhook-replays.js +20 -7
- package/dist/src/db/queries/webhook-replays.js.map +3 -3
- package/dist/src/db/queries/webhooks.d.ts +7 -0
- package/dist/src/db/queries/webhooks.js +20 -7
- package/dist/src/db/queries/webhooks.js.map +3 -3
- package/dist/src/db/schema.d.ts +7 -0
- package/dist/src/db/schema.js.map +2 -2
- package/dist/src/email/index.js +16 -2
- package/dist/src/email/index.js.map +3 -3
- package/dist/src/env.d.ts +8 -1
- package/dist/src/env.js +18 -3
- package/dist/src/env.js.map +3 -3
- package/dist/src/index.d.ts +59 -1
- package/dist/src/index.js +71 -8
- package/dist/src/index.js.map +8 -8
- package/dist/src/insights/index.d.ts +7 -0
- package/dist/src/insights/index.js +16 -2
- package/dist/src/insights/index.js.map +3 -3
- package/dist/src/leader.js +915 -27
- package/dist/src/leader.js.map +13 -6
- package/dist/src/logger.js +16 -2
- package/dist/src/logger.js.map +3 -3
- package/dist/src/node/local-client.d.ts +7 -0
- package/dist/src/node/tx-summary.js +16 -2
- package/dist/src/node/tx-summary.js.map +3 -3
- package/dist/src/queue/listener.js +27 -7
- package/dist/src/queue/listener.js.map +5 -5
- package/dist/src/schemas/index.js +2 -2
- package/dist/src/schemas/index.js.map +3 -3
- package/dist/src/schemas/subgraphs.js +2 -2
- package/dist/src/schemas/subgraphs.js.map +3 -3
- package/dist/src/types.d.ts +3 -0
- package/migrations/0197_subgraph_last_block_hash.ts +67 -0
- package/migrations/0198_blocks_event_count.ts +24 -0
- package/migrations/0199_transactions_height_tx_index_uniq.ts +77 -0
- package/migrations/0200_subgraphs_schema_name_unique.ts +39 -0
- package/migrations/0201_subgraph_gaps_range_check.ts +47 -0
- package/migrations/0202_instances_secrets_key_canary.ts +36 -0
- package/package.json +2 -2
|
@@ -39,11 +39,25 @@ function getEnv() {
|
|
|
39
39
|
} else if (result.data.NETWORK) {
|
|
40
40
|
enabledNetworks = [result.data.NETWORK];
|
|
41
41
|
} else {
|
|
42
|
-
|
|
42
|
+
const named = stacksNetwork();
|
|
43
|
+
enabledNetworks = named === "testnet" ? ["testnet"] : ["mainnet"];
|
|
43
44
|
}
|
|
44
45
|
cachedEnv = { ...result.data, enabledNetworks };
|
|
45
46
|
return cachedEnv;
|
|
46
47
|
}
|
|
48
|
+
var warnedNetworkFallback = false;
|
|
49
|
+
function stacksNetwork(env = process.env) {
|
|
50
|
+
if (env.STACKS_NETWORK)
|
|
51
|
+
return env.STACKS_NETWORK;
|
|
52
|
+
if (env.NETWORK) {
|
|
53
|
+
if (!warnedNetworkFallback) {
|
|
54
|
+
warnedNetworkFallback = true;
|
|
55
|
+
console.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
|
|
56
|
+
}
|
|
57
|
+
return env.NETWORK;
|
|
58
|
+
}
|
|
59
|
+
return "mainnet";
|
|
60
|
+
}
|
|
47
61
|
function isProductionEnv() {
|
|
48
62
|
return process.env["NODE_ENV"] === "production";
|
|
49
63
|
}
|
|
@@ -131,6 +145,167 @@ class Logger {
|
|
|
131
145
|
}
|
|
132
146
|
var logger = new Logger;
|
|
133
147
|
|
|
148
|
+
// src/runtime/backup.ts
|
|
149
|
+
import {
|
|
150
|
+
createCipheriv,
|
|
151
|
+
createDecipheriv,
|
|
152
|
+
randomBytes,
|
|
153
|
+
scryptSync,
|
|
154
|
+
timingSafeEqual
|
|
155
|
+
} from "node:crypto";
|
|
156
|
+
var BACKUP_MANIFEST_VERSION = 1;
|
|
157
|
+
var BACKUP_PARTS = [
|
|
158
|
+
"db",
|
|
159
|
+
"config",
|
|
160
|
+
"keys",
|
|
161
|
+
"handlers",
|
|
162
|
+
"scope"
|
|
163
|
+
];
|
|
164
|
+
var CANARY_PLAINTEXT = "secondlayer-secrets-key-canary-v1";
|
|
165
|
+
var IV_LEN = 12;
|
|
166
|
+
var TAG_LEN = 16;
|
|
167
|
+
var SALT_LEN = 16;
|
|
168
|
+
var SCRYPT_COST = 2 ** 15;
|
|
169
|
+
var SCRYPT_MAXMEM = 64 * 1024 * 1024;
|
|
170
|
+
var SCRYPT_OPTS = { N: SCRYPT_COST, maxmem: SCRYPT_MAXMEM };
|
|
171
|
+
function planBackup(input) {
|
|
172
|
+
if (input.fromHeight < 0) {
|
|
173
|
+
return { ok: false, reason: "scope from_height must be >= 0" };
|
|
174
|
+
}
|
|
175
|
+
if (input.toHeight !== null && input.toHeight !== undefined && input.toHeight < input.fromHeight) {
|
|
176
|
+
return { ok: false, reason: "scope to_height is below from_height" };
|
|
177
|
+
}
|
|
178
|
+
if (input.includeSecrets && !input.secretsEncrypted) {
|
|
179
|
+
return {
|
|
180
|
+
ok: false,
|
|
181
|
+
reason: "refusing to write plaintext secrets; supply a passphrase or pass the explicit plaintext override"
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
if (input.includeSecrets && !input.canary) {
|
|
185
|
+
return {
|
|
186
|
+
ok: false,
|
|
187
|
+
reason: "secrets bundle requires a key canary so a restore can prove the key matches"
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
const parts = input.includeSecrets ? [...BACKUP_PARTS] : BACKUP_PARTS.filter((p) => p !== "keys");
|
|
191
|
+
return {
|
|
192
|
+
ok: true,
|
|
193
|
+
manifest: {
|
|
194
|
+
schema_version: BACKUP_MANIFEST_VERSION,
|
|
195
|
+
created_at: input.now ?? new Date().toISOString(),
|
|
196
|
+
network: input.network,
|
|
197
|
+
parts,
|
|
198
|
+
encrypted: input.secretsEncrypted,
|
|
199
|
+
scope: {
|
|
200
|
+
from_height: input.fromHeight,
|
|
201
|
+
to_height: input.toHeight ?? null
|
|
202
|
+
},
|
|
203
|
+
db: null,
|
|
204
|
+
secrets: null
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
function secretsKeyBuffer(hexKey) {
|
|
209
|
+
const key = Buffer.from(hexKey.trim(), "hex");
|
|
210
|
+
if (key.length !== 32) {
|
|
211
|
+
throw new Error("SECONDLAYER_SECRETS_KEY must be 32 bytes hex");
|
|
212
|
+
}
|
|
213
|
+
return key;
|
|
214
|
+
}
|
|
215
|
+
function sealKeyCanary(secretsKeyHex) {
|
|
216
|
+
const key = secretsKeyBuffer(secretsKeyHex);
|
|
217
|
+
const iv = randomBytes(IV_LEN);
|
|
218
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
219
|
+
const ciphertext = Buffer.concat([
|
|
220
|
+
cipher.update(CANARY_PLAINTEXT, "utf8"),
|
|
221
|
+
cipher.final()
|
|
222
|
+
]);
|
|
223
|
+
return Buffer.concat([iv, cipher.getAuthTag(), ciphertext]).toString("base64");
|
|
224
|
+
}
|
|
225
|
+
function keyMatchesCanary(canaryBase64, secretsKeyHex) {
|
|
226
|
+
try {
|
|
227
|
+
const key = secretsKeyBuffer(secretsKeyHex);
|
|
228
|
+
const envelope = Buffer.from(canaryBase64, "base64");
|
|
229
|
+
const iv = envelope.subarray(0, IV_LEN);
|
|
230
|
+
const tag = envelope.subarray(IV_LEN, IV_LEN + TAG_LEN);
|
|
231
|
+
const ciphertext = envelope.subarray(IV_LEN + TAG_LEN);
|
|
232
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
233
|
+
decipher.setAuthTag(tag);
|
|
234
|
+
const plaintext = Buffer.concat([
|
|
235
|
+
decipher.update(ciphertext),
|
|
236
|
+
decipher.final()
|
|
237
|
+
]);
|
|
238
|
+
const expected = Buffer.from(CANARY_PLAINTEXT, "utf8");
|
|
239
|
+
return plaintext.length === expected.length && timingSafeEqual(plaintext, expected);
|
|
240
|
+
} catch {
|
|
241
|
+
return false;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
function encryptBundle(plaintext, passphrase) {
|
|
245
|
+
if (!passphrase)
|
|
246
|
+
throw new Error("passphrase is required");
|
|
247
|
+
const salt = randomBytes(SALT_LEN);
|
|
248
|
+
const key = scryptSync(passphrase, salt, 32, SCRYPT_OPTS);
|
|
249
|
+
const iv = randomBytes(IV_LEN);
|
|
250
|
+
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
|
251
|
+
const ciphertext = Buffer.concat([
|
|
252
|
+
cipher.update(plaintext, "utf8"),
|
|
253
|
+
cipher.final()
|
|
254
|
+
]);
|
|
255
|
+
return Buffer.concat([salt, iv, cipher.getAuthTag(), ciphertext]);
|
|
256
|
+
}
|
|
257
|
+
function decryptBundle(envelope, passphrase) {
|
|
258
|
+
const salt = envelope.subarray(0, SALT_LEN);
|
|
259
|
+
const iv = envelope.subarray(SALT_LEN, SALT_LEN + IV_LEN);
|
|
260
|
+
const tag = envelope.subarray(SALT_LEN + IV_LEN, SALT_LEN + IV_LEN + TAG_LEN);
|
|
261
|
+
const ciphertext = envelope.subarray(SALT_LEN + IV_LEN + TAG_LEN);
|
|
262
|
+
const key = scryptSync(passphrase, salt, 32, SCRYPT_OPTS);
|
|
263
|
+
const decipher = createDecipheriv("aes-256-gcm", key, iv);
|
|
264
|
+
decipher.setAuthTag(tag);
|
|
265
|
+
return decipher.update(ciphertext).toString("utf8") + decipher.final("utf8");
|
|
266
|
+
}
|
|
267
|
+
function precheckRestore(input) {
|
|
268
|
+
if (input.manifest.schema_version !== BACKUP_MANIFEST_VERSION) {
|
|
269
|
+
return {
|
|
270
|
+
ok: false,
|
|
271
|
+
fatal: true,
|
|
272
|
+
reason: `bundle schema_version ${input.manifest.schema_version} is not supported (expected ${BACKUP_MANIFEST_VERSION})`
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
if (input.manifest.network !== input.targetNetwork) {
|
|
276
|
+
return {
|
|
277
|
+
ok: false,
|
|
278
|
+
fatal: true,
|
|
279
|
+
reason: `bundle is ${input.manifest.network}; this instance is ${input.targetNetwork}`
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
if (!input.targetIsEmpty && !input.force) {
|
|
283
|
+
return {
|
|
284
|
+
ok: false,
|
|
285
|
+
fatal: false,
|
|
286
|
+
reason: "target database already holds chain data; restoring would overwrite it"
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
const secrets = input.manifest.secrets;
|
|
290
|
+
if (secrets) {
|
|
291
|
+
if (!input.secretsKeyHex) {
|
|
292
|
+
return {
|
|
293
|
+
ok: false,
|
|
294
|
+
fatal: false,
|
|
295
|
+
reason: "bundle carries encrypted columns but no secrets key was supplied; restoring now would leave them unreadable"
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
if (!keyMatchesCanary(secrets.canary, input.secretsKeyHex)) {
|
|
299
|
+
return {
|
|
300
|
+
ok: false,
|
|
301
|
+
fatal: true,
|
|
302
|
+
reason: "the supplied SECONDLAYER_SECRETS_KEY does not match the one this backup was taken with; encrypted columns would be permanently unreadable"
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
return { ok: true };
|
|
307
|
+
}
|
|
308
|
+
|
|
134
309
|
// src/db/queries/instance.ts
|
|
135
310
|
var INSTANCE_NETWORKS = ["mainnet", "testnet", "devnet"];
|
|
136
311
|
|
|
@@ -160,21 +335,26 @@ function parseInstanceNetwork(value) {
|
|
|
160
335
|
}
|
|
161
336
|
throw new InvalidInstanceNetworkError(value);
|
|
162
337
|
}
|
|
163
|
-
var warnedNetworkFallback = false;
|
|
164
338
|
function stacksNetworkFromEnv(env = process.env) {
|
|
165
|
-
|
|
166
|
-
return env.STACKS_NETWORK;
|
|
167
|
-
if (env.NETWORK) {
|
|
168
|
-
if (!warnedNetworkFallback) {
|
|
169
|
-
warnedNetworkFallback = true;
|
|
170
|
-
logger.warn("NETWORK is deprecated: set STACKS_NETWORK instead");
|
|
171
|
-
}
|
|
172
|
-
return env.NETWORK;
|
|
173
|
-
}
|
|
174
|
-
return "mainnet";
|
|
339
|
+
return stacksNetwork(env);
|
|
175
340
|
}
|
|
176
341
|
function instanceNetworkFromEnv(env = process.env) {
|
|
177
|
-
return parseInstanceNetwork(env
|
|
342
|
+
return parseInstanceNetwork(stacksNetwork(env));
|
|
343
|
+
}
|
|
344
|
+
async function checkInstanceNetwork(db, env = process.env) {
|
|
345
|
+
const configured = stacksNetwork(env);
|
|
346
|
+
let pinned;
|
|
347
|
+
try {
|
|
348
|
+
pinned = (await db.selectFrom("instances").select("network").executeTakeFirst())?.network;
|
|
349
|
+
} catch {
|
|
350
|
+
return "unpinned";
|
|
351
|
+
}
|
|
352
|
+
if (pinned === undefined)
|
|
353
|
+
return "unpinned";
|
|
354
|
+
if (pinned === configured)
|
|
355
|
+
return "match";
|
|
356
|
+
logger.error("STACKS_NETWORK disagrees with the network this database is pinned to; this process may be pointed at the wrong database", { configured, pinned });
|
|
357
|
+
return "mismatch";
|
|
178
358
|
}
|
|
179
359
|
async function getInstance(db) {
|
|
180
360
|
const row = await db.selectFrom("instances").select(["id", "network", "created_at"]).executeTakeFirst();
|
|
@@ -201,6 +381,33 @@ async function ensureInstance(db, input) {
|
|
|
201
381
|
return raced;
|
|
202
382
|
}
|
|
203
383
|
}
|
|
384
|
+
|
|
385
|
+
class SecretsKeyMismatchError extends Error {
|
|
386
|
+
name = "SecretsKeyMismatchError";
|
|
387
|
+
constructor() {
|
|
388
|
+
super("SECONDLAYER_SECRETS_KEY is not the key this database's secrets were sealed with. Refusing to start: running on a different key leaves every webhook signing secret unreadable. Restore the original key (the DATA_DIR volume's secrets.env, or your SECONDLAYER_SECRETS_KEY), or clear instances.secrets_key_canary only if you mean to abandon those secrets.");
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
async function ensureSecretsKeyCanary(db, input) {
|
|
392
|
+
const read = () => db.selectFrom("instances").select(["id", "secrets_key_canary"]).executeTakeFirst();
|
|
393
|
+
let row = await read();
|
|
394
|
+
if (!row) {
|
|
395
|
+
await db.insertInto("instances").values({
|
|
396
|
+
network: input.network,
|
|
397
|
+
secrets_key_canary: sealKeyCanary(input.keyHex)
|
|
398
|
+
}).onConflict((oc) => oc.doNothing()).execute();
|
|
399
|
+
row = await read();
|
|
400
|
+
if (!row)
|
|
401
|
+
throw new Error("failed to create instance");
|
|
402
|
+
}
|
|
403
|
+
if (row.secrets_key_canary === null) {
|
|
404
|
+
await db.updateTable("instances").set({ secrets_key_canary: sealKeyCanary(input.keyHex) }).where("id", "=", row.id).where("secrets_key_canary", "is", null).execute();
|
|
405
|
+
row = await read();
|
|
406
|
+
}
|
|
407
|
+
if (!row?.secrets_key_canary || !keyMatchesCanary(row.secrets_key_canary, input.keyHex)) {
|
|
408
|
+
throw new SecretsKeyMismatchError;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
204
411
|
function toInstance(row) {
|
|
205
412
|
return {
|
|
206
413
|
id: row.id,
|
|
@@ -223,6 +430,96 @@ async function hasLocalProgressRow(db, network) {
|
|
|
223
430
|
return row !== undefined;
|
|
224
431
|
}
|
|
225
432
|
|
|
433
|
+
// src/db/queries/sync-scope.ts
|
|
434
|
+
var SYNC_START_HEIGHT_ENV = "SECONDLAYER_SYNC_START_HEIGHT";
|
|
435
|
+
|
|
436
|
+
class InvalidSyncStartHeightError extends Error {
|
|
437
|
+
value;
|
|
438
|
+
name = "InvalidSyncStartHeightError";
|
|
439
|
+
constructor(value) {
|
|
440
|
+
super(`${SYNC_START_HEIGHT_ENV} must be a non-negative integer (got ${value})`);
|
|
441
|
+
this.value = value;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
function syncStartHeightFromEnv(env = process.env) {
|
|
445
|
+
const raw = env[SYNC_START_HEIGHT_ENV];
|
|
446
|
+
if (raw === undefined || raw.trim() === "")
|
|
447
|
+
return null;
|
|
448
|
+
const height = Number(raw.trim());
|
|
449
|
+
if (!Number.isInteger(height) || height < 0) {
|
|
450
|
+
throw new InvalidSyncStartHeightError(raw);
|
|
451
|
+
}
|
|
452
|
+
return height;
|
|
453
|
+
}
|
|
454
|
+
function toScope(row) {
|
|
455
|
+
return {
|
|
456
|
+
network: row.network,
|
|
457
|
+
start_height: Number(row.start_height),
|
|
458
|
+
target_height: row.target_height === null ? null : Number(row.target_height),
|
|
459
|
+
bootstrap: {
|
|
460
|
+
source: row.bootstrap_source,
|
|
461
|
+
manifest_digest: row.bootstrap_manifest_digest,
|
|
462
|
+
genesis_hash: row.genesis_hash
|
|
463
|
+
}
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
async function getSyncScope(db, network) {
|
|
467
|
+
const row = await db.selectFrom("sync_scopes").select([
|
|
468
|
+
"network",
|
|
469
|
+
"start_height",
|
|
470
|
+
"target_height",
|
|
471
|
+
"bootstrap_source",
|
|
472
|
+
"bootstrap_manifest_digest",
|
|
473
|
+
"genesis_hash"
|
|
474
|
+
]).where("network", "=", network).executeTakeFirst();
|
|
475
|
+
return row ? toScope(row) : null;
|
|
476
|
+
}
|
|
477
|
+
async function upsertSyncScope(db, scope) {
|
|
478
|
+
const row = await db.insertInto("sync_scopes").values({
|
|
479
|
+
network: scope.network,
|
|
480
|
+
start_height: scope.start_height,
|
|
481
|
+
target_height: scope.target_height,
|
|
482
|
+
bootstrap_source: scope.bootstrap.source,
|
|
483
|
+
bootstrap_manifest_digest: scope.bootstrap.manifest_digest,
|
|
484
|
+
genesis_hash: scope.bootstrap.genesis_hash
|
|
485
|
+
}).onConflict((oc) => oc.column("network").doUpdateSet({
|
|
486
|
+
start_height: scope.start_height,
|
|
487
|
+
target_height: scope.target_height,
|
|
488
|
+
bootstrap_source: scope.bootstrap.source,
|
|
489
|
+
bootstrap_manifest_digest: scope.bootstrap.manifest_digest,
|
|
490
|
+
genesis_hash: scope.bootstrap.genesis_hash,
|
|
491
|
+
updated_at: new Date
|
|
492
|
+
})).returning([
|
|
493
|
+
"network",
|
|
494
|
+
"start_height",
|
|
495
|
+
"target_height",
|
|
496
|
+
"bootstrap_source",
|
|
497
|
+
"bootstrap_manifest_digest",
|
|
498
|
+
"genesis_hash"
|
|
499
|
+
]).executeTakeFirstOrThrow();
|
|
500
|
+
return toScope(row);
|
|
501
|
+
}
|
|
502
|
+
async function resolveSyncScope(db, network) {
|
|
503
|
+
const persisted = await getSyncScope(db, network);
|
|
504
|
+
if (persisted)
|
|
505
|
+
return persisted;
|
|
506
|
+
const declaredStart = syncStartHeightFromEnv();
|
|
507
|
+
const lowest = await db.selectFrom("blocks").select(({ fn }) => fn.min("height").as("min")).where("canonical", "=", true).executeTakeFirst();
|
|
508
|
+
const lowestStored = lowest?.min === null || lowest?.min === undefined ? null : Number(lowest.min);
|
|
509
|
+
const startHeight = declaredStart ?? lowestStored ?? 0;
|
|
510
|
+
const genesis = startHeight === 0 ? await db.selectFrom("blocks").select("hash").where("canonical", "=", true).where("height", "=", 0).executeTakeFirst() : undefined;
|
|
511
|
+
return {
|
|
512
|
+
network,
|
|
513
|
+
start_height: startHeight,
|
|
514
|
+
target_height: null,
|
|
515
|
+
bootstrap: {
|
|
516
|
+
source: startHeight === 0 ? "genesis" : "import",
|
|
517
|
+
manifest_digest: null,
|
|
518
|
+
genesis_hash: genesis?.hash ?? null
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
226
523
|
// src/db/queries/integrity.ts
|
|
227
524
|
async function resolveChainTip(db, kind, opts = {}) {
|
|
228
525
|
if (kind === "canonical") {
|
|
@@ -295,6 +592,38 @@ async function checkChainDataIntegrity(db, opts) {
|
|
|
295
592
|
reason: sampleBlocks > 0 ? null : `tip is ${maxHeight} but no canonical blocks near ${sampleHeight} — wrong or empty volume?`
|
|
296
593
|
};
|
|
297
594
|
}
|
|
595
|
+
async function lowestCanonicalHeight(db, above) {
|
|
596
|
+
const { rows } = await sql`
|
|
597
|
+
SELECT MIN(height) AS min FROM blocks
|
|
598
|
+
WHERE canonical = true AND height > ${above}
|
|
599
|
+
`.execute(db);
|
|
600
|
+
const min = rows[0]?.min;
|
|
601
|
+
return min === null || min === undefined ? null : Number(min);
|
|
602
|
+
}
|
|
603
|
+
async function resolveContiguousFloor(db, network = stacksNetworkFromEnv()) {
|
|
604
|
+
const lowest = await lowestCanonicalHeight(db, -1);
|
|
605
|
+
if (lowest === null)
|
|
606
|
+
return null;
|
|
607
|
+
const scope = await getSyncScope(db, network);
|
|
608
|
+
return Math.max(lowest, scope?.start_height ?? 0);
|
|
609
|
+
}
|
|
610
|
+
async function seedContiguousFloor(db, network) {
|
|
611
|
+
const lowest = await lowestCanonicalHeight(db, -1);
|
|
612
|
+
const aboveGenesis = await lowestCanonicalHeight(db, 0);
|
|
613
|
+
if (lowest === 0 && aboveGenesis !== null && aboveGenesis > 1 && await getSyncScope(db, network) === null) {
|
|
614
|
+
await upsertSyncScope(db, {
|
|
615
|
+
network,
|
|
616
|
+
start_height: aboveGenesis,
|
|
617
|
+
target_height: null,
|
|
618
|
+
bootstrap: {
|
|
619
|
+
source: "import",
|
|
620
|
+
manifest_digest: null,
|
|
621
|
+
genesis_hash: null
|
|
622
|
+
}
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
return resolveContiguousFloor(db, network);
|
|
626
|
+
}
|
|
298
627
|
async function computeContiguousTip(db, fromHeight) {
|
|
299
628
|
const { rows } = await sql`
|
|
300
629
|
SELECT COALESCE(MAX(height), ${fromHeight}) AS tip
|
|
@@ -331,6 +660,86 @@ async function findShortBlocks(db, opts = {}) {
|
|
|
331
660
|
actualTxCount: Number(r.actual_count)
|
|
332
661
|
}));
|
|
333
662
|
}
|
|
663
|
+
function recentWindow(windowSize, column) {
|
|
664
|
+
return windowSize === null ? sql`` : sql`AND ${column} > (SELECT MAX(height) - ${windowSize} FROM blocks WHERE canonical = true)`;
|
|
665
|
+
}
|
|
666
|
+
async function findDuplicateTxIndexes(db, opts = {}) {
|
|
667
|
+
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
668
|
+
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
669
|
+
const floorClause = opts.floorHeight === undefined ? sql`` : sql`AND t.block_height > ${opts.floorHeight}`;
|
|
670
|
+
const { rows } = await sql`
|
|
671
|
+
SELECT t.block_height, t.tx_index, COUNT(*) AS n
|
|
672
|
+
FROM transactions t
|
|
673
|
+
JOIN blocks b ON b.height = t.block_height AND b.canonical = true
|
|
674
|
+
WHERE true
|
|
675
|
+
${recentWindow(windowSize, sql.ref("t.block_height"))}
|
|
676
|
+
${floorClause}
|
|
677
|
+
GROUP BY t.block_height, t.tx_index
|
|
678
|
+
HAVING COUNT(*) > 1
|
|
679
|
+
ORDER BY t.block_height, t.tx_index
|
|
680
|
+
${limitClause}
|
|
681
|
+
`.execute(db);
|
|
682
|
+
return rows.map((r) => ({
|
|
683
|
+
height: Number(r.block_height),
|
|
684
|
+
txIndex: Number(r.tx_index),
|
|
685
|
+
count: Number(r.n)
|
|
686
|
+
}));
|
|
687
|
+
}
|
|
688
|
+
async function findBurnHeightRegressions(db, opts = {}) {
|
|
689
|
+
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
690
|
+
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
691
|
+
const { rows } = await sql`
|
|
692
|
+
SELECT height, burn_block_height, previous
|
|
693
|
+
FROM (
|
|
694
|
+
SELECT height, burn_block_height,
|
|
695
|
+
LAG(burn_block_height) OVER (ORDER BY height) AS previous
|
|
696
|
+
FROM blocks
|
|
697
|
+
WHERE canonical = true
|
|
698
|
+
${recentWindow(windowSize, sql.ref("height"))}
|
|
699
|
+
) s
|
|
700
|
+
WHERE burn_block_height < previous
|
|
701
|
+
ORDER BY height
|
|
702
|
+
${limitClause}
|
|
703
|
+
`.execute(db);
|
|
704
|
+
return rows.map((r) => ({
|
|
705
|
+
height: Number(r.height),
|
|
706
|
+
burnBlockHeight: Number(r.burn_block_height),
|
|
707
|
+
previousBurnBlockHeight: Number(r.previous)
|
|
708
|
+
}));
|
|
709
|
+
}
|
|
710
|
+
async function findEventCountMismatches(db, opts = {}) {
|
|
711
|
+
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
712
|
+
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
713
|
+
const { rows } = await sql`
|
|
714
|
+
SELECT b.height, b.event_count, COUNT(e.block_height) AS actual
|
|
715
|
+
FROM blocks b
|
|
716
|
+
LEFT JOIN events e ON e.block_height = b.height
|
|
717
|
+
WHERE b.canonical = true
|
|
718
|
+
AND b.event_count IS NOT NULL
|
|
719
|
+
${recentWindow(windowSize, sql.ref("b.height"))}
|
|
720
|
+
GROUP BY b.height, b.event_count
|
|
721
|
+
HAVING COUNT(e.block_height) <> b.event_count
|
|
722
|
+
ORDER BY b.height
|
|
723
|
+
${limitClause}
|
|
724
|
+
`.execute(db);
|
|
725
|
+
return rows.map((r) => ({
|
|
726
|
+
height: Number(r.height),
|
|
727
|
+
expectedEventCount: Number(r.event_count),
|
|
728
|
+
actualEventCount: Number(r.actual)
|
|
729
|
+
}));
|
|
730
|
+
}
|
|
731
|
+
async function eventsLogicalIndexState(db) {
|
|
732
|
+
const { rows } = await sql`
|
|
733
|
+
SELECT i.indisvalid
|
|
734
|
+
FROM pg_index i
|
|
735
|
+
JOIN pg_class c ON c.oid = i.indexrelid
|
|
736
|
+
WHERE c.relname = 'events_logical_id_uniq'
|
|
737
|
+
AND i.indisunique
|
|
738
|
+
`.execute(db);
|
|
739
|
+
if (rows.length === 0)
|
|
740
|
+
return "missing";
|
|
741
|
+
return rows.every((r) => r.indisvalid) ? "valid" : "invalid";
|
|
742
|
+
}
|
|
334
743
|
async function findBrokenLinks(db, opts = {}) {
|
|
335
744
|
const windowSize = opts.window === undefined ? 1e4 : opts.window;
|
|
336
745
|
const limitClause = opts.limit ? sql`LIMIT ${opts.limit}` : sql``;
|
|
@@ -360,11 +769,17 @@ export {
|
|
|
360
769
|
checkChainDataIntegrity,
|
|
361
770
|
computeContiguousTip,
|
|
362
771
|
countMissingBlocks,
|
|
772
|
+
eventsLogicalIndexState,
|
|
363
773
|
findBrokenLinks,
|
|
774
|
+
findBurnHeightRegressions,
|
|
775
|
+
findDuplicateTxIndexes,
|
|
776
|
+
findEventCountMismatches,
|
|
364
777
|
findGaps,
|
|
365
778
|
findShortBlocks,
|
|
366
|
-
resolveChainTip
|
|
779
|
+
resolveChainTip,
|
|
780
|
+
resolveContiguousFloor,
|
|
781
|
+
seedContiguousFloor
|
|
367
782
|
};
|
|
368
783
|
|
|
369
|
-
//# debugId=
|
|
784
|
+
//# debugId=86BA71AE2C63A61D64756E2164756E21
|
|
370
785
|
//# sourceMappingURL=integrity.js.map
|