Skip to content

Commit

Permalink
Merge branch 'master' into docker
Browse files Browse the repository at this point in the history
  • Loading branch information
pouya-eghbali committed Dec 20, 2023
2 parents 18c9184 + 8e66515 commit d049cb6
Show file tree
Hide file tree
Showing 11 changed files with 130 additions and 42 deletions.
45 changes: 43 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kenshi.io/unchained",
"version": "0.8.2",
"version": "0.8.3",
"description": "",
"main": "dist/index.js",
"scripts": {
Expand All @@ -17,13 +17,15 @@
"@chainsafe/bls": "^7.1.2",
"base-ex": "^0.8.1",
"commander": "^11.1.0",
"console-table-printer": "^2.11.2",
"enquirer": "^2.4.1",
"ethers": "^6.8.1",
"hyperswarm": "^4.7.9",
"iso-websocket": "^0.1.6",
"json-canon": "^1.0.1",
"latest-version": "^7.0.0",
"mongodb": "^6.3.0",
"node-cron": "^3.0.3",
"ora": "^7.0.1",
"semver": "^7.5.4",
"unws": "^0.2.4",
Expand All @@ -36,6 +38,7 @@
},
"devDependencies": {
"@types/node": "^20.10.4",
"@types/node-cron": "^3.0.11",
"@types/semver": "^7.5.6",
"@types/winston": "^2.4.4",
"@types/ws": "^8.5.10",
Expand Down
9 changes: 2 additions & 7 deletions src/lib/bls/keys.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import bls from "@chainsafe/bls";
import { Base58 } from "base-ex";

import { SecretKey, PublicKey } from "@chainsafe/bls/types";

interface KeyPair {
secretKey: SecretKey;
publicKey: PublicKey;
}
import { KeyPair } from "../types.js";
import { SecretKey } from "@chainsafe/bls/types";

interface EncodedKeyPair {
secretKey: string;
Expand Down
6 changes: 3 additions & 3 deletions src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { sha } from "./utils/hash.js";
import {
State,
Keys,
KeyPair,
Config,
StringAnyObject,
StringGossipMethodObject,
} from "./types.js";

export const version = "0.8.2";
export const version = "0.8.3";
export const protocolVersion = "0.8.0";

export const topic = sha(`Kenshi.Unchained.Testnet.Topic.V${protocolVersion}`);

export const sockets = new Map();
export const keys: Keys = {};
export const keys: KeyPair = Object({});

export const config: Config = {
name: "Change Me",
Expand Down
18 changes: 13 additions & 5 deletions src/lib/daemon/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import * as uniswap from "../plugins/uniswap/uniswap.js";
import { gossip } from "../gossip/index.js";
import { runAtNextInterval } from "../utils/time.js";
import { runWithRetries, CALLERROR, TIMEOUT } from "../utils/retry.js";
import { GossipRequest } from "../types.js";
import { runWithRetries } from "../utils/retry.js";
import { schedule } from "node-cron";
import { printScores } from "../score/print.js";

interface UniswapArgs {
blockchain: string;
Expand All @@ -18,7 +18,7 @@ const uniswapArgs: [UniswapArgs, string, [number, number], boolean] = [
];

export const runTasks = (): void => {
runAtNextInterval(async () => {
schedule("*/5 * * * * *", async () => {
try {
const result = await runWithRetries(uniswap.work, uniswapArgs);
if (result && !(result instanceof Symbol)) {
Expand All @@ -27,5 +27,13 @@ export const runTasks = (): void => {
} catch (error) {
// Handle the error or log it
}
}, 5);
}).start();

schedule("0 */5 * * * *", async () => {
try {
printScores();
} catch (error) {
// Handle the error or log it
}
}).start();
};
7 changes: 7 additions & 0 deletions src/lib/plugins/uniswap/uniswap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { encoder } from "../../bls/keys.js";
import { WebSocketLike } from "ethers";
import { WebSocket } from "unws";
import { assetPrices } from "../../db/collections/AssetPrice.js";
import { addOnePoint } from "../../score/index.js";

import assert from "assert";

Expand Down Expand Up @@ -174,6 +175,10 @@ const setAttestations = async (
({ signer }) => !currentSignatures.includes(signer)
);

for (const { signer } of newSignatureSet) {
addOnePoint(signer);
}

const newSignatures = newSignatureSet.map((item) => item.signature);
const currentAggregation = stored.aggregated || "";
const signatureList = [currentAggregation, ...newSignatures].filter(Boolean);
Expand All @@ -194,6 +199,8 @@ const setAttestations = async (
printAttestations(size, block, price, signersSet);
}

earlyAttestations.set(block, []);

for (const [key] of attestations.entries()) {
// FIXME: Security problem where a validator can reset another
// FIXME: peer's cache by sending a big block number
Expand Down
11 changes: 11 additions & 0 deletions src/lib/score/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const peerScoreMap = new Map<string, number>();

export const addOnePoint = (peer: string) => {
const current = peerScoreMap.get(peer) || 0;
peerScoreMap.set(peer, current + 1);
};

export const resetScore = (peer: string) => peerScoreMap.set(peer, 0);
export const resetAllScores = () => peerScoreMap.clear();
export const getScoreOf = (peer: string): number => peerScoreMap.get(peer) || 0;
export const getAllScores = () => peerScoreMap.entries();
42 changes: 42 additions & 0 deletions src/lib/score/print.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { getAllScores, resetAllScores } from "./index.js";
import { logger } from "../logger/index.js";
import { Table } from "console-table-printer";
import { sockets, keys } from "../constants.js";
import { encodeKeys } from "../bls/keys.js";

export const printScores = () => {
const table = new Table({
columns: [
{ name: "peer", title: "Peer", alignment: "left", color: "blue" },
{ name: "name", title: "Name", alignment: "left", color: "yellow" },
{ name: "score", title: "Score", alignment: "center", color: "green" },
],
});

const { publicKey: thisNode } = encodeKeys(keys);

const rows = [];
const publicKeyMap = new Map(
[...sockets.entries()].map(([_, { publicKey, name }]) => [publicKey, name])
);

for (const [peer, score] of getAllScores()) {
if (peer === thisNode) {
continue;
}
const name = publicKeyMap.get(peer) || "?";
rows.push({ peer, score, name });
}

if (!rows.length) {
return;
}

table.addRows(rows.sort((a, b) => b.score - a.score));

const sprint = Math.ceil(new Date().valueOf() / 300000);
logger.info(`Scores for sprint ${sprint} are:`);
table.printTable();

resetAllScores();
};
4 changes: 2 additions & 2 deletions src/lib/swarm/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ swarm.on("connection", async (socket: Duplex, info: { publicKey: Buffer }) => {
} else if (message.type === "call") {
const result = await processRpc(message);
try {
await socket.write(JSON.stringify(result));
socket.write(JSON.stringify(result));
} catch (error) {
const err = error as NodeSystemError;
const info = err.code || err.errno || err.message;
Expand Down Expand Up @@ -100,7 +100,7 @@ swarm.on("connection", async (socket: Duplex, info: { publicKey: Buffer }) => {
type: "call",
request: { method: "introduce", args: {} },
});
await socket.write(introducePayload);
socket.write(introducePayload);
} catch (error) {}
});

Expand Down
6 changes: 3 additions & 3 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ export interface State {
connected: boolean;
}

export interface Keys {
publicKey?: PublicKey;
secretKey?: SecretKey;
export interface KeyPair {
publicKey: PublicKey;
secretKey: SecretKey;
}

interface RPCList {
Expand Down
19 changes: 0 additions & 19 deletions src/lib/utils/time.ts

This file was deleted.

0 comments on commit d049cb6

Please sign in to comment.