Skip to content

Commit

Permalink
refactor: lazy load @vulpemventures/secp256k1-zkp
Browse files Browse the repository at this point in the history
  • Loading branch information
michael1011 committed Nov 2, 2024
1 parent 37f5d19 commit 43a5004
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 51 deletions.
1 change: 1 addition & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export default [
"@ledgerhq/hw-app-eth",
"@ledgerhq/hw-transport",
"@ledgerhq/hw-transport-webhid",
"@vulpemventures/secp256k1-zkp",
],
},
],
Expand Down
2 changes: 1 addition & 1 deletion src/lazy/bolt12.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import Loader from "./Loader";

export default new Loader("bolt12", async () => await import("boltz-bolt12"));
export default new Loader("BOLT12", async () => await import("boltz-bolt12"));
15 changes: 15 additions & 0 deletions src/lazy/secp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { init } from "boltz-core/dist/lib/liquid";
import { confidential } from "liquidjs-lib";

import Loader from "./Loader";

export default new Loader("Secp256k1ZKP", async () => {
const zkp = (await import("@vulpemventures/secp256k1-zkp")).default;
const secp = await zkp();

init(secp);
return {
secpZkp: secp,
confidential: new confidential.Confidential(secp),
};
});
33 changes: 16 additions & 17 deletions src/utils/claim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import {
getNetwork,
getOutputAmount,
getTransaction,
setup,
} from "./compat";
import { parseBlindingKey, parsePrivateKey } from "./helper";
import { decodeInvoice } from "./invoice";
Expand All @@ -38,7 +37,7 @@ import {
} from "./swapCreator";
import { createMusig, hashForWitnessV1, tweakMusig } from "./taproot/musig";

const createAdjustedClaim = <
const createAdjustedClaim = async <
T extends
| (ClaimDetails & { blindingPrivateKey?: Buffer })
| LiquidClaimDetails,
Expand All @@ -50,10 +49,11 @@ const createAdjustedClaim = <
blindingKey?: Buffer,
) => {
const asset = getRelevantAssetForSwap(swap);
const inputSum = claimDetails.reduce(
(total: number, input: T) => total + getOutputAmount(asset, input),
0,
);

let inputSum = 0;
for (const details of claimDetails) {
inputSum += await getOutputAmount(asset, details);
}
const feeBudget = Math.floor(inputSum - swap.receiveAmount);

const constructClaimTransaction = getConstructClaimTransaction(asset);
Expand All @@ -72,7 +72,6 @@ const claimReverseSwap = async (
lockupTx: TransactionInterface,
cooperative: boolean = true,
): Promise<TransactionInterface | undefined> => {
await setup();
log.info(`Claiming Taproot swap cooperatively: ${cooperative}`);
const asset = getRelevantAssetForSwap(swap);

Expand All @@ -84,7 +83,7 @@ const claimReverseSwap = async (

const decodedAddress = decodeAddress(asset, swap.claimAddress);
const boltzPublicKey = Buffer.from(swap.refundPublicKey, "hex");
const musig = createMusig(privateKey, boltzPublicKey);
const musig = await createMusig(privateKey, boltzPublicKey);
const tree = SwapTreeSerializer.deserializeSwapTree(swap.swapTree);
const tweakedKey = tweakMusig(asset, musig, tree.tree);
const swapOutput = detectSwap(tweakedKey, lockupTx);
Expand All @@ -101,7 +100,7 @@ const claimReverseSwap = async (
internalKey: musig.getAggregatedPublicKey(),
},
] as (ClaimDetails & { blindingPrivateKey: Buffer })[];
const claimTx = createAdjustedClaim(
const claimTx = await createAdjustedClaim(
swap,
details,
decodedAddress.script,
Expand Down Expand Up @@ -149,7 +148,10 @@ const claimChainSwap = async (
"hex",
);
const claimPrivateKey = parsePrivateKey(swap.claimPrivateKey);
const ourClaimMusig = createMusig(claimPrivateKey, boltzRefundPublicKey);
const ourClaimMusig = await createMusig(
claimPrivateKey,
boltzRefundPublicKey,
);
const claimTree = SwapTreeSerializer.deserializeSwapTree(
swap.claimDetails.swapTree,
);
Expand All @@ -175,7 +177,7 @@ const claimChainSwap = async (
},
] as (ClaimDetails & { blindingPrivateKey: Buffer })[];
const decodedAddress = decodeAddress(swap.assetReceive, swap.claimAddress);
const claimTx = createAdjustedClaim(
const claimTx = await createAdjustedClaim(
swap,
details,
decodedAddress.script,
Expand Down Expand Up @@ -205,7 +207,7 @@ const claimChainSwap = async (
serverClaimDetails.publicKey,
"hex",
);
const theirClaimMusig = createMusig(
const theirClaimMusig = await createMusig(
parsePrivateKey(swap.refundPrivateKey),
boltzClaimPublicKey,
);
Expand Down Expand Up @@ -299,8 +301,6 @@ export const claim = async <T extends ReverseSwap | ChainSwap>(
swapStatusTransaction: { hex: string },
cooperative: boolean = true,
): Promise<T | undefined> => {
await setup();

const asset = getRelevantAssetForSwap(swap);
if (asset === RBTC) {
return undefined;
Expand Down Expand Up @@ -341,8 +341,7 @@ export const createSubmarineSignature = async (swap: SubmarineSwap) => {
return;
}

await setup();
log.info(`creating cooperative claim signature for`, swap.id);
log.info("Creating cooperative claim signature for", swap.id);

const claimDetails = await getSubmarineClaimDetails(swap.id);
if (
Expand All @@ -353,7 +352,7 @@ export const createSubmarineSignature = async (swap: SubmarineSwap) => {
}

const boltzPublicKey = Buffer.from(swap.claimPublicKey, "hex");
const musig = createMusig(
const musig = await createMusig(
parsePrivateKey(swap.refundPrivateKey),
boltzPublicKey,
);
Expand Down
24 changes: 5 additions & 19 deletions src/utils/compat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import zkp, { Secp256k1ZKP } from "@vulpemventures/secp256k1-zkp";
import { Network, Transaction, address, networks } from "bitcoinjs-lib";
import {
ClaimDetails,
Expand All @@ -11,7 +10,6 @@ import {
import {
LiquidClaimDetails,
LiquidRefundDetails,
init,
constructClaimTransaction as lcCT,
constructRefundTransaction as lcRT,
} from "boltz-core/dist/lib/liquid";
Expand All @@ -27,6 +25,7 @@ import { Network as LiquidNetwork } from "liquidjs-lib/src/networks";

import { config } from "../config";
import { BTC, LBTC, LN } from "../consts/Assets";
import secp from "../lazy/secp";
import { isInvoice, isLnurl } from "./invoice";

type LiquidTransactionOutputWithKey = LiquidTransactionOutput & {
Expand All @@ -35,21 +34,8 @@ type LiquidTransactionOutputWithKey = LiquidTransactionOutput & {

type DecodedAddress = { script: Buffer; blindingKey?: Buffer };

export let secp: Secp256k1ZKP;
let confi: confidential.Confidential;

const possibleUserInputTypes = [LN, LBTC, BTC];

const setup = async () => {
if (confi !== undefined) {
return;
}

secp = await zkp();
init(secp);
confi = new confidential.Confidential(secp);
};

const getAddress = (asset: string): typeof address | typeof LiquidAddress => {
if (asset === LBTC) {
return LiquidAddress;
Expand Down Expand Up @@ -219,18 +205,19 @@ const getConstructRefundTransaction = (
);
};

const getOutputAmount = (
const getOutputAmount = async (
asset: string,
output: TransactionOutput | LiquidTransactionOutputWithKey,
): number => {
): Promise<number> => {
if (asset !== LBTC) {
return (output as TransactionOutput).value;
}

output = output as LiquidTransactionOutputWithKey;

if (output.rangeProof?.length !== 0) {
const unblinded = confi.unblindOutputWithKey(
const { confidential } = await secp.get();
const unblinded = confidential.unblindOutputWithKey(
output,
output.blindingPrivateKey,
);
Expand All @@ -241,7 +228,6 @@ const getOutputAmount = (
};

export {
setup,
getAddress,
getNetwork,
decodeAddress,
Expand Down
7 changes: 2 additions & 5 deletions src/utils/refund.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import {
getConstructRefundTransaction,
getNetwork,
getTransaction,
setup,
} from "./compat";
import { formatError } from "./errors";
import { parseBlindingKey, parsePrivateKey } from "./helper";
Expand Down Expand Up @@ -60,7 +59,7 @@ const refundTaproot = async <T extends TransactionInterface>(

const swapTree = SwapTreeSerializer.deserializeSwapTree(lockupTree);
const boltzPublicKey = Buffer.from(theirPublicKey, "hex");
const musig = createMusig(privateKey, boltzPublicKey);
const musig = await createMusig(privateKey, boltzPublicKey);
const tweakedKey = tweakMusig(swap.assetSend, musig, swapTree.tree);

const swapOutput = detectSwap(tweakedKey, lockupTx);
Expand Down Expand Up @@ -193,9 +192,7 @@ export const refund = async <T extends SubmarineSwap | ChainSwap>(
transactionToRefund: { hex: string; timeoutBlockHeight: number },
cooperative: boolean = true,
): Promise<T> => {
log.info(`refunding swap ${swap.id}: `, swap);

await setup();
log.info(`Refunding swap ${swap.id}: `, swap);

const output = decodeAddress(swap.assetSend, refundAddress);

Expand Down
11 changes: 8 additions & 3 deletions src/utils/taproot/musig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,20 @@ import { Transaction as LiquidTransaction } from "liquidjs-lib";
import { Network as LiquidNetwork } from "liquidjs-lib/src/networks";

import { LBTC } from "../../consts/Assets";
import secp from "../../lazy/secp";
import { TransactionInterface } from "../boltzClient";
import { secp } from "../compat";

export const createMusig = (ourKeys: ECPairInterface, theirPublicKey: Buffer) =>
new Musig(secp, ourKeys, randomBytes(32), [
export const createMusig = async (
ourKeys: ECPairInterface,
theirPublicKey: Buffer,
) => {
const { secpZkp } = await secp.get();
return new Musig(secpZkp, ourKeys, randomBytes(32), [
// The key of Boltz always comes first
theirPublicKey,
ourKeys.publicKey,
]);
};

export const tweakMusig = (asset: string, musig: Musig, tree: Taptree) =>
(asset === LBTC ? LiquidTaprootUtils : TaprootUtils).tweakMusig(
Expand Down
5 changes: 2 additions & 3 deletions src/utils/validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import log from "loglevel";
import { LBTC, RBTC } from "../consts/Assets";
import { Denomination, Side, SwapType } from "../consts/Enums";
import { ChainSwapDetails } from "./boltzClient";
import { decodeAddress, setup } from "./compat";
import { decodeAddress } from "./compat";
import { formatAmountDenomination } from "./denomination";
import { ECPair, ecc } from "./ecpair";
import { decodeInvoice, isInvoice, isLnurl } from "./invoice";
Expand Down Expand Up @@ -48,10 +48,9 @@ const validateAddress = async (
blindingKey: string | undefined,
buffer: BufferConstructor,
) => {
await setup();
const tweakedKey = tweakMusig(
chain,
createMusig(ourKeys, theirPublicKey),
await createMusig(ourKeys, theirPublicKey),
tree.tree,
);

Expand Down
5 changes: 2 additions & 3 deletions tests/utils/validation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import log from "loglevel";

import { BTC, LBTC, LN } from "../../src/consts/Assets";
import { SwapType } from "../../src/consts/Enums";
import { decodeAddress, setup } from "../../src/utils/compat";
import { decodeAddress } from "../../src/utils/compat";
import { validateInvoice, validateResponse } from "../../src/utils/validation";

describe("validate responses", () => {
Expand All @@ -14,9 +14,8 @@ describe("validate responses", () => {
})) as unknown as () => Contract;
};

beforeAll(async () => {
beforeAll(() => {
log.disableAll();
await setup();
});

describe("normal swap", () => {
Expand Down

0 comments on commit 43a5004

Please sign in to comment.