Skip to content
This repository has been archived by the owner on Jul 8, 2021. It is now read-only.

Commit

Permalink
Update the receipt API (#81)
Browse files Browse the repository at this point in the history
* chore(api): update the types of receipt api

* refactor(listener): separated relay listener into files

* feat(proxy): supports proxy in the relay process

* feat(bin): add binary dj-proposal for testing proposal directly

* chore(api): update the confirmed block api

* feat(cmd): add command `confirm`

* fix(redeem): correct the redeem loop

* chore(bin): add binary tag to new bins
  • Loading branch information
clearloop authored Sep 15, 2020
1 parent 679f5f2 commit 17946fb
Show file tree
Hide file tree
Showing 15 changed files with 299 additions and 195 deletions.
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"private": false,
"name": "@darwinia/dj",
"version": "",
"version": "0.2.3-beta.2",
"description": "Darwinia bridge relayer tool",
"homepage": "https://github.com/darwinia-network/dj",
"repository": {
Expand All @@ -12,12 +12,14 @@
"license": "GPL-3.0",
"main": "lib/index.js",
"bin": {
"dj": "lib/index.js"
"dj": "lib/index.js",
"dj-proposal": "lib/src/bin/proposal.js",
"dj-confirm": "lib/src/bin/confirm.js"
},
"files": ["lib/**/*"],
"dependencies": {
"@polkadot/api": "1.30.0-beta.0",
"@polkadot/keyring": "3.3.1",
"@polkadot/api": "1.32.1",
"@polkadot/keyring": "3.4.1",
"@polkadot/util-crypto": "3.3.1",
"axios": "^0.19.2",
"prompts": "^2.3.2",
Expand All @@ -27,7 +29,7 @@
"devDependencies": {
"@commitlint/cli": "^8.3.5",
"@commitlint/config-conventional": "^8.3.4",
"@polkadot/types": "1.30.0-beta.0",
"@polkadot/types": "1.32.1",
"@types/node": "^13.11.1",
"@types/prompts": "^2.0.8",
"husky": "^4.2.5",
Expand Down
47 changes: 34 additions & 13 deletions src/api/darwinia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
import { log, Config } from "../util";
import { ApiPromise, SubmittableResult, WsProvider } from "@polkadot/api";
import { SubmittableExtrinsic } from "@polkadot/api/types";
import Keyring from "@polkadot/keyring";
import { Keyring, decodeAddress } from "@polkadot/keyring";
import { KeyringPair } from "@polkadot/keyring/types";
import { DispatchError, EventRecord } from "@polkadot/types/interfaces/types";
import { cryptoWaitReady } from "@polkadot/util-crypto";
import { SignedBlock } from "@polkadot/types/interfaces";
import {
IEthereumHeaderThingWithProof,
IReceiptWithProof,
Expand Down Expand Up @@ -83,7 +82,7 @@ export class API {
public static async auto(): Promise<API> {
const cfg = new Config();
const seed = await cfg.checkSeed();
return await API.new(seed, cfg.node, cfg.types);
return await API.new(seed, cfg.node, cfg.relayer, cfg.types);
}

/**
Expand Down Expand Up @@ -123,6 +122,7 @@ export class API {
public static async new(
seed: string,
node: string,
relayer: string,
types: Record<string, any>,
): Promise<API> {
const api = await ApiPromise.create({
Expand All @@ -132,10 +132,12 @@ export class API {

const account = await API.seed(seed);
log.trace("init darwinia api succeed");
return new API(account, (api as ApiPromise), types);
const relayerAddr = relayer.length > 0 ? decodeAddress(relayer) : new Uint8Array();
return new API(account, (api as ApiPromise), relayerAddr, types);
}

public account: KeyringPair;
public relayer: Uint8Array;
public types: Record<string, any>;
public _: ApiPromise;

Expand All @@ -147,8 +149,14 @@ export class API {
* @param {KeyringPair} account - darwinia account
* @param {ApiPromise} ap - raw polkadot api
*/
constructor(account: KeyringPair, ap: ApiPromise, types: Record<string, any>) {
constructor(
account: KeyringPair,
ap: ApiPromise,
relayer: Uint8Array,
types: Record<string, any>,
) {
this.account = account;
this.relayer = relayer;
this.types = types;
this._ = ap;
}
Expand All @@ -157,12 +165,13 @@ export class API {
* Get last confirm block
*/
public async lastConfirm(): Promise<number> {
const res = await this._.query.ethereumRelay.lastConfirmedHeaderInfo();
const res = await this._.query.ethereumRelay.confirmedBlockNumbers();
if (res.toJSON() === null) {
return 0;
}

return (res.toJSON() as any)[0] as number;
const blocks = res.toJSON() as number[];
return blocks[blocks.length - 1];
}

/**
Expand Down Expand Up @@ -207,23 +216,35 @@ export class API {
return await this.blockFinalized(ex);
}

/**
* Set confirmed block with sudo privilege
*/
public async setConfirmed(headerThing: IEthereumHeaderThingWithProof): Promise<ExResult> {
log.event(`Set confirmed block ${headerThing.header.number}`);
const ex = this._.tx.ethereumRelay.setConfirmed(headerThing);
return await this.blockFinalized(this._.tx.sudo.sudo(ex));
}

/**
* get the specify block
*
* @param {IEthHeaderThing} headerThings - Eth Header Things
*/
public async submitProposal(headerThings: IEthereumHeaderThingWithProof[]): Promise<ExResult> {
const latest = headerThings[headerThings.length - 1].header.number;
const cts = ((await this._.query.ethereumRelay.confirmedHeadersDoubleMap(
Math.floor(latest / 185142), latest,
)).toJSON() as any).timestamp;
if (cts !== 0) {
const confirmed = await this._.query.ethereumRelay.confirmedHeaders(latest);
if (confirmed.toJSON()) {
log.event(`Proposal ${latest} has been submitted yet`);
return new ExResult(true, "", "");
}

// Submit new proposal
log.event(`Submit proposal contains block ${headerThings[headerThings.length - 1].header.number}`);
const ex = this._.tx.ethereumRelay.submitProposal(headerThings);
log.event(`Submit proposal contains block ${latest}`);
let ex = this._.tx.ethereumRelay.submitProposal(headerThings);
if (this.relayer.length > 0) {
ex = this._.tx.proxy.proxy(this.relayer, "EthereumBridge", ex);
}

return await this.blockFinalized(ex);
}

Expand Down
6 changes: 2 additions & 4 deletions src/api/shadow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import {
IEthereumHeaderThingWithProof,
} from "../types";


/**
* Shadow APIs
*
Expand All @@ -20,7 +19,6 @@ export class ShadowAPI {
axios.defaults.proxy = false;
}


/**
* Get darwinia block with eth proof
*
Expand Down Expand Up @@ -59,13 +57,13 @@ export class ShadowAPI {
* @param {number} block - block number
*/
async getProposal(
leaves: number[],
member: number,
target: number,
last_leaf: number,
): Promise<IEthereumHeaderThingWithProof> {
log.event(`Fetching proposal of ${target}`);
const r: any = await axios.post("/eth/proposal", {
leaves,
member,
target,
last_leaf,
}).catch(log.err);
Expand Down
34 changes: 34 additions & 0 deletions src/bin/confirm.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env node
import { Config, log } from "../util";
import { API, ShadowAPI } from "../api";

(async () => {
const args = process.argv.slice(2);
if (args.length !== 1) {
log.warn("Usage: dj-confirm <number>");
return;
}

/// Init logs
process.env.LOGGER = "ALL";

/// Init API
const conf = new Config();
const api = await API.auto();
const shadow = new ShadowAPI(conf.shadow);
const target = Number.parseInt(args[0], 10);

// Trigger relay
const lastConfirmed = await api.lastConfirm();
try {
await api.setConfirmed(await shadow.getProposal(
lastConfirmed,
target,
target - 1,
));

log.ox(`Set confirmed block ${target} succeed!`);
} catch (e) {
log.ex(e);
}
})();
34 changes: 34 additions & 0 deletions src/bin/proposal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env node
import { Config, log } from "../util";
import { API, ShadowAPI } from "../api";

(async () => {
const args = process.argv.slice(2);
if (args.length !== 1) {
log.warn("Usage: dj-proposal <number>");
return;
}

/// Init logs
process.env.LOGGER = "ALL";

/// Init API
const conf = new Config();
const api = await API.auto();
const shadow = new ShadowAPI(conf.shadow);
const target = Number.parseInt(args[0], 10);

// Trigger relay
const lastConfirmed = await api.lastConfirm();
try {
await api.submitProposal([await shadow.getProposal(
lastConfirmed,
target,
target - 1,
)]);

log.ox(`Submitted proposal ${target}`);
} catch (e) {
log.ex(e);
}
})();
9 changes: 2 additions & 7 deletions src/listener/guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ShadowAPI, API, ExResult } from "../api";
import { log } from "../util";

// Proposal guard
export async function guard(api: API, shadow: ShadowAPI) {
export async function listen(api: API, shadow: ShadowAPI) {
let perms = 4;
if ((await api._.query.sudo.key()).toJSON().indexOf(api.account.address) > -1) {
perms = 7;
Expand All @@ -13,20 +13,17 @@ export async function guard(api: API, shadow: ShadowAPI) {
}

// start listening
let lock = false;
const handled: number[] = [];
setInterval(async () => {
if (lock) { return; }
const headers = (await api._.query.ethereumRelayerGame.pendingHeaders()).toJSON() as string[][];
if (headers.length === 0) {
return;
}

lock = true;
for (const h of headers) {
const blockNumber = Number.parseInt(h[1], 10);
if (handled.indexOf(blockNumber) > -1) {
break;
continue;
}

const block = (await shadow.getHeaderThing(blockNumber)) as any;
Expand All @@ -47,7 +44,5 @@ export async function guard(api: API, shadow: ShadowAPI) {
}
handled.push(blockNumber);
}

lock = false;
}, 10000);
}
4 changes: 2 additions & 2 deletions src/listener/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { guard } from "./guard";
export * as Cache from "./cache";
export { relay } from "./relay";
export { listen as guard } from "./guard";
export { listen as relay } from "./relay";
export { listen as ethereum } from "./eth";
Loading

0 comments on commit 17946fb

Please sign in to comment.