@rsksmart/powpeg-sdk 2.0.0-beta.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -0
- package/dist/index.d.mts +29 -5
- package/dist/index.d.ts +29 -5
- package/dist/index.js +123 -32
- package/dist/index.mjs +118 -27
- package/docs/api.md +1 -1
- package/docs/bitcoin-signers.md +40 -14
- package/docs/setup.md +8 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -28,6 +28,22 @@ await sdk.signAndBroadcastPegout(tx, someEthersSigner)
|
|
|
28
28
|
|
|
29
29
|
The SDK ships no signer implementations — see [`docs/bitcoin-signers.md`](./docs/bitcoin-signers.md) for the `BitcoinSigner` contract and how to supply one.
|
|
30
30
|
|
|
31
|
+
## Supported Bitcoin address types
|
|
32
|
+
|
|
33
|
+
| Script | Address format (main / test) | Fund a peg-in | Preferred for change | Refund address in the peg-in |
|
|
34
|
+
|---|---|---|---|---|
|
|
35
|
+
| P2PKH (legacy, BIP 44) | `1…` / `m…`, `n…` | yes | yes | yes |
|
|
36
|
+
| P2SH-P2WPKH (nested segwit, BIP 49) | `3…` / `2…` | yes, if the signer implements `getPublicKey` | yes, if the signer implements `getPublicKey` | yes |
|
|
37
|
+
| P2WPKH (native segwit, BIP 84) | `bc1q…` / `tb1q…` | yes | yes | no |
|
|
38
|
+
| Other P2SH (multisig, P2SH-P2WSH) | `3…` / `2…` | no | no | no |
|
|
39
|
+
| P2WSH | `bc1q…` / `tb1q…` (62 chars) | no | no | no |
|
|
40
|
+
| P2TR (taproot, BIP 86) | `bc1p…` / `tb1p…` | no | no | no |
|
|
41
|
+
|
|
42
|
+
Funding support is decided from each UTXO's `scriptPubKey`, not from the address format. A UTXO the SDK
|
|
43
|
+
cannot sign is skipped when it discovers UTXOs itself, and refused with `UnsupportedAddressTypeError` when
|
|
44
|
+
named in `selectedUtxos`. See [Address types and derivation](./docs/bitcoin-signers.md#address-types-and-derivation)
|
|
45
|
+
for the details and the refund address rules.
|
|
46
|
+
|
|
31
47
|
## API Reference
|
|
32
48
|
|
|
33
49
|
See [`docs/api.md`](./docs/api.md) for the full table of public exports (`PowPegSDK` and every exported type/error).
|
package/dist/index.d.mts
CHANGED
|
@@ -55,6 +55,14 @@ interface BitcoinSigner {
|
|
|
55
55
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
56
56
|
getChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
57
57
|
signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise<string>;
|
|
58
|
+
/**
|
|
59
|
+
* Compressed public key behind one of the signer's P2SH-P2WPKH (nested segwit) addresses, encoded by the
|
|
60
|
+
* signer as a hex string (66 characters, `0x` prefix optional), or `undefined` if the signer does not know
|
|
61
|
+
* it. Optional: without it, or for an address whose key it
|
|
62
|
+
* does not return, UTXOs discovered at P2SH addresses are skipped, and P2SH UTXOs passed in
|
|
63
|
+
* `selectedUtxos` are refused with `UnsupportedAddressTypeError`.
|
|
64
|
+
*/
|
|
65
|
+
getPublicKey?(address: string): Promise<string | undefined>;
|
|
58
66
|
}
|
|
59
67
|
/**
|
|
60
68
|
* Contract for a Bitcoin data provider (fee rates, UTXOs, raw transactions, broadcasting).
|
|
@@ -253,6 +261,10 @@ declare class PowPegSDK {
|
|
|
253
261
|
private getUtxos;
|
|
254
262
|
private getAddressesWithDetails;
|
|
255
263
|
private groupAddressesByUsage;
|
|
264
|
+
/**
|
|
265
|
+
* Whether the SDK can build a signable input for a UTXO held by `btcAddress`. A P2SH address counts only
|
|
266
|
+
* when `signer` returns a public key whose P2SH-P2WPKH script matches it; the key is cached in `publicKeys`.
|
|
267
|
+
*/
|
|
256
268
|
private isSpendableAddress;
|
|
257
269
|
private groupAddressesByBalance;
|
|
258
270
|
private getAddressesGroupedByUsage;
|
|
@@ -285,6 +297,18 @@ declare class PowPegSDK {
|
|
|
285
297
|
private getValidatedFeeRate;
|
|
286
298
|
private calculatePeginFee;
|
|
287
299
|
private calculateFeeAndSelectedInputs;
|
|
300
|
+
/**
|
|
301
|
+
* Redeem script for each funding input, resolved in order; see {@link PowPegSDK.resolveRedeemScript}.
|
|
302
|
+
* @throws {UnsupportedAddressTypeError} If an input's script is neither, or its redeem script cannot be resolved.
|
|
303
|
+
*/
|
|
304
|
+
private resolveRedeemScripts;
|
|
305
|
+
/**
|
|
306
|
+
* Redeem script of one funding input: undefined for P2PKH and P2WPKH, the P2SH-P2WPKH redeem script
|
|
307
|
+
* built from the public key `signer` reports for a P2SH input. The address is asked once, and not at all
|
|
308
|
+
* when `publicKeys` already holds its key.
|
|
309
|
+
* @throws {UnsupportedAddressTypeError} If the input's script is neither, or its redeem script cannot be resolved.
|
|
310
|
+
*/
|
|
311
|
+
private resolveRedeemScript;
|
|
288
312
|
/**
|
|
289
313
|
* Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
|
|
290
314
|
* using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
|
|
@@ -399,15 +423,15 @@ declare class PowPegSDK {
|
|
|
399
423
|
}>;
|
|
400
424
|
/**
|
|
401
425
|
* Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
|
|
402
|
-
* and waits for it to be mined.
|
|
426
|
+
* and waits for it to be mined on the SDK's RSK RPC node.
|
|
403
427
|
* @param {UnsignedPegout} tx - The peg-out transaction request, as returned by {@link createPegout}. Forwarded to the signer as given, so gas, nonce and fee fields set by the caller are honoured; only an absent chain id is filled in.
|
|
404
428
|
* @param {ethers.Signer} signer - Ethers signer used to send the transaction.
|
|
405
|
-
* @returns The mined transaction receipt
|
|
429
|
+
* @returns The mined transaction receipt.
|
|
406
430
|
* @throws {WrongNetworkError} If the transaction's chain id, or the signer's chain, doesn't match the network the SDK was configured for.
|
|
407
431
|
* @throws {TransactionRevertedError} If the transaction was mined but reverted.
|
|
408
432
|
* @throws {PegoutRejectedError} If the transaction was mined but the Bridge rejected and refunded the release request.
|
|
409
433
|
*/
|
|
410
|
-
signAndBroadcastPegout(tx: UnsignedPegout, signer: ethers.Signer): Promise<ethers.providers.TransactionReceipt
|
|
434
|
+
signAndBroadcastPegout(tx: UnsignedPegout, signer: ethers.Signer): Promise<ethers.providers.TransactionReceipt>;
|
|
411
435
|
/**
|
|
412
436
|
* Fetches the current status of a peg-in or peg-out transaction from the configured API.
|
|
413
437
|
* @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
|
|
@@ -502,8 +526,8 @@ declare class TransactionRevertedError extends Error {
|
|
|
502
526
|
}
|
|
503
527
|
/**
|
|
504
528
|
* Thrown when a UTXO is held by an address whose type the SDK cannot build a signable PSBT input for.
|
|
505
|
-
* A P2SH input
|
|
506
|
-
*
|
|
529
|
+
* A P2SH input is supported only as P2SH-P2WPKH, and only when the PSBT's signer implements
|
|
530
|
+
* `getPublicKey` and returns the key the address commits to.
|
|
507
531
|
*/
|
|
508
532
|
declare class UnsupportedAddressTypeError extends Error {
|
|
509
533
|
readonly address: string;
|
package/dist/index.d.ts
CHANGED
|
@@ -55,6 +55,14 @@ interface BitcoinSigner {
|
|
|
55
55
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
56
56
|
getChangeAddresses(bundleSize: number): Promise<string[]>;
|
|
57
57
|
signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise<string>;
|
|
58
|
+
/**
|
|
59
|
+
* Compressed public key behind one of the signer's P2SH-P2WPKH (nested segwit) addresses, encoded by the
|
|
60
|
+
* signer as a hex string (66 characters, `0x` prefix optional), or `undefined` if the signer does not know
|
|
61
|
+
* it. Optional: without it, or for an address whose key it
|
|
62
|
+
* does not return, UTXOs discovered at P2SH addresses are skipped, and P2SH UTXOs passed in
|
|
63
|
+
* `selectedUtxos` are refused with `UnsupportedAddressTypeError`.
|
|
64
|
+
*/
|
|
65
|
+
getPublicKey?(address: string): Promise<string | undefined>;
|
|
58
66
|
}
|
|
59
67
|
/**
|
|
60
68
|
* Contract for a Bitcoin data provider (fee rates, UTXOs, raw transactions, broadcasting).
|
|
@@ -253,6 +261,10 @@ declare class PowPegSDK {
|
|
|
253
261
|
private getUtxos;
|
|
254
262
|
private getAddressesWithDetails;
|
|
255
263
|
private groupAddressesByUsage;
|
|
264
|
+
/**
|
|
265
|
+
* Whether the SDK can build a signable input for a UTXO held by `btcAddress`. A P2SH address counts only
|
|
266
|
+
* when `signer` returns a public key whose P2SH-P2WPKH script matches it; the key is cached in `publicKeys`.
|
|
267
|
+
*/
|
|
256
268
|
private isSpendableAddress;
|
|
257
269
|
private groupAddressesByBalance;
|
|
258
270
|
private getAddressesGroupedByUsage;
|
|
@@ -285,6 +297,18 @@ declare class PowPegSDK {
|
|
|
285
297
|
private getValidatedFeeRate;
|
|
286
298
|
private calculatePeginFee;
|
|
287
299
|
private calculateFeeAndSelectedInputs;
|
|
300
|
+
/**
|
|
301
|
+
* Redeem script for each funding input, resolved in order; see {@link PowPegSDK.resolveRedeemScript}.
|
|
302
|
+
* @throws {UnsupportedAddressTypeError} If an input's script is neither, or its redeem script cannot be resolved.
|
|
303
|
+
*/
|
|
304
|
+
private resolveRedeemScripts;
|
|
305
|
+
/**
|
|
306
|
+
* Redeem script of one funding input: undefined for P2PKH and P2WPKH, the P2SH-P2WPKH redeem script
|
|
307
|
+
* built from the public key `signer` reports for a P2SH input. The address is asked once, and not at all
|
|
308
|
+
* when `publicKeys` already holds its key.
|
|
309
|
+
* @throws {UnsupportedAddressTypeError} If the input's script is neither, or its redeem script cannot be resolved.
|
|
310
|
+
*/
|
|
311
|
+
private resolveRedeemScript;
|
|
288
312
|
/**
|
|
289
313
|
* Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
|
|
290
314
|
* using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
|
|
@@ -399,15 +423,15 @@ declare class PowPegSDK {
|
|
|
399
423
|
}>;
|
|
400
424
|
/**
|
|
401
425
|
* Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
|
|
402
|
-
* and waits for it to be mined.
|
|
426
|
+
* and waits for it to be mined on the SDK's RSK RPC node.
|
|
403
427
|
* @param {UnsignedPegout} tx - The peg-out transaction request, as returned by {@link createPegout}. Forwarded to the signer as given, so gas, nonce and fee fields set by the caller are honoured; only an absent chain id is filled in.
|
|
404
428
|
* @param {ethers.Signer} signer - Ethers signer used to send the transaction.
|
|
405
|
-
* @returns The mined transaction receipt
|
|
429
|
+
* @returns The mined transaction receipt.
|
|
406
430
|
* @throws {WrongNetworkError} If the transaction's chain id, or the signer's chain, doesn't match the network the SDK was configured for.
|
|
407
431
|
* @throws {TransactionRevertedError} If the transaction was mined but reverted.
|
|
408
432
|
* @throws {PegoutRejectedError} If the transaction was mined but the Bridge rejected and refunded the release request.
|
|
409
433
|
*/
|
|
410
|
-
signAndBroadcastPegout(tx: UnsignedPegout, signer: ethers.Signer): Promise<ethers.providers.TransactionReceipt
|
|
434
|
+
signAndBroadcastPegout(tx: UnsignedPegout, signer: ethers.Signer): Promise<ethers.providers.TransactionReceipt>;
|
|
411
435
|
/**
|
|
412
436
|
* Fetches the current status of a peg-in or peg-out transaction from the configured API.
|
|
413
437
|
* @param {string} txHash - The Bitcoin or Rootstock transaction hash to look up.
|
|
@@ -502,8 +526,8 @@ declare class TransactionRevertedError extends Error {
|
|
|
502
526
|
}
|
|
503
527
|
/**
|
|
504
528
|
* Thrown when a UTXO is held by an address whose type the SDK cannot build a signable PSBT input for.
|
|
505
|
-
* A P2SH input
|
|
506
|
-
*
|
|
529
|
+
* A P2SH input is supported only as P2SH-P2WPKH, and only when the PSBT's signer implements
|
|
530
|
+
* `getPublicKey` and returns the key the address commits to.
|
|
507
531
|
*/
|
|
508
532
|
declare class UnsupportedAddressTypeError extends Error {
|
|
509
533
|
readonly address: string;
|
package/dist/index.js
CHANGED
|
@@ -52,7 +52,7 @@ __export(index_exports, {
|
|
|
52
52
|
module.exports = __toCommonJS(index_exports);
|
|
53
53
|
|
|
54
54
|
// src/sdk/powpeg.ts
|
|
55
|
-
var
|
|
55
|
+
var import_bitcoinjs_lib4 = require("bitcoinjs-lib");
|
|
56
56
|
|
|
57
57
|
// src/types.ts
|
|
58
58
|
var import_bitcoinjs_lib = require("bitcoinjs-lib");
|
|
@@ -110,6 +110,7 @@ var Network = {
|
|
|
110
110
|
};
|
|
111
111
|
|
|
112
112
|
// src/utils.ts
|
|
113
|
+
var import_bitcoinjs_lib3 = require("bitcoinjs-lib");
|
|
113
114
|
function remove0x(hex) {
|
|
114
115
|
return hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
115
116
|
}
|
|
@@ -156,9 +157,24 @@ function isP2pkhScript(script) {
|
|
|
156
157
|
function isP2wpkhScript(script) {
|
|
157
158
|
return script.length === 22 && script[0] === 0 && script[1] === 20;
|
|
158
159
|
}
|
|
159
|
-
function
|
|
160
|
+
function isFullySupportedFundingScript(script) {
|
|
160
161
|
return isP2pkhScript(script) || isP2wpkhScript(script);
|
|
161
162
|
}
|
|
163
|
+
function deriveP2shP2wpkhRedeemScript(script, publicKeyHex) {
|
|
164
|
+
if (!isP2shScript(script) || typeof publicKeyHex !== "string") {
|
|
165
|
+
return void 0;
|
|
166
|
+
}
|
|
167
|
+
const publicKey = remove0x(publicKeyHex.trim());
|
|
168
|
+
if (!/^0[23][0-9a-fA-F]{64}$/.test(publicKey)) {
|
|
169
|
+
return void 0;
|
|
170
|
+
}
|
|
171
|
+
try {
|
|
172
|
+
const redeem = import_bitcoinjs_lib3.payments.p2wpkh({ pubkey: Buffer.from(publicKey, "hex") });
|
|
173
|
+
return import_bitcoinjs_lib3.payments.p2sh({ redeem }).output?.equals(script) ? redeem.output : void 0;
|
|
174
|
+
} catch {
|
|
175
|
+
return void 0;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
162
178
|
|
|
163
179
|
// src/bridge.ts
|
|
164
180
|
var import_rsk_precompiled_abis = require("@rsksmart/rsk-precompiled-abis");
|
|
@@ -626,12 +642,27 @@ var PowPegSDK = class {
|
|
|
626
642
|
});
|
|
627
643
|
return { used, unused };
|
|
628
644
|
}
|
|
629
|
-
|
|
645
|
+
/**
|
|
646
|
+
* Whether the SDK can build a signable input for a UTXO held by `btcAddress`. A P2SH address counts only
|
|
647
|
+
* when `signer` returns a public key whose P2SH-P2WPKH script matches it; the key is cached in `publicKeys`.
|
|
648
|
+
*/
|
|
649
|
+
async isSpendableAddress(btcAddress, signer, publicKeys) {
|
|
650
|
+
let script;
|
|
630
651
|
try {
|
|
631
|
-
|
|
652
|
+
script = import_bitcoinjs_lib4.address.toOutputScript(btcAddress, this.btcNetworkConfig.lib);
|
|
632
653
|
} catch {
|
|
633
654
|
return false;
|
|
634
655
|
}
|
|
656
|
+
if (isFullySupportedFundingScript(script)) {
|
|
657
|
+
return true;
|
|
658
|
+
}
|
|
659
|
+
if (!isP2shScript(script)) {
|
|
660
|
+
return false;
|
|
661
|
+
}
|
|
662
|
+
if (!publicKeys.has(btcAddress)) {
|
|
663
|
+
publicKeys.set(btcAddress, await signer.getPublicKey?.(btcAddress));
|
|
664
|
+
}
|
|
665
|
+
return deriveP2shP2wpkhRedeemScript(script, publicKeys.get(btcAddress)) !== void 0;
|
|
635
666
|
}
|
|
636
667
|
groupAddressesByBalance(addresses) {
|
|
637
668
|
const withBalance = [];
|
|
@@ -689,7 +720,7 @@ var PowPegSDK = class {
|
|
|
689
720
|
SEGWIT: "02"
|
|
690
721
|
};
|
|
691
722
|
if (refundAddressType === "LEGACY" || refundAddressType === "SEGWIT") {
|
|
692
|
-
const hash =
|
|
723
|
+
const hash = import_bitcoinjs_lib4.address.fromBase58Check(refundAddress).hash.toString("hex");
|
|
693
724
|
output += `${prefixes[refundAddressType]}${hash}`;
|
|
694
725
|
}
|
|
695
726
|
}
|
|
@@ -725,9 +756,9 @@ var PowPegSDK = class {
|
|
|
725
756
|
*/
|
|
726
757
|
async createPegin(amount, recipientAddress, selectedUtxos, signer = this.bitcoinSigner) {
|
|
727
758
|
const addresses = await this.getAddressesGroupedByUsage(signer);
|
|
728
|
-
const psbt = new
|
|
759
|
+
const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
|
|
729
760
|
const refundAddress = addresses.nonChange.unused[0]?.address;
|
|
730
|
-
const { output: script } =
|
|
761
|
+
const { output: script } = import_bitcoinjs_lib4.payments.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
|
|
731
762
|
if (script) {
|
|
732
763
|
psbt.addOutput({
|
|
733
764
|
script,
|
|
@@ -741,6 +772,7 @@ var PowPegSDK = class {
|
|
|
741
772
|
});
|
|
742
773
|
let utxos;
|
|
743
774
|
let skippedSatoshis = 0n;
|
|
775
|
+
const publicKeys = /* @__PURE__ */ new Map();
|
|
744
776
|
if (selectedUtxos) {
|
|
745
777
|
utxos = [...selectedUtxos];
|
|
746
778
|
} else {
|
|
@@ -749,12 +781,25 @@ var PowPegSDK = class {
|
|
|
749
781
|
throw new SigningError("The signer derived no addresses, so there is nothing to discover UTXOs from. Pass selectedUtxos to fund from a set you resolved yourself.");
|
|
750
782
|
}
|
|
751
783
|
const { withBalance } = this.groupAddressesByBalance(usedAddresses);
|
|
752
|
-
const spendable =
|
|
753
|
-
|
|
784
|
+
const spendable = [];
|
|
785
|
+
for (const address2 of withBalance) {
|
|
786
|
+
if (await this.isSpendableAddress(address2.address, signer, publicKeys).catch(() => false)) {
|
|
787
|
+
spendable.push(address2);
|
|
788
|
+
} else {
|
|
789
|
+
skippedSatoshis += BigInt(address2.balance);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
754
792
|
utxos = await this.getUtxos(spendable);
|
|
755
793
|
}
|
|
756
|
-
|
|
757
|
-
|
|
794
|
+
let changeAddress;
|
|
795
|
+
for (const address2 of addresses.change.unused) {
|
|
796
|
+
if (await this.isSpendableAddress(address2.address, signer, publicKeys).catch(() => false)) {
|
|
797
|
+
changeAddress = address2;
|
|
798
|
+
break;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
changeAddress ??= addresses.change.unused[0];
|
|
802
|
+
this.funding.set(psbt, { utxos, changeAddress: changeAddress?.address, skippedSatoshis, publicKeys });
|
|
758
803
|
this.psbtSigner.set(psbt, signer);
|
|
759
804
|
return psbt;
|
|
760
805
|
}
|
|
@@ -809,6 +854,59 @@ var PowPegSDK = class {
|
|
|
809
854
|
}
|
|
810
855
|
return { inputs, change: Math.abs(rest), totalFee };
|
|
811
856
|
}
|
|
857
|
+
/**
|
|
858
|
+
* Redeem script for each funding input, resolved in order; see {@link PowPegSDK.resolveRedeemScript}.
|
|
859
|
+
* @throws {UnsupportedAddressTypeError} If an input's script is neither, or its redeem script cannot be resolved.
|
|
860
|
+
*/
|
|
861
|
+
async resolveRedeemScripts(inputs, scripts, publicKeys, signer) {
|
|
862
|
+
const redeemScripts = [];
|
|
863
|
+
for (const [index, input] of inputs.entries()) {
|
|
864
|
+
redeemScripts.push(await this.resolveRedeemScript(input, scripts[index], publicKeys, signer));
|
|
865
|
+
}
|
|
866
|
+
return redeemScripts;
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* Redeem script of one funding input: undefined for P2PKH and P2WPKH, the P2SH-P2WPKH redeem script
|
|
870
|
+
* built from the public key `signer` reports for a P2SH input. The address is asked once, and not at all
|
|
871
|
+
* when `publicKeys` already holds its key.
|
|
872
|
+
* @throws {UnsupportedAddressTypeError} If the input's script is neither, or its redeem script cannot be resolved.
|
|
873
|
+
*/
|
|
874
|
+
async resolveRedeemScript(input, script, publicKeys, signer) {
|
|
875
|
+
if (isFullySupportedFundingScript(script)) {
|
|
876
|
+
return void 0;
|
|
877
|
+
}
|
|
878
|
+
const suffix = "Fund the peg-in from a legacy (P2PKH), nested segwit (P2SH-P2WPKH) or native segwit (P2WPKH) address, or pass selectedUtxos that exclude this one.";
|
|
879
|
+
if (!isP2shScript(script)) {
|
|
880
|
+
throw new UnsupportedAddressTypeError(
|
|
881
|
+
input.address,
|
|
882
|
+
`UTXO ${input.txid}:${input.vout} is held by ${input.address}, whose script type the SDK cannot build a signable input for. ${suffix}`
|
|
883
|
+
);
|
|
884
|
+
}
|
|
885
|
+
if (!signer) {
|
|
886
|
+
throw new UnsupportedAddressTypeError(
|
|
887
|
+
input.address,
|
|
888
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${input.address}. Signing it needs the public key behind the address, and no signer is bound to this PSBT to ask for it; pass a signer to createAndFundPsbt. ${suffix}`
|
|
889
|
+
);
|
|
890
|
+
}
|
|
891
|
+
if (typeof signer.getPublicKey !== "function") {
|
|
892
|
+
throw new UnsupportedAddressTypeError(
|
|
893
|
+
input.address,
|
|
894
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${input.address}. Signing it needs the public key behind the address, and the signer bound to this PSBT does not implement getPublicKey. ${suffix}`
|
|
895
|
+
);
|
|
896
|
+
}
|
|
897
|
+
const owner = import_bitcoinjs_lib4.address.fromOutputScript(script, this.btcNetworkConfig.lib);
|
|
898
|
+
if (!publicKeys.has(owner)) {
|
|
899
|
+
publicKeys.set(owner, await signer.getPublicKey(owner));
|
|
900
|
+
}
|
|
901
|
+
const redeemScript = deriveP2shP2wpkhRedeemScript(script, publicKeys.get(owner));
|
|
902
|
+
if (!redeemScript) {
|
|
903
|
+
throw new UnsupportedAddressTypeError(
|
|
904
|
+
owner,
|
|
905
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${owner}, and the signer returned no compressed public key whose P2SH-P2WPKH script matches it. Only P2SH-wrapped P2WPKH is supported. ${suffix}`
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
return redeemScript;
|
|
909
|
+
}
|
|
812
910
|
/**
|
|
813
911
|
* Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
|
|
814
912
|
* using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
|
|
@@ -826,7 +924,7 @@ var PowPegSDK = class {
|
|
|
826
924
|
const { inputs, change, totalFee } = await this.calculateFeeAndSelectedInputs(amount, funding.utxos, resolvedFeeRate, funding.skippedSatoshis);
|
|
827
925
|
const hexTransactions = await Promise.all(inputs.map((input) => this.bitcoinDataSource.getTxHex(input.txid)));
|
|
828
926
|
const parsedOutputs = hexTransactions.map((hex, index) => {
|
|
829
|
-
const tx =
|
|
927
|
+
const tx = import_bitcoinjs_lib4.Transaction.fromHex(hex);
|
|
830
928
|
(0, import_bridges_core_sdk4.assertTruthy)(
|
|
831
929
|
tx.getId() === inputs[index].txid,
|
|
832
930
|
`Fetched transaction for UTXO ${inputs[index].txid}:${inputs[index].vout} does not match the requested txid (got ${tx.getId()}).`
|
|
@@ -839,16 +937,7 @@ var PowPegSDK = class {
|
|
|
839
937
|
);
|
|
840
938
|
return output;
|
|
841
939
|
});
|
|
842
|
-
inputs.
|
|
843
|
-
const script = parsedOutputs[index].script;
|
|
844
|
-
if (!isSupportedFundingScript(script)) {
|
|
845
|
-
const detail = isP2shScript(script) ? `the P2SH address ${input.address}. Signing it needs a redeem script the SDK cannot derive, because BitcoinSigner exposes addresses but not the public keys behind them.` : `${input.address}, whose script type the SDK cannot build a signable input for.`;
|
|
846
|
-
throw new UnsupportedAddressTypeError(
|
|
847
|
-
input.address,
|
|
848
|
-
`UTXO ${input.txid}:${input.vout} is held by ${detail} Fund the peg-in from a legacy (P2PKH) or native segwit (P2WPKH) address, or pass selectedUtxos that exclude this one.`
|
|
849
|
-
);
|
|
850
|
-
}
|
|
851
|
-
});
|
|
940
|
+
const redeemScripts = await this.resolveRedeemScripts(inputs, parsedOutputs.map((output) => output.script), funding.publicKeys, this.psbtSigner.get(psbt));
|
|
852
941
|
const initialInputCount = psbt.txInputs.length;
|
|
853
942
|
const initialOutputCount = psbt.txOutputs.length;
|
|
854
943
|
const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
|
|
@@ -863,15 +952,17 @@ var PowPegSDK = class {
|
|
|
863
952
|
}
|
|
864
953
|
inputs.forEach((input, index) => {
|
|
865
954
|
const output = parsedOutputs[index];
|
|
955
|
+
const redeemScript = redeemScripts[index];
|
|
866
956
|
psbt.addInput({
|
|
867
957
|
hash: input.txid,
|
|
868
958
|
index: input.vout,
|
|
869
|
-
// A witness input is signed from witnessUtxo alone;
|
|
959
|
+
// A native witness input is signed from witnessUtxo alone; legacy and P2SH inputs also carry their parent transaction.
|
|
870
960
|
...isWitnessProgramScript(output.script) ? {} : { nonWitnessUtxo: Buffer.from(hexTransactions[index], "hex") },
|
|
871
961
|
witnessUtxo: {
|
|
872
962
|
script: output.script,
|
|
873
963
|
value: output.value
|
|
874
|
-
}
|
|
964
|
+
},
|
|
965
|
+
...redeemScript ? { redeemScript } : {}
|
|
875
966
|
});
|
|
876
967
|
});
|
|
877
968
|
const expectedInputCount = initialInputCount + inputs.length;
|
|
@@ -908,12 +999,12 @@ var PowPegSDK = class {
|
|
|
908
999
|
* @returns {Promise<UnsignedPegin>} The funded, unsigned PSBT along with its inputs, raw transactions, and total fee.
|
|
909
1000
|
*/
|
|
910
1001
|
async createAndFundPsbt(amount, recipientAddress, utxos, feeLevel = "fast", signer) {
|
|
911
|
-
const psbt = new
|
|
1002
|
+
const psbt = new import_bitcoinjs_lib4.Psbt({ network: this.btcNetworkConfig.lib });
|
|
912
1003
|
psbt.addOutput({
|
|
913
1004
|
address: recipientAddress,
|
|
914
1005
|
value: Number(amount)
|
|
915
1006
|
});
|
|
916
|
-
this.funding.set(psbt, { utxos: [...utxos], skippedSatoshis: 0n });
|
|
1007
|
+
this.funding.set(psbt, { utxos: [...utxos], skippedSatoshis: 0n, publicKeys: /* @__PURE__ */ new Map() });
|
|
917
1008
|
if (signer) {
|
|
918
1009
|
this.psbtSigner.set(psbt, signer);
|
|
919
1010
|
}
|
|
@@ -969,14 +1060,14 @@ var PowPegSDK = class {
|
|
|
969
1060
|
const network = this.btcNetworkConfig.lib;
|
|
970
1061
|
const derivations = [
|
|
971
1062
|
() => {
|
|
972
|
-
const segwit =
|
|
1063
|
+
const segwit = import_bitcoinjs_lib4.payments.p2sh({ redeem: import_bitcoinjs_lib4.payments.p2wsh({ redeem: { output: redeemScript }, network }), network });
|
|
973
1064
|
return segwit.output && federationAddress === segwit.address ? { outputScript: segwit.output, isSegwit: true } : void 0;
|
|
974
1065
|
},
|
|
975
1066
|
() => {
|
|
976
1067
|
if (redeemScript.length > this.maxScriptSigRedeemScriptSize) {
|
|
977
1068
|
return void 0;
|
|
978
1069
|
}
|
|
979
|
-
const legacy =
|
|
1070
|
+
const legacy = import_bitcoinjs_lib4.payments.p2sh({ redeem: { output: redeemScript }, network });
|
|
980
1071
|
return legacy.output && federationAddress === legacy.address ? { outputScript: legacy.output, isSegwit: false } : void 0;
|
|
981
1072
|
}
|
|
982
1073
|
];
|
|
@@ -997,7 +1088,7 @@ var PowPegSDK = class {
|
|
|
997
1088
|
throw new FederationAddressError(`Federation address ${federationAddress} is not derivable from the active powpeg redeem script.`);
|
|
998
1089
|
}
|
|
999
1090
|
buildPegoutSimulation(outputScript, inputs, outputs, scriptSig) {
|
|
1000
|
-
const transaction = new
|
|
1091
|
+
const transaction = new import_bitcoinjs_lib4.Transaction();
|
|
1001
1092
|
if (scriptSig) {
|
|
1002
1093
|
for (let i = 0; i < inputs; i++) {
|
|
1003
1094
|
transaction.addInput(Buffer.alloc(32), 0, void 0, scriptSig);
|
|
@@ -1132,10 +1223,10 @@ var PowPegSDK = class {
|
|
|
1132
1223
|
}
|
|
1133
1224
|
/**
|
|
1134
1225
|
* Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
|
|
1135
|
-
* and waits for it to be mined.
|
|
1226
|
+
* and waits for it to be mined on the SDK's RSK RPC node.
|
|
1136
1227
|
* @param {UnsignedPegout} tx - The peg-out transaction request, as returned by {@link createPegout}. Forwarded to the signer as given, so gas, nonce and fee fields set by the caller are honoured; only an absent chain id is filled in.
|
|
1137
1228
|
* @param {ethers.Signer} signer - Ethers signer used to send the transaction.
|
|
1138
|
-
* @returns The mined transaction receipt
|
|
1229
|
+
* @returns The mined transaction receipt.
|
|
1139
1230
|
* @throws {WrongNetworkError} If the transaction's chain id, or the signer's chain, doesn't match the network the SDK was configured for.
|
|
1140
1231
|
* @throws {TransactionRevertedError} If the transaction was mined but reverted.
|
|
1141
1232
|
* @throws {PegoutRejectedError} If the transaction was mined but the Bridge rejected and refunded the release request.
|
|
@@ -1159,7 +1250,7 @@ var PowPegSDK = class {
|
|
|
1159
1250
|
throw new WrongNetworkError(`Signer is on chain ${signerChainId}, but the SDK is configured for ${this.network} (chain ${expectedChainId}).`);
|
|
1160
1251
|
}
|
|
1161
1252
|
const { hash } = await signer.sendTransaction(request);
|
|
1162
|
-
const receipt = await
|
|
1253
|
+
const receipt = await this.rskProvider.waitForTransaction(hash);
|
|
1163
1254
|
if (receipt) {
|
|
1164
1255
|
if (receipt.status === 0) {
|
|
1165
1256
|
throw new TransactionRevertedError(hash, receipt, `The peg-out transaction ${hash} was mined but reverted; no BTC release was requested.`);
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/sdk/powpeg.ts
|
|
2
|
-
import { address, payments, Psbt as Psbt2, Transaction } from "bitcoinjs-lib";
|
|
2
|
+
import { address, payments as payments2, Psbt as Psbt2, Transaction } from "bitcoinjs-lib";
|
|
3
3
|
|
|
4
4
|
// src/types.ts
|
|
5
5
|
import "bitcoinjs-lib";
|
|
@@ -57,6 +57,7 @@ var Network = {
|
|
|
57
57
|
};
|
|
58
58
|
|
|
59
59
|
// src/utils.ts
|
|
60
|
+
import { payments } from "bitcoinjs-lib";
|
|
60
61
|
function remove0x(hex) {
|
|
61
62
|
return hex.startsWith("0x") ? hex.slice(2) : hex;
|
|
62
63
|
}
|
|
@@ -103,9 +104,24 @@ function isP2pkhScript(script) {
|
|
|
103
104
|
function isP2wpkhScript(script) {
|
|
104
105
|
return script.length === 22 && script[0] === 0 && script[1] === 20;
|
|
105
106
|
}
|
|
106
|
-
function
|
|
107
|
+
function isFullySupportedFundingScript(script) {
|
|
107
108
|
return isP2pkhScript(script) || isP2wpkhScript(script);
|
|
108
109
|
}
|
|
110
|
+
function deriveP2shP2wpkhRedeemScript(script, publicKeyHex) {
|
|
111
|
+
if (!isP2shScript(script) || typeof publicKeyHex !== "string") {
|
|
112
|
+
return void 0;
|
|
113
|
+
}
|
|
114
|
+
const publicKey = remove0x(publicKeyHex.trim());
|
|
115
|
+
if (!/^0[23][0-9a-fA-F]{64}$/.test(publicKey)) {
|
|
116
|
+
return void 0;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const redeem = payments.p2wpkh({ pubkey: Buffer.from(publicKey, "hex") });
|
|
120
|
+
return payments.p2sh({ redeem }).output?.equals(script) ? redeem.output : void 0;
|
|
121
|
+
} catch {
|
|
122
|
+
return void 0;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
109
125
|
|
|
110
126
|
// src/bridge.ts
|
|
111
127
|
import { bridge } from "@rsksmart/rsk-precompiled-abis";
|
|
@@ -573,12 +589,27 @@ var PowPegSDK = class {
|
|
|
573
589
|
});
|
|
574
590
|
return { used, unused };
|
|
575
591
|
}
|
|
576
|
-
|
|
592
|
+
/**
|
|
593
|
+
* Whether the SDK can build a signable input for a UTXO held by `btcAddress`. A P2SH address counts only
|
|
594
|
+
* when `signer` returns a public key whose P2SH-P2WPKH script matches it; the key is cached in `publicKeys`.
|
|
595
|
+
*/
|
|
596
|
+
async isSpendableAddress(btcAddress, signer, publicKeys) {
|
|
597
|
+
let script;
|
|
577
598
|
try {
|
|
578
|
-
|
|
599
|
+
script = address.toOutputScript(btcAddress, this.btcNetworkConfig.lib);
|
|
579
600
|
} catch {
|
|
580
601
|
return false;
|
|
581
602
|
}
|
|
603
|
+
if (isFullySupportedFundingScript(script)) {
|
|
604
|
+
return true;
|
|
605
|
+
}
|
|
606
|
+
if (!isP2shScript(script)) {
|
|
607
|
+
return false;
|
|
608
|
+
}
|
|
609
|
+
if (!publicKeys.has(btcAddress)) {
|
|
610
|
+
publicKeys.set(btcAddress, await signer.getPublicKey?.(btcAddress));
|
|
611
|
+
}
|
|
612
|
+
return deriveP2shP2wpkhRedeemScript(script, publicKeys.get(btcAddress)) !== void 0;
|
|
582
613
|
}
|
|
583
614
|
groupAddressesByBalance(addresses) {
|
|
584
615
|
const withBalance = [];
|
|
@@ -674,7 +705,7 @@ var PowPegSDK = class {
|
|
|
674
705
|
const addresses = await this.getAddressesGroupedByUsage(signer);
|
|
675
706
|
const psbt = new Psbt2({ network: this.btcNetworkConfig.lib });
|
|
676
707
|
const refundAddress = addresses.nonChange.unused[0]?.address;
|
|
677
|
-
const { output: script } =
|
|
708
|
+
const { output: script } = payments2.embed({ data: [this.getRskOutput(recipientAddress, refundAddress)] });
|
|
678
709
|
if (script) {
|
|
679
710
|
psbt.addOutput({
|
|
680
711
|
script,
|
|
@@ -688,6 +719,7 @@ var PowPegSDK = class {
|
|
|
688
719
|
});
|
|
689
720
|
let utxos;
|
|
690
721
|
let skippedSatoshis = 0n;
|
|
722
|
+
const publicKeys = /* @__PURE__ */ new Map();
|
|
691
723
|
if (selectedUtxos) {
|
|
692
724
|
utxos = [...selectedUtxos];
|
|
693
725
|
} else {
|
|
@@ -696,12 +728,25 @@ var PowPegSDK = class {
|
|
|
696
728
|
throw new SigningError("The signer derived no addresses, so there is nothing to discover UTXOs from. Pass selectedUtxos to fund from a set you resolved yourself.");
|
|
697
729
|
}
|
|
698
730
|
const { withBalance } = this.groupAddressesByBalance(usedAddresses);
|
|
699
|
-
const spendable =
|
|
700
|
-
|
|
731
|
+
const spendable = [];
|
|
732
|
+
for (const address2 of withBalance) {
|
|
733
|
+
if (await this.isSpendableAddress(address2.address, signer, publicKeys).catch(() => false)) {
|
|
734
|
+
spendable.push(address2);
|
|
735
|
+
} else {
|
|
736
|
+
skippedSatoshis += BigInt(address2.balance);
|
|
737
|
+
}
|
|
738
|
+
}
|
|
701
739
|
utxos = await this.getUtxos(spendable);
|
|
702
740
|
}
|
|
703
|
-
|
|
704
|
-
|
|
741
|
+
let changeAddress;
|
|
742
|
+
for (const address2 of addresses.change.unused) {
|
|
743
|
+
if (await this.isSpendableAddress(address2.address, signer, publicKeys).catch(() => false)) {
|
|
744
|
+
changeAddress = address2;
|
|
745
|
+
break;
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
changeAddress ??= addresses.change.unused[0];
|
|
749
|
+
this.funding.set(psbt, { utxos, changeAddress: changeAddress?.address, skippedSatoshis, publicKeys });
|
|
705
750
|
this.psbtSigner.set(psbt, signer);
|
|
706
751
|
return psbt;
|
|
707
752
|
}
|
|
@@ -756,6 +801,59 @@ var PowPegSDK = class {
|
|
|
756
801
|
}
|
|
757
802
|
return { inputs, change: Math.abs(rest), totalFee };
|
|
758
803
|
}
|
|
804
|
+
/**
|
|
805
|
+
* Redeem script for each funding input, resolved in order; see {@link PowPegSDK.resolveRedeemScript}.
|
|
806
|
+
* @throws {UnsupportedAddressTypeError} If an input's script is neither, or its redeem script cannot be resolved.
|
|
807
|
+
*/
|
|
808
|
+
async resolveRedeemScripts(inputs, scripts, publicKeys, signer) {
|
|
809
|
+
const redeemScripts = [];
|
|
810
|
+
for (const [index, input] of inputs.entries()) {
|
|
811
|
+
redeemScripts.push(await this.resolveRedeemScript(input, scripts[index], publicKeys, signer));
|
|
812
|
+
}
|
|
813
|
+
return redeemScripts;
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Redeem script of one funding input: undefined for P2PKH and P2WPKH, the P2SH-P2WPKH redeem script
|
|
817
|
+
* built from the public key `signer` reports for a P2SH input. The address is asked once, and not at all
|
|
818
|
+
* when `publicKeys` already holds its key.
|
|
819
|
+
* @throws {UnsupportedAddressTypeError} If the input's script is neither, or its redeem script cannot be resolved.
|
|
820
|
+
*/
|
|
821
|
+
async resolveRedeemScript(input, script, publicKeys, signer) {
|
|
822
|
+
if (isFullySupportedFundingScript(script)) {
|
|
823
|
+
return void 0;
|
|
824
|
+
}
|
|
825
|
+
const suffix = "Fund the peg-in from a legacy (P2PKH), nested segwit (P2SH-P2WPKH) or native segwit (P2WPKH) address, or pass selectedUtxos that exclude this one.";
|
|
826
|
+
if (!isP2shScript(script)) {
|
|
827
|
+
throw new UnsupportedAddressTypeError(
|
|
828
|
+
input.address,
|
|
829
|
+
`UTXO ${input.txid}:${input.vout} is held by ${input.address}, whose script type the SDK cannot build a signable input for. ${suffix}`
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
if (!signer) {
|
|
833
|
+
throw new UnsupportedAddressTypeError(
|
|
834
|
+
input.address,
|
|
835
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${input.address}. Signing it needs the public key behind the address, and no signer is bound to this PSBT to ask for it; pass a signer to createAndFundPsbt. ${suffix}`
|
|
836
|
+
);
|
|
837
|
+
}
|
|
838
|
+
if (typeof signer.getPublicKey !== "function") {
|
|
839
|
+
throw new UnsupportedAddressTypeError(
|
|
840
|
+
input.address,
|
|
841
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${input.address}. Signing it needs the public key behind the address, and the signer bound to this PSBT does not implement getPublicKey. ${suffix}`
|
|
842
|
+
);
|
|
843
|
+
}
|
|
844
|
+
const owner = address.fromOutputScript(script, this.btcNetworkConfig.lib);
|
|
845
|
+
if (!publicKeys.has(owner)) {
|
|
846
|
+
publicKeys.set(owner, await signer.getPublicKey(owner));
|
|
847
|
+
}
|
|
848
|
+
const redeemScript = deriveP2shP2wpkhRedeemScript(script, publicKeys.get(owner));
|
|
849
|
+
if (!redeemScript) {
|
|
850
|
+
throw new UnsupportedAddressTypeError(
|
|
851
|
+
owner,
|
|
852
|
+
`UTXO ${input.txid}:${input.vout} is held by the P2SH address ${owner}, and the signer returned no compressed public key whose P2SH-P2WPKH script matches it. Only P2SH-wrapped P2WPKH is supported. ${suffix}`
|
|
853
|
+
);
|
|
854
|
+
}
|
|
855
|
+
return redeemScript;
|
|
856
|
+
}
|
|
759
857
|
/**
|
|
760
858
|
* Adds funding inputs (and a change output, if above the dust threshold) to an existing peg-in PSBT,
|
|
761
859
|
* using the UTXOs previously selected by {@link createPegin} or {@link createAndFundPsbt}.
|
|
@@ -786,16 +884,7 @@ var PowPegSDK = class {
|
|
|
786
884
|
);
|
|
787
885
|
return output;
|
|
788
886
|
});
|
|
789
|
-
inputs.
|
|
790
|
-
const script = parsedOutputs[index].script;
|
|
791
|
-
if (!isSupportedFundingScript(script)) {
|
|
792
|
-
const detail = isP2shScript(script) ? `the P2SH address ${input.address}. Signing it needs a redeem script the SDK cannot derive, because BitcoinSigner exposes addresses but not the public keys behind them.` : `${input.address}, whose script type the SDK cannot build a signable input for.`;
|
|
793
|
-
throw new UnsupportedAddressTypeError(
|
|
794
|
-
input.address,
|
|
795
|
-
`UTXO ${input.txid}:${input.vout} is held by ${detail} Fund the peg-in from a legacy (P2PKH) or native segwit (P2WPKH) address, or pass selectedUtxos that exclude this one.`
|
|
796
|
-
);
|
|
797
|
-
}
|
|
798
|
-
});
|
|
887
|
+
const redeemScripts = await this.resolveRedeemScripts(inputs, parsedOutputs.map((output) => output.script), funding.publicKeys, this.psbtSigner.get(psbt));
|
|
799
888
|
const initialInputCount = psbt.txInputs.length;
|
|
800
889
|
const initialOutputCount = psbt.txOutputs.length;
|
|
801
890
|
const addChange = change > Math.min(this.burnDustValue, this.burnDustMaxValue);
|
|
@@ -810,15 +899,17 @@ var PowPegSDK = class {
|
|
|
810
899
|
}
|
|
811
900
|
inputs.forEach((input, index) => {
|
|
812
901
|
const output = parsedOutputs[index];
|
|
902
|
+
const redeemScript = redeemScripts[index];
|
|
813
903
|
psbt.addInput({
|
|
814
904
|
hash: input.txid,
|
|
815
905
|
index: input.vout,
|
|
816
|
-
// A witness input is signed from witnessUtxo alone;
|
|
906
|
+
// A native witness input is signed from witnessUtxo alone; legacy and P2SH inputs also carry their parent transaction.
|
|
817
907
|
...isWitnessProgramScript(output.script) ? {} : { nonWitnessUtxo: Buffer.from(hexTransactions[index], "hex") },
|
|
818
908
|
witnessUtxo: {
|
|
819
909
|
script: output.script,
|
|
820
910
|
value: output.value
|
|
821
|
-
}
|
|
911
|
+
},
|
|
912
|
+
...redeemScript ? { redeemScript } : {}
|
|
822
913
|
});
|
|
823
914
|
});
|
|
824
915
|
const expectedInputCount = initialInputCount + inputs.length;
|
|
@@ -860,7 +951,7 @@ var PowPegSDK = class {
|
|
|
860
951
|
address: recipientAddress,
|
|
861
952
|
value: Number(amount)
|
|
862
953
|
});
|
|
863
|
-
this.funding.set(psbt, { utxos: [...utxos], skippedSatoshis: 0n });
|
|
954
|
+
this.funding.set(psbt, { utxos: [...utxos], skippedSatoshis: 0n, publicKeys: /* @__PURE__ */ new Map() });
|
|
864
955
|
if (signer) {
|
|
865
956
|
this.psbtSigner.set(psbt, signer);
|
|
866
957
|
}
|
|
@@ -916,14 +1007,14 @@ var PowPegSDK = class {
|
|
|
916
1007
|
const network = this.btcNetworkConfig.lib;
|
|
917
1008
|
const derivations = [
|
|
918
1009
|
() => {
|
|
919
|
-
const segwit =
|
|
1010
|
+
const segwit = payments2.p2sh({ redeem: payments2.p2wsh({ redeem: { output: redeemScript }, network }), network });
|
|
920
1011
|
return segwit.output && federationAddress === segwit.address ? { outputScript: segwit.output, isSegwit: true } : void 0;
|
|
921
1012
|
},
|
|
922
1013
|
() => {
|
|
923
1014
|
if (redeemScript.length > this.maxScriptSigRedeemScriptSize) {
|
|
924
1015
|
return void 0;
|
|
925
1016
|
}
|
|
926
|
-
const legacy =
|
|
1017
|
+
const legacy = payments2.p2sh({ redeem: { output: redeemScript }, network });
|
|
927
1018
|
return legacy.output && federationAddress === legacy.address ? { outputScript: legacy.output, isSegwit: false } : void 0;
|
|
928
1019
|
}
|
|
929
1020
|
];
|
|
@@ -1079,10 +1170,10 @@ var PowPegSDK = class {
|
|
|
1079
1170
|
}
|
|
1080
1171
|
/**
|
|
1081
1172
|
* Sends a peg-out transaction (as returned by {@link createPegout}) using the given ethers signer
|
|
1082
|
-
* and waits for it to be mined.
|
|
1173
|
+
* and waits for it to be mined on the SDK's RSK RPC node.
|
|
1083
1174
|
* @param {UnsignedPegout} tx - The peg-out transaction request, as returned by {@link createPegout}. Forwarded to the signer as given, so gas, nonce and fee fields set by the caller are honoured; only an absent chain id is filled in.
|
|
1084
1175
|
* @param {ethers.Signer} signer - Ethers signer used to send the transaction.
|
|
1085
|
-
* @returns The mined transaction receipt
|
|
1176
|
+
* @returns The mined transaction receipt.
|
|
1086
1177
|
* @throws {WrongNetworkError} If the transaction's chain id, or the signer's chain, doesn't match the network the SDK was configured for.
|
|
1087
1178
|
* @throws {TransactionRevertedError} If the transaction was mined but reverted.
|
|
1088
1179
|
* @throws {PegoutRejectedError} If the transaction was mined but the Bridge rejected and refunded the release request.
|
|
@@ -1106,7 +1197,7 @@ var PowPegSDK = class {
|
|
|
1106
1197
|
throw new WrongNetworkError(`Signer is on chain ${signerChainId}, but the SDK is configured for ${this.network} (chain ${expectedChainId}).`);
|
|
1107
1198
|
}
|
|
1108
1199
|
const { hash } = await signer.sendTransaction(request);
|
|
1109
|
-
const receipt = await
|
|
1200
|
+
const receipt = await this.rskProvider.waitForTransaction(hash);
|
|
1110
1201
|
if (receipt) {
|
|
1111
1202
|
if (receipt.status === 0) {
|
|
1112
1203
|
throw new TransactionRevertedError(hash, receipt, `The peg-out transaction ${hash} was mined but reverted; no BTC release was requested.`);
|
package/docs/api.md
CHANGED
|
@@ -53,6 +53,6 @@ The package ships no `BitcoinSigner` implementations — see [`bitcoin-signers.m
|
|
|
53
53
|
| `PegoutRejectedError` | class | Thrown when the peg-out transaction was mined but the Bridge rejected the release request; carries `reason` (1 below minimum, 2 caller is a contract, 3 fee above value — 1 and 3 are refunded, 2 is not), `txHash` and `amount`. |
|
|
54
54
|
| `UnsupportedSenderError` | class | Thrown when the account asked to send a peg-out is a contract account, which the Bridge refuses to release BTC for. |
|
|
55
55
|
| `TransactionRevertedError` | class | Thrown when the peg-out transaction was mined but reverted, so no release was requested; carries `txHash`. |
|
|
56
|
-
| `UnsupportedAddressTypeError` | class | Thrown when a funding UTXO
|
|
56
|
+
| `UnsupportedAddressTypeError` | class | Thrown when a funding UTXO's script cannot be built into a signable input: anything but P2PKH, P2WPKH, or a P2SH-P2WPKH whose public key the signer returns from `getPublicKey`; carries `address`. |
|
|
57
57
|
| `WrongNetworkError` | class | Thrown when the signer's chain doesn't match the network the SDK was configured for. |
|
|
58
58
|
| `InvalidFeeRateError` | class | Thrown when a fee rate from the configured `BitcoinDataSource` is missing, non-numeric, non-positive, exceeds the configured bound, or produces a fee disproportionate to the amount being sent. |
|
package/docs/bitcoin-signers.md
CHANGED
|
@@ -13,11 +13,13 @@ export interface BitcoinSigner {
|
|
|
13
13
|
getNonChangeAddresses(bundleSize: number): Promise<string[]>
|
|
14
14
|
getChangeAddresses(bundleSize: number): Promise<string[]>
|
|
15
15
|
signTransaction(psbt: Psbt, inputs?: Utxo[], transactions?: string[]): Promise<string>
|
|
16
|
+
getPublicKey?(address: string): Promise<string | undefined>
|
|
16
17
|
}
|
|
17
18
|
```
|
|
18
19
|
|
|
19
20
|
- `getNonChangeAddresses` / `getChangeAddresses` — derive `bundleSize` receive/change addresses the signer controls. `PowPegSDK` uses these to find funded addresses and an unused refund/change address.
|
|
20
21
|
- `signTransaction` — signs a peg-in PSBT and returns the serialized signed transaction. `inputs`/`transactions` carry the UTXOs being spent and their raw hex, for signers that need to verify each input against its funding transaction. **Throw on failure rather than returning an empty string** — a user declining on a device and a backend outage are different events, and an empty return is rejected with `SigningError` rather than broadcast.
|
|
22
|
+
- `getPublicKey` (optional) — returns the compressed public key, as 66 hex characters, behind one of the signer's P2SH-P2WPKH (nested segwit) addresses, or `undefined` if it doesn't know it. Implement it to let peg-ins be funded from nested segwit addresses; see below.
|
|
21
23
|
|
|
22
24
|
## Adding a signer
|
|
23
25
|
|
|
@@ -34,35 +36,59 @@ be funded from UTXOs the address holds:
|
|
|
34
36
|
| Address type | BIP | Purpose (`m/<purpose>'`) | Address format | Funding a peg-in |
|
|
35
37
|
|---|---|---|---|---|
|
|
36
38
|
| `'LEGACY'` | BIP 44 | `44'` | P2PKH (`1…` / `m…`, `n…`) | supported |
|
|
37
|
-
| `'SEGWIT'` | BIP 49 | `49'` | P2SH-wrapped P2WPKH (`3…` / `2…`) |
|
|
39
|
+
| `'SEGWIT'` | BIP 49 | `49'` | P2SH-wrapped P2WPKH (`3…` / `2…`) | supported if the signer implements `getPublicKey` |
|
|
38
40
|
| `'NATIVE SEGWIT'` | BIP 84 | `84'` | P2WPKH (`bc1…` / `tb1…`) | supported |
|
|
39
41
|
|
|
40
|
-
Funding is allowed for P2PKH and P2WPKH scripts and nothing else, decided from the UTXO's
|
|
41
|
-
`scriptPubKey` rather than from the shape of the address. That distinction matters for bech32: a P2WSH
|
|
42
|
+
Funding is allowed for P2PKH, P2WPKH and P2SH-P2WPKH scripts and nothing else, decided from the UTXO's
|
|
43
|
+
own `scriptPubKey` rather than from the shape of the address. That distinction matters for bech32: a P2WSH
|
|
42
44
|
and a taproot address look like a P2WPKH one, and only the script tells them apart.
|
|
43
45
|
|
|
46
|
+
### Nested segwit (P2SH-P2WPKH)
|
|
47
|
+
|
|
44
48
|
A P2SH input can only be signed with the redeem script behind the address, which is derived from the
|
|
45
|
-
public key. `
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
49
|
+
public key. For each P2SH UTXO, `fundPegin` asks the signer bound to the PSBT for that key with
|
|
50
|
+
`getPublicKey(address)` — `address` is the one the UTXO's script encodes — builds the P2WPKH redeem
|
|
51
|
+
script from it, and adds the input only if hashing that script reproduces the P2SH hash being spent. The
|
|
52
|
+
input then carries `redeemScript` and `witnessUtxo`, plus the parent transaction in `nonWitnessUtxo`, so a
|
|
53
|
+
signer built on bitcoinjs-lib can sign and finalize it without adding anything.
|
|
54
|
+
|
|
55
|
+
`fundPegin` throws `UnsupportedAddressTypeError` naming the address the UTXO's script encodes when the
|
|
56
|
+
signer doesn't implement `getPublicKey`, returns `undefined`, returns anything but a compressed public key,
|
|
57
|
+
or returns a key whose P2SH-P2WPKH script doesn't match — which is also what any other P2SH script, such as
|
|
58
|
+
a multisig or a P2SH-P2WSH, gets. Each address is asked once per peg-in, in order: a key `createPegin`
|
|
59
|
+
already resolved during discovery is reused by `fundPegin`. An error thrown by `getPublicKey` propagates
|
|
60
|
+
unchanged from `fundPegin`. While `createPegin` discovers UTXOs or chooses the change address, it only rules
|
|
61
|
+
that address out, and a discovered address it rules out has its balance reported as skipped. A PSBT from `createAndFundPsbt` without a `signer` has no signer to ask, so its P2SH
|
|
62
|
+
UTXOs are refused with an error that says to pass one.
|
|
63
|
+
|
|
64
|
+
### Unsupported scripts
|
|
50
65
|
|
|
51
66
|
A UTXO held by any other script — P2WSH, taproot, a bare multisig — is refused the same way. Each needs a
|
|
52
67
|
redeem script, a witness script or a key that `BitcoinSigner` does not expose, so the SDK cannot build a
|
|
53
|
-
complete PSBT input for it.
|
|
68
|
+
complete PSBT input for it. Fund from a legacy, nested segwit or native segwit address, or pass
|
|
69
|
+
`selectedUtxos` that exclude the UTXO. Every check runs before the PSBT is touched, so a refused UTXO
|
|
70
|
+
leaves it exactly as `createPegin` returned it — no inputs added, no change output, and still fundable.
|
|
54
71
|
|
|
55
72
|
When `createPegin` discovers UTXOs itself, it looks only at the signer's legacy and native segwit
|
|
56
|
-
addresses,
|
|
73
|
+
addresses, plus the nested segwit ones whose key `getPublicKey` returns and matches, so a wallet holding
|
|
74
|
+
several types funds a peg-in from the part the SDK can sign. If what remains
|
|
57
75
|
does not cover the amount, `NotEnoughFundsError` says how much was left out. The same preference applies
|
|
58
76
|
to the change address: change goes to the first unused change address the SDK could fund from later,
|
|
59
77
|
falling back to the first unused one, and then to the first funding input's address. `UnsupportedAddressTypeError`
|
|
60
78
|
is therefore reserved for a UTXO the caller named in `selectedUtxos`.
|
|
61
79
|
|
|
62
|
-
Every funding input carries `witnessUtxo`. A legacy input also carries
|
|
63
|
-
|
|
64
|
-
carry it. So a signer built on bitcoinjs-lib can sign
|
|
65
|
-
itself.
|
|
80
|
+
Every funding input carries `witnessUtxo`. A legacy or nested segwit input also carries
|
|
81
|
+
`nonWitnessUtxo`, the full parent transaction; a native segwit input is signed from `witnessUtxo` alone and
|
|
82
|
+
does not carry it. So a signer built on bitcoinjs-lib can sign any supported type without fetching
|
|
83
|
+
anything itself.
|
|
84
|
+
|
|
85
|
+
### Refund address
|
|
86
|
+
|
|
87
|
+
`createPegin` writes the first unused address from `getNonChangeAddresses` into the peg-in's `OP_RETURN`
|
|
88
|
+
as its refund address, but only when it is P2PKH or P2SH: those are the only types the Bridge's peg-in
|
|
89
|
+
protocol can encode. When that address is native segwit or taproot, or every address is used, the
|
|
90
|
+
`OP_RETURN` carries no refund address, and the peg-in is still valid. Without one, the Bridge falls back to
|
|
91
|
+
the sender of the first input when it is P2PKH or P2SH-P2WPKH.
|
|
66
92
|
|
|
67
93
|
Coin type is `0'` on `MAIN` and `1'` on `TEST`, so a full account path reads
|
|
68
94
|
`m/84'/1'/0'/0/<index>` for a native-segwit receive address on testnet, and `.../1/<index>` for a change
|
package/docs/setup.md
CHANGED
|
@@ -116,15 +116,17 @@ The bare strings `'MAIN'` and `'TEST'` are still accepted, so either style works
|
|
|
116
116
|
|
|
117
117
|
- `TrezorSigner` and `LedgerSigner` are no longer exported; supply your own `BitcoinSigner` (see
|
|
118
118
|
[`bitcoin-signers.md`](./bitcoin-signers.md)).
|
|
119
|
-
- A peg-in can only be funded from P2PKH and P2WPKH UTXOs
|
|
120
|
-
|
|
121
|
-
|
|
119
|
+
- A peg-in can only be funded from P2PKH, P2WPKH and P2SH-P2WPKH UTXOs, the last only when the signer
|
|
120
|
+
implements `getPublicKey`; anything else — another P2SH (`2…`/`3…`), P2WSH, taproot, a bare multisig —
|
|
121
|
+
makes `fundPegin` throw `UnsupportedAddressTypeError`. In 1.x such a UTXO was accepted and failed later
|
|
122
|
+
inside the signer, except a bare multisig, which did sign.
|
|
123
|
+
Legacy and nested segwit funding inputs now also carry `nonWitnessUtxo`, so they sign without the
|
|
124
|
+
signer fetching the parent transaction itself; nested segwit inputs carry their `redeemScript` too.
|
|
125
|
+
Native segwit inputs do not carry `nonWitnessUtxo`, so the PSBT does not grow by the size of each
|
|
126
|
+
parent transaction.
|
|
122
127
|
- `maxBundleSize`, `burnDustValue`, `maxFeeRateSatPerByte` and `maxFeeToAmountRatio` are validated at
|
|
123
128
|
construction, and `signAndBroadcastPegout` refuses a request addressed anywhere but the bridge, or one
|
|
124
129
|
carrying calldata.
|
|
125
|
-
Legacy funding inputs now also carry `nonWitnessUtxo`, so they sign without the signer fetching the
|
|
126
|
-
parent transaction itself. Witness inputs do not carry it, so the PSBT does not grow by the size of
|
|
127
|
-
each parent transaction.
|
|
128
130
|
- The constructor takes a single options object instead of nine positional parameters:
|
|
129
131
|
`new PowPegSDK(signer, dataSource, 'TEST', undefined, apiUrl)` becomes
|
|
130
132
|
`new PowPegSDK({ network: Network.TEST, bitcoinSigner: signer, bitcoinDataSource: dataSource, apiUrl })`.
|
package/package.json
CHANGED