@lodestar/beacon-node
Version:
A Typescript implementation of the beacon chain
58 lines • 2.4 kB
JavaScript
import { MapDef } from "@lodestar/utils";
import { BlockInputType } from "../../chain/blocks/types.js";
import { PendingBlockStatus, } from "../interface.js";
export function getAllDescendantBlocks(blockRootHex, blocks) {
// Do one pass over all blocks to index by parent
const byParent = new MapDef(() => []);
for (const block of blocks.values()) {
if (block.parentBlockRootHex != null) {
byParent.getOrDefault(block.parentBlockRootHex).push(block);
}
}
// Then, do a second pass recursively to get `blockRootHex` child blocks
return addToDescendantBlocks(blockRootHex, byParent);
}
/** Recursive function for `getAllDescendantBlocks()` */
function addToDescendantBlocks(childBlockRootHex, byParent, descendantBlocks = []) {
const firstDescendantBlocks = byParent.get(childBlockRootHex);
if (firstDescendantBlocks) {
for (const firstDescendantBlock of firstDescendantBlocks) {
descendantBlocks.push(firstDescendantBlock);
addToDescendantBlocks(firstDescendantBlock.blockRootHex, byParent, descendantBlocks);
}
}
return descendantBlocks;
}
export function getDescendantBlocks(blockRootHex, blocks) {
const descendantBlocks = [];
for (const block of blocks.values()) {
if (block.parentBlockRootHex === blockRootHex) {
descendantBlocks.push(block);
}
}
return descendantBlocks;
}
/**
* Given this chain segment unknown block n => downloaded block n + 1 => downloaded block n + 2
* return `{unknowns: [n], ancestors: []}`
*
* Given this chain segment: downloaded block n => downloaded block n + 1 => downloaded block n + 2
* return {unknowns: [], ancestors: [n]}
*/
export function getUnknownAndAncestorBlocks(blocks) {
const unknowns = [];
const ancestors = [];
for (const block of blocks.values()) {
const parentHex = block.parentBlockRootHex;
if (block.status === PendingBlockStatus.pending &&
(block.blockInput?.block == null || block.blockInput?.type === BlockInputType.dataPromise) &&
parentHex == null) {
unknowns.push(block);
}
if (block.status === PendingBlockStatus.downloaded && parentHex && !blocks.has(parentHex)) {
ancestors.push(block);
}
}
return { unknowns, ancestors };
}
//# sourceMappingURL=pendingBlocksTree.js.map