Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions packages/core/__tests__/dlc/CoinSelect.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,36 @@ describe('CoinSelect', () => {
expect(fee).to.equal(BigInt(687));
});

it('reserves fees for the extra override bytes', () => {
const feeRate = BigInt(10);
expect(dualFees(feeRate, 1, 1, 78)).to.equal(
dualFees(feeRate, 1, 1) + BigInt(78) * feeRate,
);

// A UTXO that covers the collateral at the plain fee but not with a
// 100-byte override in place of a 22-byte accept script.
const collateral = BigInt(100000);
const utxo: UTXO = {
address: 'bcrt1qjzut0906d9sk4hml4k6sz6cssljktf4c7yl80f',
txid: 'c7bf12ac16aba1cf6c7769117294853453f7da3006363dfe4e8979847e32f7e1',
value: Number(
collateral + dualFees(feeRate, 1, 1) + dustThreshold(feeRate),
),
vout: 0,
};
expect(
dualFundingCoinSelect([utxo], [collateral], feeRate).inputs,
).to.have.length(1);
const withOverride = dualFundingCoinSelect(
[utxo],
[collateral],
feeRate,
78,
);
expect(withOverride.inputs).to.have.length(0);
expect(withOverride.fee).to.equal(dualFees(feeRate, 1, 1, 78));
});

it('should calculate lower fees for taproot inputs', () => {
const feeRate = BigInt(450);
const p2wpkhFee = dualFees(feeRate, 1, 1);
Expand Down
119 changes: 119 additions & 0 deletions packages/core/__tests__/dlc/TxBuilder.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
DlcAcceptWithoutSigs,
DlcOffer,
FundingInput,
PayoutScriptOverrides,
} from '@node-dlc/messaging';
import { expect } from 'chai';

Expand Down Expand Up @@ -211,6 +212,19 @@ describe('TxBuilder', () => {
});
});

describe('BatchDlcTxBuilder.calculateMaxCollateral - payout script overrides', () => {
it('leaves room for the extra override bytes', () => {
const inputs = [createTestFundingInput(BigInt(1000000))];
const feeRate = BigInt(5);
expect(
BatchDlcTxBuilder.calculateMaxCollateral(inputs, feeRate, 1, 12),
).to.equal(
BatchDlcTxBuilder.calculateMaxCollateral(inputs, feeRate, 1) -
BigInt(12) * feeRate,
);
});
});

describe('BatchDlcTxBuilder.buildFundingTransaction - Dust Filtering', () => {
it('should create change outputs when above dust threshold', () => {
// Create inputs with sufficient value for both collateral and change
Expand Down Expand Up @@ -461,4 +475,109 @@ describe('TxBuilder', () => {
expect(tx.inputs.length).to.equal(3); // All unique inputs
});
});
describe('BatchDlcTxBuilder.buildFundingTransaction - payout script overrides', () => {
const p2tr = Buffer.from('5120' + '11'.repeat(32), 'hex');

const overridesPaying = (script: Buffer): PayoutScriptOverrides => {
const overrides = new PayoutScriptOverrides();
overrides.overrides = [
{
outcome: { type: 'enum', outcome: 'liquidated' },
scriptPubkey: script,
},
];
return overrides;
};

const build = (overrides?: PayoutScriptOverrides, feeRate = BigInt(1)) => {
const offer = createTestDlcOffer(
BigInt(1000000),
[createTestFundingInput(BigInt(1010000))],
feeRate,
);
offer.payoutScriptOverrides = overrides;
const accept = createTestDlcAccept(BigInt(1000000), [
createTestFundingInput(BigInt(1005000), 2),
]);
const tx = new BatchDlcTxBuilder(
[offer],
[accept],
).buildFundingTransaction();
// Outputs by serial id: funding (1), offer change (3), accept change (5).
return {
funding: tx.outputs[0].value.sats,
offerChange: tx.outputs[1].value.sats,
acceptChange: tx.outputs[2].value.sats,
};
};

it('reserves the accepter CET fee for a longer override script', () => {
const feeRate = BigInt(3);
const plain = build(undefined, feeRate);
const overridden = build(overridesPaying(p2tr), feeRate);

// ceil((249 + 4 * 34) / 4) - ceil((249 + 4 * 22) / 4) = 97 - 85 vbytes,
// paid by the accepter.
const extra = BigInt(12) * feeRate;
expect(overridden.funding).to.equal(plain.funding + extra);
expect(overridden.acceptChange).to.equal(plain.acceptChange - extra);
expect(overridden.offerChange).to.equal(plain.offerChange);
});

it('has a lone funding offerer reserve the extra bytes', () => {
const feeRate = BigInt(2);
const singleFunded = (overrides?: PayoutScriptOverrides) => {
const offer = createTestDlcOffer(
BigInt(1000000),
[createTestFundingInput(BigInt(1010000))],
feeRate,
);
offer.payoutScriptOverrides = overrides;
const accept = createTestDlcAccept(BigInt(0));
const tx = new BatchDlcTxBuilder(
[offer],
[accept],
).buildFundingTransaction();
return tx.outputs.map((o) => o.value.sats);
};

const [plainFunding, plainChange] = singleFunded();
const [funding, change] = singleFunded(overridesPaying(p2tr));
expect(funding).to.equal(plainFunding + BigInt(12) * feeRate);
expect(change).to.equal(plainChange - BigInt(12) * feeRate);
});

it('charges each contract of a batch for its own overrides', () => {
const offerInput = createTestFundingInput(BigInt(3000000));
const acceptInput = createTestFundingInput(BigInt(3000000), 2);
const offers = [0, 1].map((i) => {
const offer = createTestDlcOffer(BigInt(1000000), [offerInput]);
offer.fundOutputSerialId = BigInt(10 + i);
return offer;
});
const accepts = [0, 1].map(() =>
createTestDlcAccept(BigInt(1000000), [acceptInput]),
);
const fundingOutputs = () =>
new BatchDlcTxBuilder(offers, accepts)
.buildFundingTransaction()
.outputs.map((o) => o.value.sats);

const plain = fundingOutputs();
offers[0].payoutScriptOverrides = overridesPaying(p2tr);
const mixed = fundingOutputs();

// Outputs by serial id: offer change (3), accept change (5), then the
// funding outputs (10, 11). Only the first contract has an override.
expect(mixed[2]).to.equal(plain[2] + BigInt(12));
expect(mixed[3]).to.equal(plain[3]);
expect(mixed[1]).to.equal(plain[1] - BigInt(12));
expect(mixed[0]).to.equal(plain[0]);
});

it('keeps the fee when the override script is no longer', () => {
const short = Buffer.from('0014' + '22'.repeat(20), 'hex');
expect(build(overridesPaying(short))).to.deep.equal(build());
});
});
});
40 changes: 40 additions & 0 deletions packages/core/__tests__/dlc/TxFinalizer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { expect } from 'chai';

import {
DEFAULT_MAX_WITNESS_LEN,
DualFundingTxFinalizer,
fundingInputWithWitnessLen,
getFinalizerByCount,
getMaxWitnessLen,
} from '../../lib';
Expand Down Expand Up @@ -50,4 +52,42 @@ describe('TxFinalizer', () => {
).to.throw('Expected 2 witness lengths, got 1');
});
});
describe('acceptOverrideExtraLen', () => {
const p2wpkh = Buffer.alloc(22);
const inputs = () => [fundingInputWithWitnessLen(DEFAULT_MAX_WITNESS_LEN)];
const finalizer = (acceptFunds: boolean, extraLen?: number) =>
new DualFundingTxFinalizer(
inputs(),
p2wpkh,
p2wpkh,
acceptFunds ? inputs() : [],
p2wpkh,
p2wpkh,
BigInt(2),
1,
extraLen,
);

it('has the accepter pay for the extra bytes when it funds', () => {
// A 34-byte override for a 22-byte accept script: 12 extra vbytes,
// ceil((249 + 4 * 34) / 4) = 97 against 85.
expect(finalizer(true).acceptFutureFee).to.equal(BigInt(85 * 2));
expect(finalizer(true, 12).acceptFutureFee).to.equal(BigInt(97 * 2));
expect(finalizer(true, 12).offerFutureFee).to.equal(
finalizer(true).offerFutureFee,
);
});

it('has the offerer pay for them when the accepter funds nothing', () => {
expect(finalizer(false, 12).offerFutureFee).to.equal(
finalizer(false).offerFutureFee + BigInt(12 * 2),
);
expect(finalizer(false, 12).acceptFees).to.equal(BigInt(0));
});

it('rejects a negative or fractional length', () => {
expect(() => finalizer(true, -1)).to.throw(/non-negative integer/);
expect(() => finalizer(true, 1.5)).to.throw(/non-negative integer/);
});
});
});
20 changes: 17 additions & 3 deletions packages/core/lib/dlc/CoinSelect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,19 @@ const witnessLensFromInputCount = (
() => DEFAULT_MAX_WITNESS_LEN,
);

/**
* The fees a funding party pays, for coin selection.
*
* `overrideExtraLen` is the PayoutScriptOverrides bytes this party reserves
* CET fee for, summed over the contracts: the bytes by which the longest
* override script exceeds the accepter's payout script. The accepter pays
* them when it funds, the offerer when it funds the contract alone.
*/
export const dualFees = (
feeRate: bigint,
numInputsOrWitnessLens: number | number[],
numContracts: number,
overrideExtraLen = 0,
): bigint => {
const fakeSPK = Buffer.from(
'0014663117d27e78eb432505180654e603acb30e8a4a',
Expand All @@ -87,7 +96,7 @@ export const dualFees = (
);
const acceptInputs = [fundingInputWithWitnessLen(DEFAULT_MAX_WITNESS_LEN)];

return new DualFundingTxFinalizer(
const fees = new DualFundingTxFinalizer(
offerInputs,
fakeSPK,
fakeSPK,
Expand All @@ -97,6 +106,9 @@ export const dualFees = (
feeRate,
numContracts,
).offerFees;

// One vbyte of CET fee per extra override byte.
return fees + feeRate * BigInt(overrideExtraLen);
};

/**
Expand All @@ -113,6 +125,7 @@ export const dualFundingCoinSelect = (
utxos: UTXO[],
collaterals: bigint[], // in satoshis
feeRate: bigint,
overrideExtraLen = 0, // see dualFees
): { inputs: UTXO[]; fee: bigint } => {
utxos = [...utxos].sort((a, b) =>
Number(utxoScore(b, feeRate) - utxoScore(a, feeRate)),
Expand All @@ -134,7 +147,7 @@ export const dualFundingCoinSelect = (
if (utxoFee > utxo.value) {
if (i === utxos.length - 1)
return {
fee: dualFees(feeRate, 1, collaterals.length),
fee: dualFees(feeRate, 1, collaterals.length, overrideExtraLen),
inputs: [],
};
continue;
Expand All @@ -147,6 +160,7 @@ export const dualFundingCoinSelect = (
feeRate,
inputs.map((input) => getMaxWitnessLen(scriptTypeFromUtxo(input))),
collaterals.length,
overrideExtraLen,
);

// go again?
Expand All @@ -156,7 +170,7 @@ export const dualFundingCoinSelect = (
}

return {
fee: dualFees(feeRate, 1, collaterals.length),
fee: dualFees(feeRate, 1, collaterals.length, overrideExtraLen),
inputs: [],
};
};
38 changes: 34 additions & 4 deletions packages/core/lib/dlc/TxBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ export class BatchDlcTxBuilder {
* @param fundingInputs The inputs to be used for funding
* @param feeRatePerVb Fee rate in satoshis per virtual byte
* @param numContracts Number of DLC contracts being created (default: 1)
* @param overrideExtraLen PayoutScriptOverrides bytes the offerer reserves
* CET fee for, summed over the contracts: the bytes by which the longest
* override script exceeds the accepter's payout script (default: 0)
* @returns Maximum collateral amount in satoshis
*
* @example
Expand All @@ -67,6 +70,7 @@ export class BatchDlcTxBuilder {
fundingInputs: FundingInput[],
feeRatePerVb: bigint,
numContracts = 1,
overrideExtraLen = 0,
): bigint {
// Calculate total input value
const totalInputValue = fundingInputs.reduce((total, input) => {
Expand All @@ -87,6 +91,7 @@ export class BatchDlcTxBuilder {
fakeSPK,
feeRatePerVb,
numContracts,
overrideExtraLen,
);

// For exact-amount scenarios, we need to account for:
Expand Down Expand Up @@ -132,6 +137,7 @@ export class BatchDlcTxBuilder {
Script.p2wshLock(multisigScript),
);

const overrideExtraLens = this.overrideExtraLens();
const finalizer = new DualFundingTxFinalizer(
this.dlcOffers[0].fundingInputs,
this.dlcOffers[0].payoutSpk,
Expand All @@ -141,6 +147,7 @@ export class BatchDlcTxBuilder {
this.dlcAccepts[0].changeSpk,
this.dlcOffers[0].feeRatePerVb,
this.dlcOffers.length,
overrideExtraLens.reduce((total, len) => total + len, 0),
);

this.dlcOffers[0].fundingInputs.forEach((input) => {
Expand Down Expand Up @@ -193,15 +200,20 @@ export class BatchDlcTxBuilder {
return offerInput + acceptInput;
});

const fundingValues = totalInputs.map((totalInput) => {
// The extra override bytes are priced per contract, so each funding
// output carries its own contract's share rather than an even split.
const { offerOverrideExtraFee, acceptOverrideExtraFee } = finalizer;
const overrideExtraCharged =
offerOverrideExtraFee + acceptOverrideExtraFee > BigInt(0);
const fundingValues = totalInputs.map((totalInput, i) => {
const offerFutureFeePerOffer = new Decimal(
finalizer.offerFutureFee.toString(),
(finalizer.offerFutureFee - offerOverrideExtraFee).toString(),
)
.div(this.dlcOffers.length)
.ceil()
.toNumber();
const acceptFutureFeePerAccept = new Decimal(
finalizer.acceptFutureFee.toString(),
(finalizer.acceptFutureFee - acceptOverrideExtraFee).toString(),
)
.div(this.dlcAccepts.length)
.ceil()
Expand All @@ -210,7 +222,10 @@ export class BatchDlcTxBuilder {
return (
totalInput +
Value.fromSats(offerFutureFeePerOffer).sats +
Value.fromSats(acceptFutureFeePerAccept).sats
Value.fromSats(acceptFutureFeePerAccept).sats +
(overrideExtraCharged
? finalizer.feeRate * BigInt(overrideExtraLens[i])
: BigInt(0))
);
});

Expand Down Expand Up @@ -275,6 +290,21 @@ export class BatchDlcTxBuilder {
return tx.toTx();
}

/**
* For each contract, the bytes by which the longest PayoutScriptOverrides
* script exceeds the accepter's payout script, or zero. dlcdevkit reserves
* the accepter's CET fee at the longest script a CET may pay it.
*/
private overrideExtraLens(): number[] {
return this.dlcOffers.map((offer, i) => {
const acceptPayoutSpk = this.dlcAccepts[i].payoutSpk;
const longest =
offer.payoutScriptOverrides?.acceptPayoutScriptLen(acceptPayoutSpk) ??
acceptPayoutSpk.length;
return longest - acceptPayoutSpk.length;
});
}

private ensureSameFundingInputs(): void {
// Check for offers
const referenceOfferInputs = this.dlcOffers[0].fundingInputs.map((input) =>
Expand Down
Loading
Loading