Skip to content

Commit

Permalink
[Validator] Add BridgeScheduler
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelKim20 committed Mar 19, 2024
1 parent bb0f88c commit 727a7d9
Show file tree
Hide file tree
Showing 17 changed files with 809 additions and 146 deletions.
35 changes: 1 addition & 34 deletions packages/validator/hardhat.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import "@nomiclabs/hardhat-ethers";
import "@nomiclabs/hardhat-waffle";
import "@nomiclabs/hardhat-web3";
import "hardhat-change-network";
import "@openzeppelin/hardhat-upgrades";
import "@typechain/hardhat";
import "hardhat-change-network";
import "hardhat-gas-reporter";
import "solidity-coverage";
import "solidity-docgen";
Expand Down Expand Up @@ -35,39 +35,6 @@ function getAccounts() {
accounts.push(process.env.FEE);
}

if (
process.env.LINK_VALIDATOR1 !== undefined &&
process.env.LINK_VALIDATOR1.trim() !== "" &&
reg_bytes64.test(process.env.LINK_VALIDATOR1)
) {
accounts.push(process.env.LINK_VALIDATOR1);
} else {
process.env.LINK_VALIDATOR1 = Wallet.createRandom().privateKey;
accounts.push(process.env.LINK_VALIDATOR1);
}

if (
process.env.LINK_VALIDATOR2 !== undefined &&
process.env.LINK_VALIDATOR2.trim() !== "" &&
reg_bytes64.test(process.env.LINK_VALIDATOR2)
) {
accounts.push(process.env.LINK_VALIDATOR2);
} else {
process.env.LINK_VALIDATOR2 = Wallet.createRandom().privateKey;
accounts.push(process.env.LINK_VALIDATOR2);
}

if (
process.env.LINK_VALIDATOR3 !== undefined &&
process.env.LINK_VALIDATOR3.trim() !== "" &&
reg_bytes64.test(process.env.LINK_VALIDATOR3)
) {
accounts.push(process.env.LINK_VALIDATOR3);
} else {
process.env.LINK_VALIDATOR3 = Wallet.createRandom().privateKey;
accounts.push(process.env.LINK_VALIDATOR3);
}

if (
process.env.BRIDGE_VALIDATOR1 !== undefined &&
process.env.BRIDGE_VALIDATOR1.trim() !== "" &&
Expand Down
3 changes: 2 additions & 1 deletion packages/validator/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"start": "TESTING=false NODE_ENV=production hardhat run src/main.ts --network production_net",
"formatting:check": "prettier '**/*.{json,sol,ts,js,yaml}' -c",
"formatting:write": "prettier '**/*.{json,sol,ts,js,yaml}' --write",
"test:01-Collector": "TESTING=true hardhat test test/01-Collector.test.ts"
"test:01-Collector": "TESTING=true hardhat test test/01-Collector.test.ts",
"test:02-Bridge": "TESTING=true hardhat test test/02-Bridge.test.ts"
},
"repository": {
"type": "git",
Expand Down
4 changes: 4 additions & 0 deletions packages/validator/src/DefaultServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { WebService } from "./service/WebService";
import { ValidatorStorage } from "./storage/ValidatorStorage";

import { register } from "prom-client";
import { Validator } from "./scheduler/Validator";

export class DefaultServer extends WebService {
/**
Expand All @@ -20,6 +21,7 @@ export class DefaultServer extends WebService {

public readonly defaultRouter: DefaultRouter;
public readonly storage: ValidatorStorage;
public readonly validators: Validator[];

/**
* Constructor
Expand All @@ -36,13 +38,15 @@ export class DefaultServer extends WebService {
this.config = config;
this.storage = storage;
this.defaultRouter = new DefaultRouter(this, this.metrics);
this.validators = this.config.bridge.validators.map((m) => new Validator(this.config, this.storage, m));

if (!schedules) schedules = [];
schedules.forEach((m) => this.schedules.push(m));
this.schedules.forEach((m) =>
m.setOption({
config: this.config,
storage: this.storage,
validators: this.validators,
})
);
}
Expand Down
14 changes: 1 addition & 13 deletions packages/validator/src/routers/DefaultRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,9 @@ import express from "express";
import { Metrics } from "../metrics/Metrics";

export class DefaultRouter {
/**
*
* @private
*/
private _web_service: WebService;
private readonly _metrics: Metrics;

/**
*
* @param service WebService
* @param metrics Metrics
*/
constructor(service: WebService, metrics: Metrics) {
this._web_service = service;
this._metrics = metrics;
Expand All @@ -34,6 +25,7 @@ export class DefaultRouter {
private async getHealthStatus(req: express.Request, res: express.Response) {
return res.status(200).json("OK");
}

private makeResponseData(code: number, data: any, error?: any): any {
return {
code,
Expand All @@ -42,10 +34,6 @@ export class DefaultRouter {
};
}

/**
* GET /metrics
* @private
*/
private async getMetrics(req: express.Request, res: express.Response) {
res.set("Content-Type", this._metrics.contentType());
this._metrics.add("status", 1);
Expand Down
52 changes: 13 additions & 39 deletions packages/validator/src/scheduler/BridgeScheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ import { ValidatorStorage } from "../storage/ValidatorStorage";
import { Scheduler } from "./Scheduler";

// @ts-ignore
import { BlockNumber } from "web3-core";
import { EventCollector } from "./EventCollector";
import { Validator } from "./Validator";

export class BridgeScheduler extends Scheduler {
private _config: Config | undefined;
private _storage: ValidatorStorage | undefined;

private _collectorA: EventCollector | undefined;
private _collectorB: EventCollector | undefined;
private _validators: Validator[] | undefined;

constructor(expression: string) {
super(expression);
Expand All @@ -35,51 +33,27 @@ export class BridgeScheduler extends Scheduler {
}
}

public setOption(options: any) {
if (options) {
if (options.config && options.config instanceof Config) this._config = options.config;
if (options.storage && options.storage instanceof ValidatorStorage) this._storage = options.storage;
}

if (this._config !== undefined && this._storage !== undefined) {
this._collectorA = new EventCollector(
this._config,
this._storage,
this._config.bridge.networkAName,
this._config.bridge.networkAContractAddress,
1n
);

this._collectorB = new EventCollector(
this._config,
this._storage,
this._config.bridge.networkBName,
this._config.bridge.networkBContractAddress,
1n
);
}
}

public get collectorA() {
if (this._collectorA !== undefined) return this._collectorA;
private get validators(): Validator[] {
if (this._validators !== undefined) return this._validators;
else {
logger.error("collectorA is not ready yet.");
logger.error("Validators is not ready yet.");
process.exit(1);
}
}

public get collectorB() {
if (this._collectorB !== undefined) return this._collectorB;
else {
logger.error("_collectorB is not ready yet.");
process.exit(1);
public setOption(options: any) {
if (options) {
if (options.config && options.config instanceof Config) this._config = options.config;
if (options.storage && options.storage instanceof ValidatorStorage) this._storage = options.storage;
if (options.validators) this._validators = options.validators;
}
}

protected async work() {
try {
await this.collectorA.work();
await this.collectorB.work();
for (const validator of this.validators) {
await validator.work();
}
} catch (error) {
logger.error(`Failed to execute the BridgeScheduler: ${error}`);
}
Expand Down
43 changes: 23 additions & 20 deletions packages/validator/src/scheduler/EventCollector.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,59 @@
import { IBridge__factory } from "../../typechain-types";
import { Config } from "../common/Config";
import { logger } from "../common/Logger";
import { ValidatorStorage } from "../storage/ValidatorStorage";

import { BigNumber } from "ethers";
import { BigNumber, Wallet } from "ethers";
import * as hre from "hardhat";
import { logger } from "../common/Logger";
import { ValidatorType } from "../types";

export class EventCollector {
private wallet: Wallet;
private readonly type: ValidatorType;
private readonly network: string;
private readonly contractAddress: string;
private readonly startNumber: bigint;
private contract: any;
private config: Config | undefined;
private storage: ValidatorStorage;

constructor(
config: Config,
storage: ValidatorStorage,
type: ValidatorType,
network: string,
contractAddress: string,
startBlockNumber: bigint
startBlockNumber: bigint,
wallet: Wallet
) {
this.config = config;
this.storage = storage;
this.type = type;
this.network = network;
this.contractAddress = contractAddress;
this.startNumber = startBlockNumber;
this.wallet = wallet;
}

private async getLastBlockNumber(): Promise<BigNumber> {
private async getLatestBlockNumber(): Promise<bigint> {
const block = await hre.ethers.provider.getBlock("latest");
return BigNumber.from(block.number);
return BigInt(block.number);
}

public async work() {
hre.changeNetwork(this.network);

let latestCollectedNumber = await this.storage.getLatestNumber(this.network);
const latestBlockNumber = await this.getLatestBlockNumber();

let from: BigInt;
const latestCollectedNumber = await this.storage.getLatestNumber(this.wallet.address, this.type, this.network);
if (latestCollectedNumber === undefined) {
latestCollectedNumber = this.startNumber - 1n;
from = this.startNumber;
} else {
from = latestCollectedNumber + 1n;
if (from > latestBlockNumber) from = this.startNumber;
}

const block = await hre.ethers.provider.getBlock("latest");
const lastBlockNumber = BigInt(block.number);

let from = latestCollectedNumber + 1n;
if (from > lastBlockNumber) from = this.startNumber;

this.contract = new hre.web3.eth.Contract(IBridge__factory.abi as any, this.contractAddress);
const events = await this.contract.getPastEvents("BridgeDeposited", {
fromBlock: Number(from),
toBlock: Number(lastBlockNumber),
toBlock: Number(latestBlockNumber),
});

const depositEvents = events.map((m: any) => {
Expand All @@ -65,8 +68,8 @@ export class EventCollector {
};
});

if (depositEvents.length > 0) await this.storage.postEvents(depositEvents);
if (depositEvents.length > 0) await this.storage.postEvents(depositEvents, this.wallet.address, this.type);

await this.storage.setLatestNumber(this.network, lastBlockNumber);
await this.storage.setLatestNumber(this.wallet.address, this.type, this.network, latestBlockNumber);
}
}
Loading

0 comments on commit 727a7d9

Please sign in to comment.