Skip to content

Commit

Permalink
feat: finish full flow of relayer server
Browse files Browse the repository at this point in the history
  • Loading branch information
perfogic committed Aug 14, 2024
1 parent 93e6e60 commit 84bf440
Show file tree
Hide file tree
Showing 12 changed files with 321 additions and 53 deletions.
5 changes: 5 additions & 0 deletions packages/bitcoin-bridge-wasm-sdk/wasm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,11 @@ export function toSourceAddr(dest: Dest): string;
*/
export function decodeRawTx(raw_tx: string): Transaction;
/**
* @param {Transaction} tx
* @returns {string}
*/
export function getBitcoinTransactionTxid(tx: Transaction): string;
/**
* @param {Xpub} xpub
* @returns {string}
*/
Expand Down
21 changes: 21 additions & 0 deletions packages/bitcoin-bridge-wasm-sdk/wasm.js
Original file line number Diff line number Diff line change
Expand Up @@ -775,6 +775,27 @@ module.exports.decodeRawTx = function(raw_tx) {
return takeObject(ret);
};

/**
* @param {Transaction} tx
* @returns {string}
*/
module.exports.getBitcoinTransactionTxid = function(tx) {
let deferred1_0;
let deferred1_1;
try {
const retptr = wasm.__wbindgen_add_to_stack_pointer(-16);
wasm.getBitcoinTransactionTxid(retptr, addHeapObject(tx));
var r0 = getInt32Memory0()[retptr / 4 + 0];
var r1 = getInt32Memory0()[retptr / 4 + 1];
deferred1_0 = r0;
deferred1_1 = r1;
return getStringFromWasm0(r0, r1);
} finally {
wasm.__wbindgen_add_to_stack_pointer(16);
wasm.__wbindgen_free(deferred1_0, deferred1_1, 1);
}
};

/**
* @param {Xpub} xpub
* @returns {string}
Expand Down
Binary file modified packages/bitcoin-bridge-wasm-sdk/wasm_bg.wasm
Binary file not shown.
1 change: 1 addition & 0 deletions packages/bitcoin-bridge-wasm-sdk/wasm_bg.wasm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export function commitmentBytes(a: number, b: number): void;
export function toReceiverAddr(a: number, b: number): void;
export function toSourceAddr(a: number, b: number): void;
export function decodeRawTx(a: number, b: number): number;
export function getBitcoinTransactionTxid(a: number, b: number): void;
export function encodeXpub(a: number, b: number): void;
export function newRawSignatorySet(a: number, b: number, c: number, d: number): number;
export function newSignatorySet(a: number, b: number, c: number, d: number, e: number): void;
Expand Down
63 changes: 59 additions & 4 deletions packages/contracts-sdk/src/CwBitcoin.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
SigningCosmWasmClient,
} from "@cosmjs/cosmwasm-stargate";
import {
Addr,
ArrayOfBinary,
ArrayOfTupleOfArraySize32OfUint8AndUint32,
Binary,
Expand All @@ -22,6 +23,8 @@ import {
Dest,
HeaderConfig,
Metadata,
NullableString,
NullableUint32,
Signature,
String,
Uint32,
Expand All @@ -33,6 +36,7 @@ export interface CwBitcoinReadOnlyInterface {
bitcoinConfig: () => Promise<BitcoinConfig>;
checkpointConfig: () => Promise<CheckpointConfig>;
headerConfig: () => Promise<HeaderConfig>;
signatoryKey: ({ addr }: { addr: Addr }) => Promise<NullableString>;
headerHeight: () => Promise<Uint32>;
depositFees: ({ index }: { index?: number }) => Promise<Uint64>;
checkpointFees: ({ index }: { index?: number }) => Promise<Uint64>;
Expand All @@ -49,6 +53,7 @@ export interface CwBitcoinReadOnlyInterface {
limit: number;
}) => Promise<ArrayOfBinary>;
signedRecoveryTxs: () => Promise<ArrayOfBinary>;
checkpointTx: ({ index }: { index?: number }) => Promise<Binary>;
sidechainBlockHash: () => Promise<String>;
checkpointByIndex: ({ index }: { index: number }) => Promise<Checkpoint>;
buildingCheckpoint: () => Promise<Checkpoint>;
Expand All @@ -65,10 +70,10 @@ export interface CwBitcoinReadOnlyInterface {
xpub: String;
}) => Promise<ArrayOfTupleOfArraySize32OfUint8AndUint32>;
processedOutpoint: ({ key }: { key: string }) => Promise<Boolean>;
confirmedIndex: () => Promise<Uint32>;
confirmedIndex: () => Promise<NullableUint32>;
buildingIndex: () => Promise<Uint32>;
completedIndex: () => Promise<Uint32>;
unhandledConfirmedIndex: () => Promise<Uint32>;
unhandledConfirmedIndex: () => Promise<NullableUint32>;
}
export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
client: CosmWasmClient;
Expand All @@ -80,12 +85,14 @@ export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
this.bitcoinConfig = this.bitcoinConfig.bind(this);
this.checkpointConfig = this.checkpointConfig.bind(this);
this.headerConfig = this.headerConfig.bind(this);
this.signatoryKey = this.signatoryKey.bind(this);
this.headerHeight = this.headerHeight.bind(this);
this.depositFees = this.depositFees.bind(this);
this.checkpointFees = this.checkpointFees.bind(this);
this.withdrawalFees = this.withdrawalFees.bind(this);
this.completedCheckpointTxs = this.completedCheckpointTxs.bind(this);
this.signedRecoveryTxs = this.signedRecoveryTxs.bind(this);
this.checkpointTx = this.checkpointTx.bind(this);
this.sidechainBlockHash = this.sidechainBlockHash.bind(this);
this.checkpointByIndex = this.checkpointByIndex.bind(this);
this.buildingCheckpoint = this.buildingCheckpoint.bind(this);
Expand Down Expand Up @@ -114,6 +121,13 @@ export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
header_config: {},
});
};
signatoryKey = async ({ addr }: { addr: Addr }): Promise<NullableString> => {
return this.client.queryContractSmart(this.contractAddress, {
signatory_key: {
addr,
},
});
};
headerHeight = async (): Promise<Uint32> => {
return this.client.queryContractSmart(this.contractAddress, {
header_height: {},
Expand Down Expand Up @@ -163,6 +177,13 @@ export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
signed_recovery_txs: {},
});
};
checkpointTx = async ({ index }: { index?: number }): Promise<Binary> => {
return this.client.queryContractSmart(this.contractAddress, {
checkpoint_tx: {
index,
},
});
};
sidechainBlockHash = async (): Promise<String> => {
return this.client.queryContractSmart(this.contractAddress, {
sidechain_block_hash: {},
Expand Down Expand Up @@ -216,7 +237,7 @@ export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
},
});
};
confirmedIndex = async (): Promise<Uint32> => {
confirmedIndex = async (): Promise<NullableUint32> => {
return this.client.queryContractSmart(this.contractAddress, {
confirmed_index: {},
});
Expand All @@ -231,7 +252,7 @@ export class CwBitcoinQueryClient implements CwBitcoinReadOnlyInterface {
completed_index: {},
});
};
unhandledConfirmedIndex = async (): Promise<Uint32> => {
unhandledConfirmedIndex = async (): Promise<NullableUint32> => {
return this.client.queryContractSmart(this.contractAddress, {
unhandled_confirmed_index: {},
});
Expand Down Expand Up @@ -388,6 +409,16 @@ export interface CwBitcoinInterface extends CwBitcoinReadOnlyInterface {
_memo?: string,
_funds?: Coin[]
) => Promise<ExecuteResult>;
changeBtcAdmin: (
{
newAdmin,
}: {
newAdmin: string;
},
_fee?: number | StdFee | "auto",
_memo?: string,
_funds?: Coin[]
) => Promise<ExecuteResult>;
triggerBeginBlock: (
{
hash,
Expand Down Expand Up @@ -428,6 +459,7 @@ export class CwBitcoinClient
this.setSignatoryKey = this.setSignatoryKey.bind(this);
this.addValidators = this.addValidators.bind(this);
this.registerDenom = this.registerDenom.bind(this);
this.changeBtcAdmin = this.changeBtcAdmin.bind(this);
this.triggerBeginBlock = this.triggerBeginBlock.bind(this);
}

Expand Down Expand Up @@ -749,6 +781,29 @@ export class CwBitcoinClient
_funds
);
};
changeBtcAdmin = async (
{
newAdmin,
}: {
newAdmin: string;
},
_fee: number | StdFee | "auto" = "auto",
_memo?: string,
_funds?: Coin[]
): Promise<ExecuteResult> => {
return await this.client.execute(
this.sender,
this.contractAddress,
{
change_btc_admin: {
new_admin: newAdmin,
},
},
_fee,
_memo,
_funds
);
};
triggerBeginBlock = async (
{
hash,
Expand Down
17 changes: 17 additions & 0 deletions packages/contracts-sdk/src/CwBitcoin.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ export type ExecuteMsg =
subdenom: string;
};
}
| {
change_btc_admin: {
new_admin: string;
};
}
| {
trigger_begin_block: {
hash: Binary;
Expand Down Expand Up @@ -203,6 +208,11 @@ export type QueryMsg =
| {
header_config: {};
}
| {
signatory_key: {
addr: Addr;
};
}
| {
header_height: {};
}
Expand Down Expand Up @@ -230,6 +240,11 @@ export type QueryMsg =
| {
signed_recovery_txs: {};
}
| {
checkpoint_tx: {
index?: number | null;
};
}
| {
sidechain_block_hash: {};
}
Expand Down Expand Up @@ -367,7 +382,9 @@ export interface Signatory {
export type Uint32 = number;
export type Uint64 = number;
export type ArrayOfBinary = Binary[];
export type NullableUint32 = number | null;
export type Boolean = boolean;
export type NullableString = String | null;
export type ArrayOfTupleOfArraySize32OfUint8AndUint32 = [
[
number,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,20 @@ const getCheckpointFee = catchAsync(async (req: Request, res: Response) => {
});
});

const getStoreCheckpointIndexes = catchAsync(
async (req: Request, res: Response) => {
const data = await checkpointService.getStoreCheckpointIndexes();
res.status(httpStatus.OK).json({
message: "Get completed index successfully",
data,
});
}
);

export default {
getCheckpoint,
getDepositFee,
getWithdrawFee,
getCheckpointFee,
getStoreCheckpointIndexes,
};
4 changes: 4 additions & 0 deletions packages/orchestrator/src/apis/routes/checkpoint.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,9 @@ router.get("/", checkpointController.getCheckpoint);
router.get("/deposit_fee", checkpointController.getDepositFee);
router.get("/withdraw_fee", checkpointController.getWithdrawFee);
router.get("/checkpoint_fee", checkpointController.getCheckpointFee);
router.get(
"/store_checkpoint_indexes",
checkpointController.getStoreCheckpointIndexes
);

export default router;
19 changes: 19 additions & 0 deletions packages/orchestrator/src/apis/services/checkpoint.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,28 @@ const getCheckpointFee = async (index: number | undefined) => {
return queryClient.checkpointFees({ index });
};

const getStoreCheckpointIndexes = async () => {
const client = await initQueryClient(
env.cosmos.rpcUrl || WasmLocalConfig.rpcEndpoint
);
const queryClient = new CwBitcoinQueryClient(client, env.cosmos.cwBitcoin);
const [completedIndex, confirmedIndex, firstUnconfirmedIndex] =
await Promise.all([
queryClient.completedIndex(),
queryClient.confirmedIndex(),
queryClient.unhandledConfirmedIndex(),
]);
return {
completedIndex,
confirmedIndex,
firstUnconfirmedIndex,
};
};

export default {
getCheckpoint,
getDepositFee,
getWithdrawFee,
getCheckpointFee,
getStoreCheckpointIndexes,
};
52 changes: 29 additions & 23 deletions packages/orchestrator/src/script.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { CwBitcoinClient } from "@oraichain/bitcoin-bridge-contracts-sdk";
import { encodeXpub } from "@oraichain/bitcoin-bridge-wasm-sdk";
import BIP32Factory from "bip32";
import * as btc from "bitcoinjs-lib";
import * as crypto from "crypto";
import { RPCClient } from "rpc-bitcoin";
import * as ecc from "tiny-secp256k1";
import env from "./configs/env";
import { WasmLocalConfig } from "./configs/networks";
import { initSignerClient } from "./utils/cosmos";
import { initSignerClient, wrappedExecuteTransaction } from "./utils/cosmos";

// Function to create a buffer from a single byte
function createSeed(num: number): Buffer {
Expand Down Expand Up @@ -39,6 +40,12 @@ const main = async () => {
const blockchainInfo = await btcClient.getblockchaininfo();
const btcHeight = blockchainInfo.blocks;

// console.log(
// await cwBitcoinClient.signatoryKey({
// addr: "orai1tuf6xqfffyxtye68wasrh9vdrad3nzh6exum6g",
// })
// );

// console.log(sender);

// register denom
Expand Down Expand Up @@ -80,28 +87,27 @@ const main = async () => {
const xpriv = node.toBase58();
const xpub = node.neutered().toBase58();

// let signTxs = await cwBitcoinClient.signingTxsAtCheckpointIndex({
// xpub: encodeXpub({ key: xpub }),
// checkpointIndex: 2,
// });
// let sigs = [];
// for (const signTx of signTxs) {
// const [msg, sigsetIndex] = signTx;
// const node = bip32.fromBase58(xpriv, btc.networks.testnet);
// const key = node.derive(sigsetIndex);
// const sig = key.sign(Buffer.from(msg));
// sigs = [...sigs, Array.from(sig)];
// }

// await wrappedExecuteTransaction(async () => {
// const tx = await cwBitcoinClient.submitCheckpointSignature({
// btcHeight,
// checkpointIndex: 2,
// sigs,
// xpub: encodeXpub({ key: xpub }),
// });
// console.log(tx.transactionHash);
// });
let signTxs = await cwBitcoinClient.signingTxsAtCheckpointIndex({
xpub: encodeXpub({ key: xpub }),
checkpointIndex: 6,
});
let sigs = [];
for (const signTx of signTxs) {
const [msg, sigsetIndex] = signTx;
const node = bip32.fromBase58(xpriv, btc.networks.testnet);
const key = node.derive(sigsetIndex);
const sig = key.sign(Buffer.from(msg));
sigs = [...sigs, Array.from(sig)];
}
await wrappedExecuteTransaction(async () => {
const tx = await cwBitcoinClient.submitCheckpointSignature({
btcHeight,
checkpointIndex: 6,
sigs,
xpub: encodeXpub({ key: xpub }),
});
console.log(tx.transactionHash);
});

// const array = new Uint8Array(32);
// let tx = await cwBitcoinClient.addValidators({
Expand Down
Loading

0 comments on commit 84bf440

Please sign in to comment.