Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: fix root hash, add DAG testcases, DFS function #220

Merged
merged 9 commits into from
Nov 1, 2024
23 changes: 18 additions & 5 deletions packages/object/src/hashgraph/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as crypto from "node:crypto";
import type { Logger } from "@topology-foundation/logger";
import { Logger } from "@topology-foundation/logger";
import { linearizeMultiple } from "../linearize/multipleSemantics.js";
import { linearizePair } from "../linearize/pairSemantics.js";
import {
Expand All @@ -8,13 +8,19 @@ import {
} from "../proto/topology/object/object_pb.js";
import { BitSet } from "./bitset.js";

let log: Logger;
const log: Logger = new Logger("hashgraph");

// Reexporting the Vertex and Operation types from the protobuf file
export { Vertex, Operation };

export type Hash = string;

export enum DepthFirstSearchState {
Unvisited = 0,
Visiting = 1,
Visited = 2,
}

export enum OperationType {
NOP = "-1",
}
Expand Down Expand Up @@ -154,22 +160,29 @@ export class HashGraph {

DFS(visited: Map<Hash, number> = new Map()): Hash[] {
const result: Hash[] = [];
for (const vertex of this.getAllVertices()) {
visited.set(vertex.hash, DepthFirstSearchState.Unvisited);
}
const visit = (hash: Hash) => {
visited.set(hash, 1);
visited.set(hash, DepthFirstSearchState.Visiting);

const children = this.forwardEdges.get(hash) || [];
for (const child of children) {
if (visited.get(child) === 1) {
if (visited.get(child) === DepthFirstSearchState.Visiting) {
log.error("::hashgraph::DFS: Cycle detected");
return;
}
if (visited.get(child) === undefined) {
log.error("::hashgraph::DFS: Undefined child");
return;
}
if (visited.get(child) === DepthFirstSearchState.Unvisited) {
visit(child);
}
}

result.push(hash);
visited.set(hash, 2);
visited.set(hash, DepthFirstSearchState.Visited);
};

visit(HashGraph.rootHash);
Expand Down
3 changes: 2 additions & 1 deletion packages/object/tests/hashgraph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe("HashGraph construction tests", () => {

obj2.merge(obj1.hashGraph.getAllVertices());

// expect(obj2.hashGraph.selfCheckConstraints()).toBe(true);
expect(obj2.hashGraph.selfCheckConstraints()).toBe(true);

const linearOps = obj2.hashGraph.linearizeOperations();
expect(linearOps).toEqual([
Expand All @@ -41,6 +41,7 @@ describe("HashGraph construction tests", () => {
*/
const cro1 = obj1.cro as AddWinsSet<number>;
cro1.add(1);
// add fake root
const hash = obj1.hashGraph.addVertex(
{
type: "root",
Expand Down
Loading