@kadena/hardhat-chainweb
Version:
Hardhat plugin for Kadena's Chainweb network
102 lines (98 loc) • 2.14 kB
text/typescript
/* *************************************************************************** */
/* Compute Chain Distances */
// Compute shortest path via breadth first search. For small, connected,
// degree-diameter graphs this has acceptable performance. (well, it's bad, but
// not terribly bad)
//
export function distance(
srcChain: number,
trgChain: number,
graph: Record<number, number[]>,
) {
if (srcChain == trgChain) {
return 0;
}
const visited = [srcChain];
const queue = [[srcChain, 0] as [number, number]];
while (queue.length > 0) {
const [cur, d] = queue.shift()!;
for (const adj of graph[cur]) {
if (adj == trgChain) {
return d + 1;
}
if (!visited.includes(adj)) {
visited.push(adj);
queue.push([adj, d + 1]);
}
}
}
throw new Error('Chain not found in Chainweb');
}
export function createGraph(chains: number = 2): Array<number[]> {
switch (chains) {
case 2:
return [[1], [0]];
case 3:
return [
[],
[],
[],
];
case 4:
return [
[],
[],
[],
[],
];
case 5:
return [
[],
[],
[],
[],
[],
];
case 10:
return [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
];
case 20: {
return [
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
[],
];
}
default:
throw new Error(
'Valid chain counts are 2, 3, 4, 5, 10, 20; if you need a different chain count, please provide the graph explicitly',
);
}
}