-
Notifications
You must be signed in to change notification settings - Fork 1
/
simple-covenant.ts
398 lines (337 loc) · 9.94 KB
/
simple-covenant.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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"use strict";
import ElementsClient from "./elements-client";
import { IssueAssetResponse } from "./elements-client/module";
let ecpair = require("ecpair");
let { ECPairFactory } = ecpair;
let ecc = require("tiny-secp256k1");
let liquidjs = require("liquidjs-lib");
let bip341 = liquidjs.bip341;
let { amountWithPrecisionToSatoshis } = liquidjs.issuance;
let ECPair = ECPairFactory(ecc);
let regtest = liquidjs.networks.regtest;
const LBTC_ASSET_ID = regtest.assetHash;
// Unspendable pubkey described in https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki
// Using this exact value reduces privacy
const unspendablePubkey =
"0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0";
let privateKeyBuffer = Buffer.from(
"968f91395a8d682e5e3dd4a4f19465f1d9122cbbe82a5a624d863c39513a4eed",
"hex"
);
let keypair = ECPair.fromPrivateKey(privateKeyBuffer);
async function spendToCovenant(
assetId,
keypairAddress,
lbtcTxIdSource,
lbtcIndex,
assetTxId,
assetIndex,
lbtcAmount,
assetAmount,
rpcClient
) {
let enforceCovenant =
"OP_0 OP_INSPECTINPUTSCRIPTPUBKEY OP_DROP OP_0 OP_INSPECTOUTPUTSCRIPTPUBKEY OP_DROP OP_EQUAL";
const script = `${enforceCovenant}`.trim();
const leaves = [
{
scriptHex: liquidjs.script.fromASM(script).toString("hex"),
},
];
let treeRoot = bip341.toHashTree(leaves);
const bip341Factory = bip341.BIP341Factory(ecc);
const output = bip341Factory.taprootOutputScript(
Buffer.from(unspendablePubkey, "hex"),
treeRoot
);
const p2trAddress = liquidjs.address.fromOutputScript(output, regtest);
let assetUtxo0 = liquidjs.address.toOutputScript(keypairAddress);
const nonce = Buffer.from("00", "hex");
const assetBuffer = Buffer.concat([
Buffer.from("01", "hex"),
Buffer.from(assetId, "hex").reverse(),
]);
const lbtcBuffer = Buffer.concat([
Buffer.from("01", "hex"),
Buffer.from(LBTC_ASSET_ID, "hex").reverse(),
]);
let lbtcScript = liquidjs.address.toOutputScript(keypairAddress);
let pset = new liquidjs.Psbt({ network: regtest });
pset
.addInput({
hash: assetTxId,
index: assetIndex,
witnessUtxo: {
asset: assetBuffer,
script: assetUtxo0,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(assetAmount)
),
nonce,
},
})
.addInput({
hash: lbtcTxIdSource,
index: lbtcIndex,
witnessUtxo: {
asset: lbtcBuffer,
script: lbtcScript,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(lbtcAmount)
),
nonce,
},
})
//output
.addOutput({
asset: assetBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(assetAmount)
),
address: p2trAddress,
nonce,
})
//change
.addOutput({
asset: lbtcBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(lbtcAmount) - 500
),
address: keypairAddress,
nonce,
})
//fee
.addOutput({
nonce,
asset: lbtcBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(500),
script: Buffer.alloc(0),
});
pset.signInput(0, keypair);
pset.signInput(1, keypair);
pset.finalizeAllInputs();
let tx = pset.extractTransaction().toHex();
console.log("\n\nTransaction Hex:\n");
console.log(tx);
console.log("\n\n");
return rpcClient.request(`sendrawtransaction`, [tx]);
}
async function spendFromCovenant(
assetId,
keypairAddress,
assetScriptPubKey,
lbtcTxIdSource,
lbtcIndex,
assetTxId,
assetIndex,
lbtcAmount,
assetAmount,
rpcClient
) {
let enforceCovenant =
"OP_0 OP_INSPECTINPUTSCRIPTPUBKEY OP_DROP OP_0 OP_INSPECTOUTPUTSCRIPTPUBKEY OP_DROP OP_EQUAL";
const script = `${enforceCovenant}`.trim();
const leaves = [
{
scriptHex: liquidjs.script.fromASM(script).toString("hex"),
},
];
const leaf = leaves[0];
const leafHash = bip341.tapLeafHash(leaf);
const hashTree = bip341.toHashTree(leaves);
const pathToLeaf = bip341.findScriptPath(hashTree, leafHash);
const bip341Factory = bip341.BIP341Factory(ecc);
const taprootStack = bip341Factory.taprootSignScriptStack(
Buffer.from(unspendablePubkey, "hex"),
leaf,
hashTree.hash,
pathToLeaf
);
let treeRoot = bip341.toHashTree(leaves);
const output = bip341Factory.taprootOutputScript(
Buffer.from(unspendablePubkey, "hex"),
treeRoot
);
const p2trAddress = liquidjs.address.fromOutputScript(output, regtest);
let assetUtxo0 = Buffer.from(assetScriptPubKey, "hex");
const nonce = Buffer.from("00", "hex");
const assetBuffer = Buffer.concat([
Buffer.from("01", "hex"),
Buffer.from(assetId, "hex").reverse(),
]);
const lbtcBuffer = Buffer.concat([
Buffer.from("01", "hex"),
Buffer.from(LBTC_ASSET_ID, "hex").reverse(),
]);
let lbtcScript = liquidjs.address.toOutputScript(keypairAddress);
let pset = new liquidjs.Psbt({ network: regtest });
pset
.addInput({
hash: assetTxId,
index: assetIndex,
witnessScript: liquidjs.script.fromASM(script),
witnessUtxo: {
asset: assetBuffer,
script: assetUtxo0,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(assetAmount)
),
nonce,
},
})
.addInput({
hash: lbtcTxIdSource,
index: lbtcIndex,
witnessUtxo: {
asset: lbtcBuffer,
script: lbtcScript,
value: liquidjs.confidential.satoshiToConfidentialValue(lbtcAmount),
nonce,
},
})
.addOutput({
asset: assetBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(
amountWithPrecisionToSatoshis(assetAmount)
),
address: p2trAddress,
nonce,
})
.addOutput({
asset: lbtcBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(lbtcAmount - 500),
address: keypairAddress,
nonce,
})
.addOutput({
nonce,
asset: lbtcBuffer,
value: liquidjs.confidential.satoshiToConfidentialValue(500),
script: Buffer.alloc(0),
});
pset.signInput(1, keypair);
pset.finalizeInput(1);
pset.updateInput(0, {
finalScriptWitness: liquidjs.witnessStackToScriptWitness([...taprootStack]),
});
let tx = pset.extractTransaction().toHex();
console.log("\n\nTransaction Hex:\n\n");
console.log(tx);
console.log("\n\n");
console.log("Try broadcast final tx:\n\n");
return rpcClient.request(`sendrawtransaction`, [tx]);
}
let getOutputForAssetId = (tx, assetId) => {
let { vout } = tx;
for (let i = 0; i < vout.length; i++) {
if (vout[i].asset == assetId && vout[i].scriptPubKey.asm) {
return i;
}
}
return -1;
};
async function run() {
let elementsClient = new ElementsClient();
let balance = await elementsClient.getBalance();
console.log(`LBTC Balance: ${balance.bitcoin}\n\n`);
/************************/
console.log("Issuing new asset...");
const amount = 10;
const reissuanceTokenAmount = 1;
let issueAssetResponse: IssueAssetResponse = await elementsClient.issueAsset(
amount,
reissuanceTokenAmount
);
console.log(`issueasset result: ${JSON.stringify(issueAssetResponse)}\n\n`);
/************************/
console.log("Sending new asset to test address...");
const lbtcAmount = .0001;
const { address: keypairAddress } = liquidjs.payments.p2wpkh({
network: regtest,
pubkey: keypair.publicKey,
});
let sendAssetTxId = await elementsClient.sendToAddress(
keypairAddress,
amount,
issueAssetResponse.asset
);
await elementsClient.sendToAddress(
keypairAddress,
reissuanceTokenAmount,
issueAssetResponse.token
);
console.log(
`sendtoaddress (${issueAssetResponse.asset}) result: ${sendAssetTxId}\n\n`
);
/************************/
console.log("Sending LBTC to test address...");
let lbtcFundingTxId = await elementsClient.sendToAddress(
keypairAddress,
lbtcAmount
);
console.log(`sendToAddress (BTC) result: ${lbtcFundingTxId}\n\n`);
/************************/
console.log("Determining which output index holds LBTC...");
let lbtcFundingTransaction = await elementsClient.getRawTransaction(
lbtcFundingTxId,
true
);
let lbtcFaucetVout = getOutputForAssetId(
lbtcFundingTransaction,
LBTC_ASSET_ID
);
/************************/
console.log(
`Determining which output index holds ${issueAssetResponse.asset}...`
);
let assetFundingTransaction = await elementsClient.getRawTransaction(
sendAssetTxId,
true
);
let assetFaucetVout = getOutputForAssetId(
assetFundingTransaction,
issueAssetResponse.asset
);
/************************/
console.log(`Spending to covenant...`);
let resp = await spendToCovenant(
issueAssetResponse.asset,
keypairAddress,
lbtcFundingTxId,
lbtcFaucetVout,
sendAssetTxId,
assetFaucetVout,
lbtcAmount,
amount,
elementsClient.getRawClient()
);
console.log("TXID:", resp);
console.log("FINISHED\n");
/************************/
console.log(
`Determining which output index from the covenant spend transaction holds LBTC...`
);
let spendToCovenantTx = await elementsClient.getRawTransaction(resp, true);
let lbtcVout = getOutputForAssetId(spendToCovenantTx, LBTC_ASSET_ID);
let assetVout = getOutputForAssetId(
spendToCovenantTx,
issueAssetResponse.asset
);
/************************/
console.log(`Spending from covenant...`);
let spendFromCovenantTx = await spendFromCovenant(
issueAssetResponse.asset,
keypairAddress,
spendToCovenantTx.vout[assetVout].scriptPubKey.hex,
resp,
lbtcVout,
resp,
assetVout,
// '- 500' because 500 was taken as fee in 'spendToCovenant'
amountWithPrecisionToSatoshis(lbtcAmount) - 500,
10,
elementsClient.getRawClient()
);
console.log("Final transaction id:", spendFromCovenantTx);
}
run();