-
Notifications
You must be signed in to change notification settings - Fork 18
/
Claim.ts
175 lines (151 loc) · 5.51 KB
/
Claim.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/**
* This file is based on the repository github.com/submarineswaps/swaps-service created by Alex Bosworth
*/
import ops from '@boltz/bitcoin-ops';
import * as bip65 from 'bip65';
import { Transaction, crypto, script } from 'bitcoinjs-lib';
import { tapleafHash, toHashTree } from 'bitcoinjs-lib/src/payments/bip341';
import * as varuint from 'varuint-bitcoin';
import { getHexString } from '../Utils';
import { OutputType } from '../consts/Enums';
import { ClaimDetails } from '../consts/Types';
import { encodeSignature, scriptBuffersToScript } from './SwapUtils';
import { createControlBlock, hashForWitnessV1 } from './TaprootUtils';
const dummyTaprootSignature = Buffer.alloc(64);
export const isRelevantTaprootOutput = (
utxo: Omit<ClaimDetails, 'value' | 'keys'>,
) => utxo.type === OutputType.Taproot && utxo.cooperative !== true;
export const validateInputs = (
utxos: Omit<ClaimDetails, 'value' | 'keys'>[],
) => {
if (
utxos
.filter((utxo) => utxo.type !== OutputType.Taproot)
.some((utxo) => utxo.redeemScript === undefined)
) {
throw 'not all non Taproot inputs have a redeem script';
}
const relevantTaprootOutputs = utxos.filter(isRelevantTaprootOutput);
if (relevantTaprootOutputs.some((utxo) => utxo.swapTree === undefined)) {
throw 'not all Taproot inputs have a swap tree';
}
if (relevantTaprootOutputs.some((utxo) => utxo.internalKey === undefined)) {
throw 'not all Taproot inputs have an internal key';
}
};
/**
* Claim swaps
*
* @param utxos UTXOs that should be claimed or refunded
* @param destinationScript the output script to which the funds should be sent
* @param fee how many satoshis should be paid as fee
* @param isRbf whether the transaction should signal full Replace-by-Fee
* @param timeoutBlockHeight locktime of the transaction; only needed if the transaction is a refund
* @param isRefund whether the transaction is a refund or claim
*/
export const constructClaimTransaction = (
utxos: ClaimDetails[],
destinationScript: Buffer,
fee: number,
isRbf = true,
timeoutBlockHeight?: number,
isRefund = false,
): Transaction => {
validateInputs(utxos);
const tx = new Transaction();
// Refund transactions are just like claim ones and therefore this method
// is also used for refunds. The locktime of refund transactions has to be
// after the timelock of the UTXO is expired
if (timeoutBlockHeight) {
tx.locktime = bip65.encode({ blocks: timeoutBlockHeight });
}
// The sum of the values of all UTXOs that should be claimed or refunded
let utxoValueSum = BigInt(0);
utxos.forEach((utxo) => {
utxoValueSum += BigInt(utxo.value);
// Add the swap as input to the transaction
// RBF reference: https://github.com/bitcoin/bips/blob/master/bip-0125.mediawiki#summary
tx.addInput(utxo.txHash, utxo.vout, isRbf ? 0xfffffffd : 0xffffffff);
});
// Send the sum of the UTXOs minus the estimated fee to the destination address
tx.addOutput(destinationScript, Number(utxoValueSum - BigInt(fee)));
utxos.forEach((utxo, index) => {
switch (utxo.type) {
// Construct and sign the input scripts for P2SH inputs
case OutputType.Legacy: {
const sigHash = tx.hashForSignature(
index,
utxo.redeemScript!,
Transaction.SIGHASH_ALL,
);
const signature = utxo.keys.sign(sigHash);
const inputScript = [
encodeSignature(Transaction.SIGHASH_ALL, signature),
utxo.preimage,
ops.OP_PUSHDATA1,
utxo.redeemScript!,
];
tx.setInputScript(index, scriptBuffersToScript(inputScript));
break;
}
// Construct the nested redeem script for nested SegWit inputs
case OutputType.Compatibility: {
const nestedScript = [
getHexString(Buffer.from(varuint.encode(ops.OP_0).buffer)),
crypto.sha256(utxo.redeemScript!),
];
const nested = scriptBuffersToScript(nestedScript);
tx.setInputScript(index, scriptBuffersToScript([nested]));
break;
}
}
// Construct and sign the witness for (nested) SegWit inputs
// When the Taproot output is spent cooperatively, we leave it empty
if (utxo.type === OutputType.Taproot) {
if (utxo.cooperative !== true) {
const tapLeaf = isRefund
? utxo.swapTree!.refundLeaf
: utxo.swapTree!.claimLeaf;
const sigHash = hashForWitnessV1(
utxos,
tx,
index,
tapleafHash(tapLeaf),
Transaction.SIGHASH_DEFAULT,
);
const signature = utxo.keys.signSchnorr(sigHash);
const witness = isRefund ? [signature] : [signature, utxo.preimage];
tx.setWitness(
index,
witness.concat([
tapLeaf.output,
createControlBlock(
toHashTree(utxo.swapTree!.tree),
tapLeaf,
utxo.internalKey!,
),
]),
);
} else {
// Stub the signature to allow for accurate fee estimations
tx.setWitness(index, [dummyTaprootSignature]);
}
} else if (
utxo.type === OutputType.Bech32 ||
utxo.type === OutputType.Compatibility
) {
const sigHash = tx.hashForWitnessV0(
index,
utxo.redeemScript!,
utxo.value,
Transaction.SIGHASH_ALL,
);
const signature = script.signature.encode(
utxo.keys.sign(sigHash),
Transaction.SIGHASH_ALL,
);
tx.setWitness(index, [signature, utxo.preimage, utxo.redeemScript!]);
}
});
return tx;
};