@leather.io/bitcoin 0.8.6 → 0.9.1
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/.turbo/turbo-build.log +6 -6
- package/CHANGELOG.md +25 -0
- package/dist/index.d.ts +51 -7
- package/dist/index.js +20 -12
- package/dist/index.js.map +1 -1
- package/package.json +9 -9
- package/src/bitcoin.utils.ts +5 -1
- package/src/p2tr-address-gen.ts +9 -5
- package/src/p2wpkh-address-gen.ts +9 -5
- package/src/p2wsh-p2sh-address-gen.spec.ts +2 -2
- package/src/p2wsh-p2sh-address-gen.ts +2 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
|
|
2
|
-
> @leather.io/bitcoin@0.
|
|
2
|
+
> @leather.io/bitcoin@0.9.1 build /home/runner/work/mono/mono/packages/bitcoin
|
|
3
3
|
> tsup
|
|
4
4
|
|
|
5
5
|
[34mCLI[39m Building entry: src/index.ts
|
|
@@ -9,9 +9,9 @@
|
|
|
9
9
|
[34mCLI[39m Target: es2022
|
|
10
10
|
[34mCLI[39m Cleaning output folder
|
|
11
11
|
[34mESM[39m Build start
|
|
12
|
-
[32mESM[39m [1mdist/index.js [22m[
|
|
13
|
-
[32mESM[39m [1mdist/index.js.map [22m[
|
|
14
|
-
[32mESM[39m ⚡️ Build success in
|
|
12
|
+
[32mESM[39m [1mdist/index.js [22m[32m18.36 KB[39m
|
|
13
|
+
[32mESM[39m [1mdist/index.js.map [22m[32m34.01 KB[39m
|
|
14
|
+
[32mESM[39m ⚡️ Build success in 31ms
|
|
15
15
|
[34mDTS[39m Build start
|
|
16
|
-
[32mDTS[39m ⚡️ Build success in
|
|
17
|
-
[32mDTS[39m [1mdist/index.d.ts [22m[
|
|
16
|
+
[32mDTS[39m ⚡️ Build success in 2081ms
|
|
17
|
+
[32mDTS[39m [1mdist/index.d.ts [22m[32m11.13 KB[39m
|
package/CHANGELOG.md
CHANGED
|
@@ -119,6 +119,31 @@
|
|
|
119
119
|
* dependencies
|
|
120
120
|
* @leather.io/utils bumped to 0.10.1
|
|
121
121
|
|
|
122
|
+
### Dependencies
|
|
123
|
+
|
|
124
|
+
* The following workspace dependencies were updated
|
|
125
|
+
* dependencies
|
|
126
|
+
* @leather.io/crypto bumped to 1.0.4
|
|
127
|
+
|
|
128
|
+
## [0.9.0](https://github.com/leather-io/mono/compare/@leather.io/bitcoin-v0.8.6...@leather.io/bitcoin-v0.9.0) (2024-07-18)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
### Features
|
|
132
|
+
|
|
133
|
+
* **mobile:** add base key generation ([2e96346](https://github.com/leather-io/mono/commit/2e9634644b459b3917ef353579ca0e476b87096d))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
### Dependencies
|
|
137
|
+
|
|
138
|
+
* The following workspace dependencies were updated
|
|
139
|
+
* dependencies
|
|
140
|
+
* @leather.io/constants bumped to 0.8.2
|
|
141
|
+
* @leather.io/models bumped to 0.10.2
|
|
142
|
+
* @leather.io/utils bumped to 0.10.2
|
|
143
|
+
* devDependencies
|
|
144
|
+
* @leather.io/rpc bumped to 2.0.2
|
|
145
|
+
* @leather.io/tsconfig-config bumped to 0.5.1
|
|
146
|
+
|
|
122
147
|
## [0.8.2](https://github.com/leather-io/mono/compare/@leather.io/bitcoin-v0.8.1...@leather.io/bitcoin-v0.8.2) (2024-07-02)
|
|
123
148
|
|
|
124
149
|
|
package/dist/index.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { SigHash } from '@scure/btc-signer/transaction';
|
|
|
7
7
|
import { SignatureHash, PaymentTypes } from '@leather.io/rpc';
|
|
8
8
|
import { TransactionInput, TransactionOutput } from '@scure/btc-signer/psbt';
|
|
9
9
|
import * as _scure_btc_signer_payment from '@scure/btc-signer/payment';
|
|
10
|
-
import {
|
|
10
|
+
import { deriveBip39SeedFromMnemonic, deriveRootBip32Keychain } from '@leather.io/crypto';
|
|
11
11
|
|
|
12
12
|
declare function ecPairFromPrivateKey(key: Uint8Array): ecpair.ECPairInterface;
|
|
13
13
|
declare function hashBip322Message(message: Uint8Array | string): Uint8Array;
|
|
@@ -17,6 +17,10 @@ declare const bip322TransactionToSignValues: {
|
|
|
17
17
|
sequence: number;
|
|
18
18
|
};
|
|
19
19
|
declare function isSupportedMessageSigningPaymentType(paymentType: string): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Encode witness data for a BIP322 message
|
|
22
|
+
* TODO: Refactor to remove `Buffer` use
|
|
23
|
+
*/
|
|
20
24
|
declare function encodeMessageWitnessData(witnessArray: Buffer[]): Buffer;
|
|
21
25
|
declare function tweakSigner(signer: bitcoin.Signer, opts?: any): bitcoin.Signer;
|
|
22
26
|
|
|
@@ -68,8 +72,19 @@ interface BitcoinAccount {
|
|
|
68
72
|
network: BitcoinNetworkModes;
|
|
69
73
|
}
|
|
70
74
|
declare function initBitcoinAccount(derivationPath: string, policy: string): BitcoinAccount;
|
|
75
|
+
/**
|
|
76
|
+
* Represents a map of `BitcoinNetworkModes` to `NetworkModes`. While Bitcoin
|
|
77
|
+
* has a number of networks, its often only necessary to consider the higher
|
|
78
|
+
* level concept of mainnet and testnet
|
|
79
|
+
*/
|
|
71
80
|
declare const bitcoinNetworkToCoreNetworkMap: Record<BitcoinNetworkModes, NetworkModes>;
|
|
72
81
|
declare function bitcoinNetworkModeToCoreNetworkMode(mode: BitcoinNetworkModes): "mainnet" | "testnet";
|
|
82
|
+
/**
|
|
83
|
+
* Map representing the "Coin Type" section of a derivation path.
|
|
84
|
+
* Consider example below, Coin type is one, thus testnet
|
|
85
|
+
* @example
|
|
86
|
+
* `m/86'/1'/0'/0/0`
|
|
87
|
+
*/
|
|
73
88
|
declare const coinTypeMap: Record<NetworkModes, 0 | 1>;
|
|
74
89
|
declare function getBitcoinCoinTypeIndexByNetwork(network: BitcoinNetworkModes): 0 | 1;
|
|
75
90
|
declare function deriveAddressIndexKeychainFromAccount(keychain: HDKey): (index: number) => HDKey;
|
|
@@ -79,6 +94,9 @@ declare function ecdsaPublicKeyToSchnorr(pubKey: Uint8Array): Uint8Array;
|
|
|
79
94
|
declare const toXOnly: (pubKey: Buffer) => Buffer;
|
|
80
95
|
declare function decodeBitcoinTx(tx: string): ReturnType<typeof btc.RawTx.decode>;
|
|
81
96
|
declare function getAddressFromOutScript(script: Uint8Array, bitcoinNetwork: BtcSignerNetwork): string;
|
|
97
|
+
/**
|
|
98
|
+
* Payment type identifiers, as described by `@scure/btc-signer` library
|
|
99
|
+
*/
|
|
82
100
|
type BtcSignerLibPaymentTypeIdentifers = 'wpkh' | 'wsh' | 'tr' | 'pkh' | 'sh';
|
|
83
101
|
declare const paymentTypeMap: Record<BtcSignerLibPaymentTypeIdentifers, PaymentTypes>;
|
|
84
102
|
declare function btcSignerLibPaymentTypeToPaymentTypeMap(payment: BtcSignerLibPaymentTypeIdentifers): PaymentTypes;
|
|
@@ -86,6 +104,12 @@ declare function isBtcSignerLibPaymentType(payment: string): payment is BtcSigne
|
|
|
86
104
|
declare function parseKnownPaymentType(payment: BtcSignerLibPaymentTypeIdentifers | PaymentTypes): PaymentTypes;
|
|
87
105
|
type PaymentTypeMap<T> = Record<PaymentTypes, T>;
|
|
88
106
|
declare function whenPaymentType(mode: PaymentTypes | BtcSignerLibPaymentTypeIdentifers): <T extends unknown>(paymentMap: PaymentTypeMap<T>) => T;
|
|
107
|
+
/**
|
|
108
|
+
* Infers the Bitcoin payment type from the derivation path.
|
|
109
|
+
* Below we see path has 86 in it, per convention, this refers to taproot payments
|
|
110
|
+
* @example
|
|
111
|
+
* `m/86'/1'/0'/0/0`
|
|
112
|
+
*/
|
|
89
113
|
declare function inferPaymentTypeFromPath(path: string): PaymentTypes;
|
|
90
114
|
declare function inferNetworkFromPath(path: string): NetworkModes;
|
|
91
115
|
declare function extractExtendedPublicKeyFromPolicy(policy: string): string;
|
|
@@ -102,18 +126,30 @@ interface GetTaprootAddressArgs {
|
|
|
102
126
|
network: BitcoinNetworkModes;
|
|
103
127
|
}
|
|
104
128
|
declare function getTaprootAddress({ index, keychain, network }: GetTaprootAddressArgs): string;
|
|
129
|
+
/**
|
|
130
|
+
* @deprecated
|
|
131
|
+
* Use `deriveRootBip32Keychain` in `@leather.io/crypto` instead
|
|
132
|
+
*/
|
|
105
133
|
declare function mnemonicToRootNode(secretKey: string): HDKey;
|
|
106
134
|
declare function getPsbtTxInputs(psbtTx: btc.Transaction): TransactionInput[];
|
|
107
135
|
declare function getPsbtTxOutputs(psbtTx: btc.Transaction): TransactionOutput[];
|
|
108
136
|
|
|
109
|
-
declare function
|
|
110
|
-
|
|
137
|
+
declare function makeTaprootAccountDerivationPath(network: BitcoinNetworkModes, accountIndex: number): string;
|
|
138
|
+
/** @deprecated Use makeTaprootAccountDerivationPath */
|
|
139
|
+
declare const getTaprootAccountDerivationPath: typeof makeTaprootAccountDerivationPath;
|
|
140
|
+
declare function makeTaprootAddressIndexDerivationPath(network: BitcoinNetworkModes, accountIndex: number, addressIndex: number): string;
|
|
141
|
+
/** @deprecated Use makeTaprootAddressIndexDerivationPath */
|
|
142
|
+
declare const getTaprootAddressIndexDerivationPath: typeof makeTaprootAddressIndexDerivationPath;
|
|
111
143
|
declare function deriveTaprootAccount(keychain: HDKey, network: BitcoinNetworkModes): (accountIndex: number) => BitcoinAccount;
|
|
112
144
|
declare function getTaprootPayment(publicKey: Uint8Array, network: BitcoinNetworkModes): _scure_btc_signer_payment.P2TROut;
|
|
113
145
|
declare function getTaprootPaymentFromAddressIndex(keychain: HDKey, network: BitcoinNetworkModes): _scure_btc_signer_payment.P2TROut;
|
|
114
146
|
|
|
115
|
-
declare function
|
|
116
|
-
|
|
147
|
+
declare function makeNativeSegwitAccountDerivationPath(network: BitcoinNetworkModes, accountIndex: number): string;
|
|
148
|
+
/** @deprecated Use makeNativeSegwitAccountDerivationPath */
|
|
149
|
+
declare const getNativeSegwitAccountDerivationPath: typeof makeNativeSegwitAccountDerivationPath;
|
|
150
|
+
declare function makeNativeSegwitAddressIndexDerivationPath(network: BitcoinNetworkModes, accountIndex: number, addressIndex: number): string;
|
|
151
|
+
/** @deprecated Use makeNativeSegwitAddressIndexDerivationPath */
|
|
152
|
+
declare const getNativeSegwitAddressIndexDerivationPath: typeof makeNativeSegwitAddressIndexDerivationPath;
|
|
117
153
|
declare function deriveNativeSegwitAccountFromRootKeychain(keychain: HDKey, network: BitcoinNetworkModes): (accountIndex: number) => BitcoinAccount;
|
|
118
154
|
declare function getNativeSegWitPaymentFromAddressIndex(keychain: HDKey, network: BitcoinNetworkModes): _scure_btc_signer_payment.P2Ret;
|
|
119
155
|
interface DeriveNativeSegWitReceiveAddressIndexArgs {
|
|
@@ -122,7 +158,15 @@ interface DeriveNativeSegWitReceiveAddressIndexArgs {
|
|
|
122
158
|
}
|
|
123
159
|
declare function deriveNativeSegWitReceiveAddressIndex({ xpub, network, }: DeriveNativeSegWitReceiveAddressIndexArgs): _scure_btc_signer_payment.P2Ret | undefined;
|
|
124
160
|
|
|
125
|
-
|
|
161
|
+
/**
|
|
162
|
+
* @deprecated
|
|
163
|
+
* Use `deriveBip39MnemonicFromSeed` from `@leather.io/crypto`
|
|
164
|
+
*/
|
|
165
|
+
declare const deriveBtcBip49SeedFromMnemonic: typeof deriveBip39SeedFromMnemonic;
|
|
166
|
+
/**
|
|
167
|
+
* @deprecated
|
|
168
|
+
* Use `deriveRootBip32Keychain` from `@leather.io/crypto`
|
|
169
|
+
*/
|
|
126
170
|
declare const deriveRootBtcKeychain: typeof deriveRootBip32Keychain;
|
|
127
171
|
declare function decodeCompressedWifPrivateKey(key: string): Uint8Array;
|
|
128
172
|
declare const payToScriptHashTestnetPrefix = 196;
|
|
@@ -131,4 +175,4 @@ declare function makePayToScriptHashAddressBytes(keyHash: Uint8Array): Uint8Arra
|
|
|
131
175
|
declare function makePayToScriptHashAddress(addressBytes: Uint8Array, network: NetworkModes): string;
|
|
132
176
|
declare function publicKeyToPayToScriptHashAddress(publicKey: Uint8Array, network: NetworkModes): string;
|
|
133
177
|
|
|
134
|
-
export { type AllowedSighashTypes, type BitcoinAccount, type BtcSignerLibPaymentTypeIdentifers, type BtcSignerNetwork, type GetTaprootAddressArgs, type PaymentTypeMap, type Signer, bip322TransactionToSignValues, bitcoinNetworkModeToCoreNetworkMode, bitcoinNetworkToCoreNetworkMap, btcSignerLibPaymentTypeToPaymentTypeMap, coinTypeMap, createNativeSegwitBitcoinJsSigner, createTaprootBitcoinJsSigner, createToSpendTx, createWalletIdDecoratedPath, decodeBitcoinTx, decodeCompressedWifPrivateKey, deriveAddressIndexKeychainFromAccount, deriveAddressIndexZeroFromAccount, deriveBtcBip49SeedFromMnemonic, deriveNativeSegWitReceiveAddressIndex, deriveNativeSegwitAccountFromRootKeychain, deriveRootBtcKeychain, deriveTaprootAccount, ecPairFromPrivateKey, ecdsaPublicKeyLength, ecdsaPublicKeyToSchnorr, encodeMessageWitnessData, extractExtendedPublicKeyFromPolicy, getAddressFromOutScript, getBitcoinCoinTypeIndexByNetwork, getBitcoinInputAddress, getBitcoinJsLibNetworkConfigByMode, getBtcSignerLibNetworkConfigByMode, getHdKeyVersionsFromNetwork, getInputPaymentType, getNativeSegWitPaymentFromAddressIndex, getNativeSegwitAccountDerivationPath, getNativeSegwitAddressIndexDerivationPath, getPsbtTxInputs, getPsbtTxOutputs, getTaprootAccountDerivationPath, getTaprootAddress, getTaprootAddressIndexDerivationPath, getTaprootPayment, getTaprootPaymentFromAddressIndex, hashBip322Message, inferNetworkFromPath, inferPaymentTypeFromPath, initBitcoinAccount, isBtcSignerLibPaymentType, isSupportedMessageSigningPaymentType, lookUpLedgerKeysByPath, makePayToScriptHashAddress, makePayToScriptHashAddressBytes, makePayToScriptHashKeyHash, mnemonicToRootNode, parseKnownPaymentType, payToScriptHashTestnetPrefix, paymentTypeMap, publicKeyToPayToScriptHashAddress, signBip322MessageSimple, toXOnly, tweakSigner, whenPaymentType };
|
|
178
|
+
export { type AllowedSighashTypes, type BitcoinAccount, type BtcSignerLibPaymentTypeIdentifers, type BtcSignerNetwork, type GetTaprootAddressArgs, type PaymentTypeMap, type Signer, bip322TransactionToSignValues, bitcoinNetworkModeToCoreNetworkMode, bitcoinNetworkToCoreNetworkMap, btcSignerLibPaymentTypeToPaymentTypeMap, coinTypeMap, createNativeSegwitBitcoinJsSigner, createTaprootBitcoinJsSigner, createToSpendTx, createWalletIdDecoratedPath, decodeBitcoinTx, decodeCompressedWifPrivateKey, deriveAddressIndexKeychainFromAccount, deriveAddressIndexZeroFromAccount, deriveBtcBip49SeedFromMnemonic, deriveNativeSegWitReceiveAddressIndex, deriveNativeSegwitAccountFromRootKeychain, deriveRootBtcKeychain, deriveTaprootAccount, ecPairFromPrivateKey, ecdsaPublicKeyLength, ecdsaPublicKeyToSchnorr, encodeMessageWitnessData, extractExtendedPublicKeyFromPolicy, getAddressFromOutScript, getBitcoinCoinTypeIndexByNetwork, getBitcoinInputAddress, getBitcoinJsLibNetworkConfigByMode, getBtcSignerLibNetworkConfigByMode, getHdKeyVersionsFromNetwork, getInputPaymentType, getNativeSegWitPaymentFromAddressIndex, getNativeSegwitAccountDerivationPath, getNativeSegwitAddressIndexDerivationPath, getPsbtTxInputs, getPsbtTxOutputs, getTaprootAccountDerivationPath, getTaprootAddress, getTaprootAddressIndexDerivationPath, getTaprootPayment, getTaprootPaymentFromAddressIndex, hashBip322Message, inferNetworkFromPath, inferPaymentTypeFromPath, initBitcoinAccount, isBtcSignerLibPaymentType, isSupportedMessageSigningPaymentType, lookUpLedgerKeysByPath, makeNativeSegwitAccountDerivationPath, makeNativeSegwitAddressIndexDerivationPath, makePayToScriptHashAddress, makePayToScriptHashAddressBytes, makePayToScriptHashKeyHash, makeTaprootAccountDerivationPath, makeTaprootAddressIndexDerivationPath, mnemonicToRootNode, parseKnownPaymentType, payToScriptHashTestnetPrefix, paymentTypeMap, publicKeyToPayToScriptHashAddress, signBip322MessageSimple, toXOnly, tweakSigner, whenPaymentType };
|
package/dist/index.js
CHANGED
|
@@ -59,12 +59,14 @@ function getBitcoinJsLibNetworkConfigByMode(network) {
|
|
|
59
59
|
// src/p2tr-address-gen.ts
|
|
60
60
|
import * as btc from "@scure/btc-signer";
|
|
61
61
|
import { DerivationPathDepth } from "@leather.io/crypto";
|
|
62
|
-
function
|
|
62
|
+
function makeTaprootAccountDerivationPath(network, accountIndex) {
|
|
63
63
|
return `m/86'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;
|
|
64
64
|
}
|
|
65
|
-
|
|
66
|
-
|
|
65
|
+
var getTaprootAccountDerivationPath = makeTaprootAccountDerivationPath;
|
|
66
|
+
function makeTaprootAddressIndexDerivationPath(network, accountIndex, addressIndex) {
|
|
67
|
+
return makeTaprootAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;
|
|
67
68
|
}
|
|
69
|
+
var getTaprootAddressIndexDerivationPath = makeTaprootAddressIndexDerivationPath;
|
|
68
70
|
function deriveTaprootAccount(keychain, network) {
|
|
69
71
|
if (keychain.depth !== DerivationPathDepth.Root)
|
|
70
72
|
throw new Error("Keychain passed is not an account");
|
|
@@ -72,8 +74,8 @@ function deriveTaprootAccount(keychain, network) {
|
|
|
72
74
|
type: "p2tr",
|
|
73
75
|
network,
|
|
74
76
|
accountIndex,
|
|
75
|
-
derivationPath:
|
|
76
|
-
keychain: keychain.derive(
|
|
77
|
+
derivationPath: makeTaprootAccountDerivationPath(network, accountIndex),
|
|
78
|
+
keychain: keychain.derive(makeTaprootAccountDerivationPath(network, accountIndex))
|
|
77
79
|
});
|
|
78
80
|
}
|
|
79
81
|
function getTaprootPayment(publicKey, network) {
|
|
@@ -377,20 +379,22 @@ async function signBip322MessageSimple(args) {
|
|
|
377
379
|
import { HDKey as HDKey2 } from "@scure/bip32";
|
|
378
380
|
import * as btc3 from "@scure/btc-signer";
|
|
379
381
|
import { DerivationPathDepth as DerivationPathDepth3 } from "@leather.io/crypto";
|
|
380
|
-
function
|
|
382
|
+
function makeNativeSegwitAccountDerivationPath(network, accountIndex) {
|
|
381
383
|
return `m/84'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;
|
|
382
384
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
+
var getNativeSegwitAccountDerivationPath = makeNativeSegwitAccountDerivationPath;
|
|
386
|
+
function makeNativeSegwitAddressIndexDerivationPath(network, accountIndex, addressIndex) {
|
|
387
|
+
return makeNativeSegwitAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;
|
|
385
388
|
}
|
|
389
|
+
var getNativeSegwitAddressIndexDerivationPath = makeNativeSegwitAddressIndexDerivationPath;
|
|
386
390
|
function deriveNativeSegwitAccountFromRootKeychain(keychain, network) {
|
|
387
391
|
if (keychain.depth !== DerivationPathDepth3.Root) throw new Error("Keychain passed is not a root");
|
|
388
392
|
return (accountIndex) => ({
|
|
389
393
|
type: "p2wpkh",
|
|
390
394
|
network,
|
|
391
395
|
accountIndex,
|
|
392
|
-
derivationPath:
|
|
393
|
-
keychain: keychain.derive(
|
|
396
|
+
derivationPath: makeNativeSegwitAccountDerivationPath(network, accountIndex),
|
|
397
|
+
keychain: keychain.derive(makeNativeSegwitAccountDerivationPath(network, accountIndex))
|
|
394
398
|
});
|
|
395
399
|
}
|
|
396
400
|
function getNativeSegWitPaymentFromAddressIndex(keychain, network) {
|
|
@@ -414,8 +418,8 @@ function deriveNativeSegWitReceiveAddressIndex({
|
|
|
414
418
|
import { ripemd160 } from "@noble/hashes/ripemd160";
|
|
415
419
|
import { sha256 as sha2562 } from "@noble/hashes/sha256";
|
|
416
420
|
import { base58check } from "@scure/base";
|
|
417
|
-
import {
|
|
418
|
-
var deriveBtcBip49SeedFromMnemonic =
|
|
421
|
+
import { deriveBip39SeedFromMnemonic, deriveRootBip32Keychain } from "@leather.io/crypto";
|
|
422
|
+
var deriveBtcBip49SeedFromMnemonic = deriveBip39SeedFromMnemonic;
|
|
419
423
|
var deriveRootBtcKeychain = deriveRootBip32Keychain;
|
|
420
424
|
function decodeCompressedWifPrivateKey(key) {
|
|
421
425
|
const compressedWifFormatPrivateKey = base58check(sha2562).decode(key);
|
|
@@ -499,9 +503,13 @@ export {
|
|
|
499
503
|
isBtcSignerLibPaymentType,
|
|
500
504
|
isSupportedMessageSigningPaymentType,
|
|
501
505
|
lookUpLedgerKeysByPath,
|
|
506
|
+
makeNativeSegwitAccountDerivationPath,
|
|
507
|
+
makeNativeSegwitAddressIndexDerivationPath,
|
|
502
508
|
makePayToScriptHashAddress,
|
|
503
509
|
makePayToScriptHashAddressBytes,
|
|
504
510
|
makePayToScriptHashKeyHash,
|
|
511
|
+
makeTaprootAccountDerivationPath,
|
|
512
|
+
makeTaprootAddressIndexDerivationPath,
|
|
505
513
|
mnemonicToRootNode,
|
|
506
514
|
parseKnownPaymentType,
|
|
507
515
|
payToScriptHashTestnetPrefix,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bip322/bip322-utils.ts","../src/bitcoin.utils.ts","../src/bitcoin.network.ts","../src/p2tr-address-gen.ts","../src/bip322/sign-message-bip322-bitcoinjs.ts","../src/p2wpkh-address-gen.ts","../src/p2wsh-p2sh-address-gen.ts"],"sourcesContent":["import ecc from '@bitcoinerlab/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { hexToBytes, utf8ToBytes } from '@stacks/common';\nimport * as bitcoin from 'bitcoinjs-lib';\nimport { ECPairFactory } from 'ecpair';\nimport { encode } from 'varuint-bitcoin';\n\nimport { PaymentTypes } from '@leather.io/rpc';\nimport { isString } from '@leather.io/utils';\n\nimport { toXOnly } from '../bitcoin.utils';\n\nconst bip322MessageTag = 'BIP0322-signed-message';\n\nconst ECPair = ECPairFactory(ecc);\nbitcoin.initEccLib(ecc);\n\nexport function ecPairFromPrivateKey(key: Uint8Array) {\n return ECPair.fromPrivateKey(Buffer.from(key));\n}\n\n// See tagged hashes section of BIP-340\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#design\nconst messageTagHash = Uint8Array.from([\n ...sha256(utf8ToBytes(bip322MessageTag)),\n ...sha256(utf8ToBytes(bip322MessageTag)),\n]);\n\nexport function hashBip322Message(message: Uint8Array | string) {\n return sha256(\n Uint8Array.from([...messageTagHash, ...(isString(message) ? utf8ToBytes(message) : message)])\n );\n}\n\nexport const bip322TransactionToSignValues = {\n prevoutHash: hexToBytes('0000000000000000000000000000000000000000000000000000000000000000'),\n prevoutIndex: 0xffffffff,\n sequence: 0,\n};\n\nfunction encodeVarString(b: Buffer) {\n return Buffer.concat([encode(b.byteLength), b]);\n}\n\nconst supportedMessageSigningPaymentTypes: PaymentTypes[] = ['p2wpkh', 'p2tr'];\n\nexport function isSupportedMessageSigningPaymentType(paymentType: string) {\n return supportedMessageSigningPaymentTypes.includes(paymentType as PaymentTypes);\n}\n\n/**\n * Encode witness data for a BIP322 message\n * TODO: Refactor to remove `Buffer` use\n */\nexport function encodeMessageWitnessData(witnessArray: Buffer[]) {\n const len = encode(witnessArray.length);\n return Buffer.concat([len, ...witnessArray.map(witness => encodeVarString(witness))]);\n}\n\nfunction tapTweakHash(pubKey: Buffer, h: Buffer | undefined): Buffer {\n return bitcoin.crypto.taggedHash('TapTweak', Buffer.concat(h ? [pubKey, h] : [pubKey]));\n}\n\nexport function tweakSigner(signer: bitcoin.Signer, opts: any = {}): bitcoin.Signer {\n // @ts-expect-error privateKey exists on signer\n let privateKey: Uint8Array | undefined = signer.privateKey!;\n if (!privateKey) {\n throw new Error('Private key is required for tweaking signer!');\n }\n if (signer.publicKey[0] === 3) {\n privateKey = ecc.privateNegate(privateKey);\n }\n\n const tweakedPrivateKey = ecc.privateAdd(\n privateKey,\n tapTweakHash(toXOnly(signer.publicKey), opts.tweakHash)\n );\n if (!tweakedPrivateKey) {\n throw new Error('Invalid tweaked private key!');\n }\n\n return ECPair.fromPrivateKey(Buffer.from(tweakedPrivateKey), {\n network: opts.network,\n });\n}\n","import { hexToBytes } from '@noble/hashes/utils';\nimport { HDKey, Versions } from '@scure/bip32';\nimport { mnemonicToSeedSync } from '@scure/bip39';\nimport * as btc from '@scure/btc-signer';\nimport { TransactionInput, TransactionOutput } from '@scure/btc-signer/psbt';\n\nimport { DerivationPathDepth, extractAccountIndexFromPath } from '@leather.io/crypto';\nimport { BitcoinNetworkModes, NetworkModes } from '@leather.io/models';\nimport type { PaymentTypes } from '@leather.io/rpc';\nimport { defaultWalletKeyId, isDefined, whenNetwork } from '@leather.io/utils';\n\nimport { BtcSignerNetwork, getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport { getTaprootPayment } from './p2tr-address-gen';\n\nexport interface BitcoinAccount {\n type: PaymentTypes;\n derivationPath: string;\n keychain: HDKey;\n accountIndex: number;\n network: BitcoinNetworkModes;\n}\nexport function initBitcoinAccount(derivationPath: string, policy: string): BitcoinAccount {\n const xpub = extractExtendedPublicKeyFromPolicy(policy);\n const network = inferNetworkFromPath(derivationPath);\n return {\n keychain: HDKey.fromExtendedKey(xpub, getHdKeyVersionsFromNetwork(network)),\n network,\n derivationPath,\n type: inferPaymentTypeFromPath(derivationPath),\n accountIndex: extractAccountIndexFromPath(derivationPath),\n };\n}\n\n/**\n * Represents a map of `BitcoinNetworkModes` to `NetworkModes`. While Bitcoin\n * has a number of networks, its often only necessary to consider the higher\n * level concepts of mainnet and testnet\n */\nexport const bitcoinNetworkToCoreNetworkMap: Record<BitcoinNetworkModes, NetworkModes> = {\n mainnet: 'mainnet',\n testnet: 'testnet',\n regtest: 'testnet',\n signet: 'testnet',\n};\nexport function bitcoinNetworkModeToCoreNetworkMode(mode: BitcoinNetworkModes) {\n return bitcoinNetworkToCoreNetworkMap[mode];\n}\n\n/**\n * Map representing the \"Coin Type\" section of a derivation path.\n * Consider example below, Coin type is one, thus testnet\n * @example\n * `m/86'/1'/0'/0/0`\n */\nexport const coinTypeMap: Record<NetworkModes, 0 | 1> = {\n mainnet: 0,\n testnet: 1,\n};\n\nexport function getBitcoinCoinTypeIndexByNetwork(network: BitcoinNetworkModes) {\n return coinTypeMap[bitcoinNetworkModeToCoreNetworkMode(network)];\n}\n\nexport function deriveAddressIndexKeychainFromAccount(keychain: HDKey) {\n if (keychain.depth !== DerivationPathDepth.Account)\n throw new Error('Keychain passed is not an account');\n\n return (index: number) => keychain.deriveChild(0).deriveChild(index);\n}\n\nexport function deriveAddressIndexZeroFromAccount(keychain: HDKey) {\n return deriveAddressIndexKeychainFromAccount(keychain)(0);\n}\n\nexport const ecdsaPublicKeyLength = 33;\n\nexport function ecdsaPublicKeyToSchnorr(pubKey: Uint8Array) {\n if (pubKey.byteLength !== ecdsaPublicKeyLength) throw new Error('Invalid public key length');\n return pubKey.slice(1);\n}\n\n// Basically same as above, to remove\nexport const toXOnly = (pubKey: Buffer) => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33));\n\nexport function decodeBitcoinTx(tx: string): ReturnType<typeof btc.RawTx.decode> {\n return btc.RawTx.decode(hexToBytes(tx));\n}\n\nexport function getAddressFromOutScript(script: Uint8Array, bitcoinNetwork: BtcSignerNetwork) {\n const outputScript = btc.OutScript.decode(script);\n\n switch (outputScript.type) {\n case 'pkh':\n case 'sh':\n case 'wpkh':\n case 'wsh':\n return btc.Address(bitcoinNetwork).encode({\n type: outputScript.type,\n hash: outputScript.hash,\n });\n case 'tr':\n return btc.Address(bitcoinNetwork).encode({\n type: outputScript.type,\n pubkey: outputScript.pubkey,\n });\n case 'ms':\n return btc.p2ms(outputScript.m, outputScript.pubkeys).address ?? '';\n case 'pk':\n return btc.p2pk(outputScript.pubkey, bitcoinNetwork).address ?? '';\n case 'unknown':\n return 'unknown';\n case 'tr_ms':\n case 'tr_ns':\n default:\n return '';\n }\n}\n\n/**\n * Payment type identifiers, as described by `@scure/btc-signer` library\n */\nexport type BtcSignerLibPaymentTypeIdentifers = 'wpkh' | 'wsh' | 'tr' | 'pkh' | 'sh';\n\nexport const paymentTypeMap: Record<BtcSignerLibPaymentTypeIdentifers, PaymentTypes> = {\n wpkh: 'p2wpkh',\n wsh: 'p2wpkh-p2sh',\n tr: 'p2tr',\n pkh: 'p2pkh',\n sh: 'p2sh',\n};\n\nexport function btcSignerLibPaymentTypeToPaymentTypeMap(\n payment: BtcSignerLibPaymentTypeIdentifers\n) {\n return paymentTypeMap[payment];\n}\n\nexport function isBtcSignerLibPaymentType(\n payment: string\n): payment is BtcSignerLibPaymentTypeIdentifers {\n return payment in paymentTypeMap;\n}\n\nexport function parseKnownPaymentType(payment: BtcSignerLibPaymentTypeIdentifers | PaymentTypes) {\n return isBtcSignerLibPaymentType(payment)\n ? btcSignerLibPaymentTypeToPaymentTypeMap(payment)\n : payment;\n}\n\nexport type PaymentTypeMap<T> = Record<PaymentTypes, T>;\nexport function whenPaymentType(mode: PaymentTypes | BtcSignerLibPaymentTypeIdentifers) {\n return <T extends unknown>(paymentMap: PaymentTypeMap<T>): T =>\n paymentMap[parseKnownPaymentType(mode)];\n}\n\n/**\n * Infers the Bitcoin payment type from the derivation path.\n * Below we see path has 86 in it, per convention, this refers to taproot payments\n * @example\n * `m/86'/1'/0'/0/0`\n */\nexport function inferPaymentTypeFromPath(path: string): PaymentTypes {\n if (path.startsWith('m/84')) return 'p2wpkh';\n if (path.startsWith('m/86')) return 'p2tr';\n if (path.startsWith('m/44')) return 'p2pkh';\n throw new Error(`Unable to infer payment type from path=${path}`);\n}\n\nexport function inferNetworkFromPath(path: string): NetworkModes {\n return path.split('/')[2].startsWith('0') ? 'mainnet' : 'testnet';\n}\n\nexport function extractExtendedPublicKeyFromPolicy(policy: string) {\n return policy.split(']')[1];\n}\n\nexport function createWalletIdDecoratedPath(policy: string, walletId: string) {\n return policy.split(']')[0].replace('[', '').replace('m', walletId);\n}\n\n// Primarily used to get the correct `Version` when passing Ledger Bitcoin\n// extended public keys to the HDKey constructor\nexport function getHdKeyVersionsFromNetwork(network: NetworkModes) {\n return whenNetwork(network)({\n mainnet: undefined,\n testnet: {\n private: 0x00000000,\n public: 0x043587cf,\n } as Versions,\n });\n}\n\nexport function getBitcoinInputAddress(input: TransactionInput, bitcoinNetwork: BtcSignerNetwork) {\n if (isDefined(input.witnessUtxo))\n return getAddressFromOutScript(input.witnessUtxo.script, bitcoinNetwork);\n if (isDefined(input.nonWitnessUtxo) && isDefined(input.index))\n return getAddressFromOutScript(\n input.nonWitnessUtxo.outputs[input.index]?.script,\n bitcoinNetwork\n );\n return '';\n}\n\nexport function getInputPaymentType(\n input: TransactionInput,\n network: BitcoinNetworkModes\n): PaymentTypes {\n const address = getBitcoinInputAddress(input, getBtcSignerLibNetworkConfigByMode(network));\n if (address === '') throw new Error('Input address cannot be empty');\n if (address.startsWith('bc1p') || address.startsWith('tb1p') || address.startsWith('bcrt1p'))\n return 'p2tr';\n if (address.startsWith('bc1q') || address.startsWith('tb1q') || address.startsWith('bcrt1q'))\n return 'p2wpkh';\n throw new Error('Unable to infer payment type from input address');\n}\n\n// Ledger wallets are keyed by their derivation path. To reuse the look up logic\n// between payment types, this factory fn accepts a fn that generates the path\nexport function lookUpLedgerKeysByPath(\n getDerivationPath: (network: BitcoinNetworkModes, accountIndex: number) => string\n) {\n return (\n ledgerKeyMap: Record<string, { policy: string } | undefined>,\n network: BitcoinNetworkModes\n ) =>\n (accountIndex: number) => {\n const path = getDerivationPath(network, accountIndex);\n // Single wallet mode, hardcoded default walletId\n const account = ledgerKeyMap[path.replace('m', defaultWalletKeyId)];\n if (!account) return;\n return initBitcoinAccount(path, account.policy);\n };\n}\n\nexport interface GetTaprootAddressArgs {\n index: number;\n keychain?: HDKey;\n network: BitcoinNetworkModes;\n}\nexport function getTaprootAddress({ index, keychain, network }: GetTaprootAddressArgs) {\n if (!keychain) throw new Error('Expected keychain to be provided');\n\n if (keychain.depth !== DerivationPathDepth.Account)\n throw new Error('Expects keychain to be on the account index');\n\n const addressIndex = deriveAddressIndexKeychainFromAccount(keychain)(index);\n\n if (!addressIndex.publicKey) {\n throw new Error('Expected publicKey to be defined');\n }\n\n const payment = getTaprootPayment(addressIndex.publicKey, network);\n\n if (!payment.address) throw new Error('Expected address to be defined');\n\n return payment.address;\n}\n\nexport function mnemonicToRootNode(secretKey: string) {\n const seed = mnemonicToSeedSync(secretKey);\n return HDKey.fromMasterSeed(seed);\n}\n\nexport function getPsbtTxInputs(psbtTx: btc.Transaction): TransactionInput[] {\n const inputsLength = psbtTx.inputsLength;\n const inputs: TransactionInput[] = [];\n for (let i = 0; i < inputsLength; i++) inputs.push(psbtTx.getInput(i));\n return inputs;\n}\n\nexport function getPsbtTxOutputs(psbtTx: btc.Transaction): TransactionOutput[] {\n const outputsLength = psbtTx.outputsLength;\n const outputs: TransactionOutput[] = [];\n for (let i = 0; i < outputsLength; i++) outputs.push(psbtTx.getOutput(i));\n return outputs;\n}\n","import * as bitcoinJs from 'bitcoinjs-lib';\n\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\n// See this PR https://github.com/paulmillr/@scure/btc-signer/pull/15\n// Atttempting to add these directly to the library\nexport interface BtcSignerNetwork {\n bech32: string;\n pubKeyHash: number;\n scriptHash: number;\n wif: number;\n}\n\nconst bitcoinMainnet: BtcSignerNetwork = {\n bech32: 'bc',\n pubKeyHash: 0x00,\n scriptHash: 0x05,\n wif: 0x80,\n};\n\nconst bitcoinTestnet: BtcSignerNetwork = {\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n};\n\nconst bitcoinRegtest: BtcSignerNetwork = {\n bech32: 'bcrt',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n};\n\nconst btcSignerLibNetworks: Record<BitcoinNetworkModes, BtcSignerNetwork> = {\n mainnet: bitcoinMainnet,\n testnet: bitcoinTestnet,\n regtest: bitcoinRegtest,\n // Signet originally was going to have its own prefix but authors decided to\n // copy testnet\n signet: bitcoinTestnet,\n};\n\nexport function getBtcSignerLibNetworkConfigByMode(network: BitcoinNetworkModes) {\n return btcSignerLibNetworks[network];\n}\n\nconst bitcoinJsLibNetworks: Record<BitcoinNetworkModes, bitcoinJs.Network> = {\n mainnet: bitcoinJs.networks.bitcoin,\n testnet: bitcoinJs.networks.testnet,\n regtest: bitcoinJs.networks.regtest,\n signet: bitcoinJs.networks.testnet,\n};\n\nexport function getBitcoinJsLibNetworkConfigByMode(network: BitcoinNetworkModes) {\n return bitcoinJsLibNetworks[network];\n}\n","import { HDKey } from '@scure/bip32';\nimport * as btc from '@scure/btc-signer';\n\nimport { DerivationPathDepth } from '@leather.io/crypto';\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport {\n BitcoinAccount,\n ecdsaPublicKeyToSchnorr,\n getBitcoinCoinTypeIndexByNetwork,\n} from './bitcoin.utils';\n\nexport function getTaprootAccountDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number\n) {\n return `m/86'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;\n}\n\nexport function getTaprootAddressIndexDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number,\n addressIndex: number\n) {\n return getTaprootAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;\n}\n\nexport function deriveTaprootAccount(keychain: HDKey, network: BitcoinNetworkModes) {\n if (keychain.depth !== DerivationPathDepth.Root)\n throw new Error('Keychain passed is not an account');\n\n return (accountIndex: number): BitcoinAccount => ({\n type: 'p2tr',\n network,\n accountIndex,\n derivationPath: getTaprootAccountDerivationPath(network, accountIndex),\n keychain: keychain.derive(getTaprootAccountDerivationPath(network, accountIndex)),\n });\n}\n\nexport function getTaprootPayment(publicKey: Uint8Array, network: BitcoinNetworkModes) {\n return btc.p2tr(\n ecdsaPublicKeyToSchnorr(publicKey),\n undefined,\n getBtcSignerLibNetworkConfigByMode(network)\n );\n}\n\nexport function getTaprootPaymentFromAddressIndex(keychain: HDKey, network: BitcoinNetworkModes) {\n if (keychain.depth !== DerivationPathDepth.AddressIndex)\n throw new Error('Keychain passed is not an address index');\n\n if (!keychain.publicKey) throw new Error('Keychain has no public key');\n\n return getTaprootPayment(keychain.publicKey, network);\n}\n","import { base64 } from '@scure/base';\nimport * as btc from '@scure/btc-signer';\nimport * as bitcoin from 'bitcoinjs-lib';\n\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBitcoinJsLibNetworkConfigByMode } from '../bitcoin.network';\nimport {\n bip322TransactionToSignValues,\n ecPairFromPrivateKey,\n encodeMessageWitnessData,\n hashBip322Message,\n tweakSigner,\n} from './bip322-utils';\n\nexport function createNativeSegwitBitcoinJsSigner(privateKey: Buffer) {\n return ecPairFromPrivateKey(privateKey);\n}\n\nexport function createTaprootBitcoinJsSigner(privateKey: Buffer) {\n return tweakSigner(ecPairFromPrivateKey(privateKey));\n}\n\nexport function createToSpendTx(address: string, message: string, network: BitcoinNetworkModes) {\n const { prevoutHash, prevoutIndex, sequence } = bip322TransactionToSignValues;\n\n const script = bitcoin.address.toOutputScript(\n address,\n getBitcoinJsLibNetworkConfigByMode(network)\n );\n\n const hash = hashBip322Message(message);\n const commands = [0, Buffer.from(hash)];\n const scriptSig = bitcoin.script.compile(commands);\n\n const virtualToSpend = new bitcoin.Transaction();\n virtualToSpend.version = 0;\n virtualToSpend.addInput(Buffer.from(prevoutHash), prevoutIndex, sequence, scriptSig);\n virtualToSpend.addOutput(script, 0);\n return { virtualToSpend, script };\n}\n\nfunction createToSignTx(toSpendTxHex: Buffer, script: Buffer, network: BitcoinNetworkModes) {\n const virtualToSign = new bitcoin.Psbt({ network: getBitcoinJsLibNetworkConfigByMode(network) });\n virtualToSign.setVersion(0);\n const prevTxHash = toSpendTxHex;\n const prevOutIndex = 0;\n const toSignScriptSig = bitcoin.script.compile([bitcoin.script.OPS.OP_RETURN]);\n\n virtualToSign.addInput({\n hash: prevTxHash,\n index: prevOutIndex,\n sequence: 0,\n witnessUtxo: { script, value: 0 },\n });\n\n virtualToSign.addOutput({ script: toSignScriptSig, value: 0 });\n return virtualToSign;\n}\n\ninterface SignBip322MessageSimple {\n address: string;\n message: string;\n network: BitcoinNetworkModes;\n signPsbt(psbt: bitcoin.Psbt): Promise<btc.Transaction>;\n}\nexport async function signBip322MessageSimple(args: SignBip322MessageSimple) {\n const { address, message, network, signPsbt } = args;\n\n const { virtualToSpend, script } = createToSpendTx(address, message, network);\n\n const virtualToSign = createToSignTx(virtualToSpend.getHash(), script, network);\n\n const signedTx = await signPsbt(virtualToSign);\n\n const asBitcoinJsTransaction = bitcoin.Psbt.fromBuffer(Buffer.from(signedTx.toPSBT()));\n\n asBitcoinJsTransaction.finalizeInput(0);\n\n // sign the tx\n // section 5.1\n // github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb\n const toSignTx = asBitcoinJsTransaction.extractTransaction();\n\n const result = encodeMessageWitnessData(toSignTx.ins[0].witness);\n\n return {\n virtualToSpend,\n virtualToSign: toSignTx,\n unencodedSig: result,\n signature: base64.encode(result),\n };\n}\n","import { HDKey } from '@scure/bip32';\nimport * as btc from '@scure/btc-signer';\n\nimport { DerivationPathDepth } from '@leather.io/crypto';\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport {\n BitcoinAccount,\n deriveAddressIndexZeroFromAccount,\n getBitcoinCoinTypeIndexByNetwork,\n} from './bitcoin.utils';\n\nexport function getNativeSegwitAccountDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number\n) {\n return `m/84'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;\n}\n\nexport function getNativeSegwitAddressIndexDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number,\n addressIndex: number\n) {\n return getNativeSegwitAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;\n}\n\nexport function deriveNativeSegwitAccountFromRootKeychain(\n keychain: HDKey,\n network: BitcoinNetworkModes\n) {\n if (keychain.depth !== DerivationPathDepth.Root) throw new Error('Keychain passed is not a root');\n return (accountIndex: number): BitcoinAccount => ({\n type: 'p2wpkh',\n network,\n accountIndex,\n derivationPath: getNativeSegwitAccountDerivationPath(network, accountIndex),\n keychain: keychain.derive(getNativeSegwitAccountDerivationPath(network, accountIndex)),\n });\n}\n\nexport function getNativeSegWitPaymentFromAddressIndex(\n keychain: HDKey,\n network: BitcoinNetworkModes\n) {\n if (keychain.depth !== DerivationPathDepth.AddressIndex)\n throw new Error('Keychain passed is not an address index');\n\n if (!keychain.publicKey) throw new Error('Keychain does not have a public key');\n\n return btc.p2wpkh(keychain.publicKey, getBtcSignerLibNetworkConfigByMode(network));\n}\n\ninterface DeriveNativeSegWitReceiveAddressIndexArgs {\n xpub: string;\n network: BitcoinNetworkModes;\n}\nexport function deriveNativeSegWitReceiveAddressIndex({\n xpub,\n network,\n}: DeriveNativeSegWitReceiveAddressIndexArgs) {\n if (!xpub) return;\n const keychain = HDKey.fromExtendedKey(xpub);\n if (!keychain) return;\n const zeroAddressIndex = deriveAddressIndexZeroFromAccount(keychain);\n return getNativeSegWitPaymentFromAddressIndex(zeroAddressIndex, network);\n}\n","import { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base58check } from '@scure/base';\n\nimport { deriveBip39MnemonicFromSeed, deriveRootBip32Keychain } from '@leather.io/crypto';\nimport { NetworkModes } from '@leather.io/models';\n\n/**\n * @deprecated\n * Use `deriveBip39MnemonicFromSeed` from `@leather.io/crypto`\n */\nexport const deriveBtcBip49SeedFromMnemonic = deriveBip39MnemonicFromSeed;\n\n/**\n * @deprecated\n * Use `deriveRootBip32Keychain` from `@leather.io/crypto`\n */\nexport const deriveRootBtcKeychain = deriveRootBip32Keychain;\n\nexport function decodeCompressedWifPrivateKey(key: string) {\n // https://en.bitcoinwiki.org/wiki/Wallet_import_format\n // Decode Compressed WIF format private key\n const compressedWifFormatPrivateKey = base58check(sha256).decode(key);\n // Drop leading network byte, trailing public key SEC format byte\n return compressedWifFormatPrivateKey.slice(1, compressedWifFormatPrivateKey.length - 1);\n}\n\n// https://en.bitcoin.it/wiki/List_of_address_prefixes\nconst payToScriptHashMainnetPrefix = 0x05;\nexport const payToScriptHashTestnetPrefix = 0xc4;\n\nconst payToScriptHashPrefixMap: Record<NetworkModes, number> = {\n mainnet: payToScriptHashMainnetPrefix,\n testnet: payToScriptHashTestnetPrefix,\n};\n\nfunction hash160(input: Uint8Array) {\n return ripemd160(sha256(input));\n}\n\nexport function makePayToScriptHashKeyHash(publicKey: Uint8Array) {\n return hash160(publicKey);\n}\n\nexport function makePayToScriptHashAddressBytes(keyHash: Uint8Array) {\n const redeemScript = Uint8Array.from([\n ...Uint8Array.of(0x00),\n ...Uint8Array.of(keyHash.length),\n ...keyHash,\n ]);\n return hash160(redeemScript);\n}\n\nexport function makePayToScriptHashAddress(addressBytes: Uint8Array, network: NetworkModes) {\n const networkByte = payToScriptHashPrefixMap[network];\n const addressWithPrefix = Uint8Array.from([networkByte, ...addressBytes]);\n return base58check(sha256).encode(addressWithPrefix);\n}\n\nexport function publicKeyToPayToScriptHashAddress(publicKey: Uint8Array, network: NetworkModes) {\n const hash = makePayToScriptHashKeyHash(publicKey);\n const addrBytes = makePayToScriptHashAddressBytes(hash);\n return makePayToScriptHashAddress(addrBytes, network);\n}\n"],"mappings":";AAAA,OAAO,SAAS;AAChB,SAAS,cAAc;AACvB,SAAS,cAAAA,aAAY,mBAAmB;AACxC,YAAY,aAAa;AACzB,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AAGvB,SAAS,gBAAgB;;;ACRzB,SAAS,kBAAkB;AAC3B,SAAS,aAAuB;AAChC,SAAS,0BAA0B;AACnC,YAAYC,UAAS;AAGrB,SAAS,uBAAAC,sBAAqB,mCAAmC;AAGjE,SAAS,oBAAoB,WAAW,mBAAmB;;;ACT3D,YAAY,eAAe;AAa3B,IAAM,iBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,KAAK;AACP;AAEA,IAAM,iBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,KA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AW,OAAO;AACtD;","names":["hexToBytes","btc","DerivationPathDepth","DerivationPathDepth","script","address","hexToBytes","bitcoin","address","script","HDKey","btc","DerivationPathDepth","DerivationPathDepth","HDKey","sha256"]}
|
|
1
|
+
{"version":3,"sources":["../src/bip322/bip322-utils.ts","../src/bitcoin.utils.ts","../src/bitcoin.network.ts","../src/p2tr-address-gen.ts","../src/bip322/sign-message-bip322-bitcoinjs.ts","../src/p2wpkh-address-gen.ts","../src/p2wsh-p2sh-address-gen.ts"],"sourcesContent":["import ecc from '@bitcoinerlab/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { hexToBytes, utf8ToBytes } from '@stacks/common';\nimport * as bitcoin from 'bitcoinjs-lib';\nimport { ECPairFactory } from 'ecpair';\nimport { encode } from 'varuint-bitcoin';\n\nimport { PaymentTypes } from '@leather.io/rpc';\nimport { isString } from '@leather.io/utils';\n\nimport { toXOnly } from '../bitcoin.utils';\n\nconst bip322MessageTag = 'BIP0322-signed-message';\n\nconst ECPair = ECPairFactory(ecc);\nbitcoin.initEccLib(ecc);\n\nexport function ecPairFromPrivateKey(key: Uint8Array) {\n return ECPair.fromPrivateKey(Buffer.from(key));\n}\n\n// See tagged hashes section of BIP-340\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#design\nconst messageTagHash = Uint8Array.from([\n ...sha256(utf8ToBytes(bip322MessageTag)),\n ...sha256(utf8ToBytes(bip322MessageTag)),\n]);\n\nexport function hashBip322Message(message: Uint8Array | string) {\n return sha256(\n Uint8Array.from([...messageTagHash, ...(isString(message) ? utf8ToBytes(message) : message)])\n );\n}\n\nexport const bip322TransactionToSignValues = {\n prevoutHash: hexToBytes('0000000000000000000000000000000000000000000000000000000000000000'),\n prevoutIndex: 0xffffffff,\n sequence: 0,\n};\n\nfunction encodeVarString(b: Buffer) {\n return Buffer.concat([encode(b.byteLength), b]);\n}\n\nconst supportedMessageSigningPaymentTypes: PaymentTypes[] = ['p2wpkh', 'p2tr'];\n\nexport function isSupportedMessageSigningPaymentType(paymentType: string) {\n return supportedMessageSigningPaymentTypes.includes(paymentType as PaymentTypes);\n}\n\n/**\n * Encode witness data for a BIP322 message\n * TODO: Refactor to remove `Buffer` use\n */\nexport function encodeMessageWitnessData(witnessArray: Buffer[]) {\n const len = encode(witnessArray.length);\n return Buffer.concat([len, ...witnessArray.map(witness => encodeVarString(witness))]);\n}\n\nfunction tapTweakHash(pubKey: Buffer, h: Buffer | undefined): Buffer {\n return bitcoin.crypto.taggedHash('TapTweak', Buffer.concat(h ? [pubKey, h] : [pubKey]));\n}\n\nexport function tweakSigner(signer: bitcoin.Signer, opts: any = {}): bitcoin.Signer {\n // @ts-expect-error privateKey exists on signer\n let privateKey: Uint8Array | undefined = signer.privateKey!;\n if (!privateKey) {\n throw new Error('Private key is required for tweaking signer!');\n }\n if (signer.publicKey[0] === 3) {\n privateKey = ecc.privateNegate(privateKey);\n }\n\n const tweakedPrivateKey = ecc.privateAdd(\n privateKey,\n tapTweakHash(toXOnly(signer.publicKey), opts.tweakHash)\n );\n if (!tweakedPrivateKey) {\n throw new Error('Invalid tweaked private key!');\n }\n\n return ECPair.fromPrivateKey(Buffer.from(tweakedPrivateKey), {\n network: opts.network,\n });\n}\n","import { hexToBytes } from '@noble/hashes/utils';\nimport { HDKey, Versions } from '@scure/bip32';\nimport { mnemonicToSeedSync } from '@scure/bip39';\nimport * as btc from '@scure/btc-signer';\nimport { TransactionInput, TransactionOutput } from '@scure/btc-signer/psbt';\n\nimport { DerivationPathDepth, extractAccountIndexFromPath } from '@leather.io/crypto';\nimport { BitcoinNetworkModes, NetworkModes } from '@leather.io/models';\nimport type { PaymentTypes } from '@leather.io/rpc';\nimport { defaultWalletKeyId, isDefined, whenNetwork } from '@leather.io/utils';\n\nimport { BtcSignerNetwork, getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport { getTaprootPayment } from './p2tr-address-gen';\n\nexport interface BitcoinAccount {\n type: PaymentTypes;\n derivationPath: string;\n keychain: HDKey;\n accountIndex: number;\n network: BitcoinNetworkModes;\n}\nexport function initBitcoinAccount(derivationPath: string, policy: string): BitcoinAccount {\n const xpub = extractExtendedPublicKeyFromPolicy(policy);\n const network = inferNetworkFromPath(derivationPath);\n return {\n keychain: HDKey.fromExtendedKey(xpub, getHdKeyVersionsFromNetwork(network)),\n network,\n derivationPath,\n type: inferPaymentTypeFromPath(derivationPath),\n accountIndex: extractAccountIndexFromPath(derivationPath),\n };\n}\n\n/**\n * Represents a map of `BitcoinNetworkModes` to `NetworkModes`. While Bitcoin\n * has a number of networks, its often only necessary to consider the higher\n * level concept of mainnet and testnet\n */\nexport const bitcoinNetworkToCoreNetworkMap: Record<BitcoinNetworkModes, NetworkModes> = {\n mainnet: 'mainnet',\n testnet: 'testnet',\n regtest: 'testnet',\n signet: 'testnet',\n};\nexport function bitcoinNetworkModeToCoreNetworkMode(mode: BitcoinNetworkModes) {\n return bitcoinNetworkToCoreNetworkMap[mode];\n}\n\n/**\n * Map representing the \"Coin Type\" section of a derivation path.\n * Consider example below, Coin type is one, thus testnet\n * @example\n * `m/86'/1'/0'/0/0`\n */\nexport const coinTypeMap: Record<NetworkModes, 0 | 1> = {\n mainnet: 0,\n testnet: 1,\n};\n\nexport function getBitcoinCoinTypeIndexByNetwork(network: BitcoinNetworkModes) {\n return coinTypeMap[bitcoinNetworkModeToCoreNetworkMode(network)];\n}\n\nexport function deriveAddressIndexKeychainFromAccount(keychain: HDKey) {\n if (keychain.depth !== DerivationPathDepth.Account)\n throw new Error('Keychain passed is not an account');\n\n return (index: number) => keychain.deriveChild(0).deriveChild(index);\n}\n\nexport function deriveAddressIndexZeroFromAccount(keychain: HDKey) {\n return deriveAddressIndexKeychainFromAccount(keychain)(0);\n}\n\nexport const ecdsaPublicKeyLength = 33;\n\nexport function ecdsaPublicKeyToSchnorr(pubKey: Uint8Array) {\n if (pubKey.byteLength !== ecdsaPublicKeyLength) throw new Error('Invalid public key length');\n return pubKey.slice(1);\n}\n\n// Basically same as above, to remove\nexport const toXOnly = (pubKey: Buffer) => (pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33));\n\nexport function decodeBitcoinTx(tx: string): ReturnType<typeof btc.RawTx.decode> {\n return btc.RawTx.decode(hexToBytes(tx));\n}\n\nexport function getAddressFromOutScript(script: Uint8Array, bitcoinNetwork: BtcSignerNetwork) {\n const outputScript = btc.OutScript.decode(script);\n\n switch (outputScript.type) {\n case 'pkh':\n case 'sh':\n case 'wpkh':\n case 'wsh':\n return btc.Address(bitcoinNetwork).encode({\n type: outputScript.type,\n hash: outputScript.hash,\n });\n case 'tr':\n return btc.Address(bitcoinNetwork).encode({\n type: outputScript.type,\n pubkey: outputScript.pubkey,\n });\n case 'ms':\n return btc.p2ms(outputScript.m, outputScript.pubkeys).address ?? '';\n case 'pk':\n return btc.p2pk(outputScript.pubkey, bitcoinNetwork).address ?? '';\n case 'unknown':\n return 'unknown';\n case 'tr_ms':\n case 'tr_ns':\n default:\n return '';\n }\n}\n\n/**\n * Payment type identifiers, as described by `@scure/btc-signer` library\n */\nexport type BtcSignerLibPaymentTypeIdentifers = 'wpkh' | 'wsh' | 'tr' | 'pkh' | 'sh';\n\nexport const paymentTypeMap: Record<BtcSignerLibPaymentTypeIdentifers, PaymentTypes> = {\n wpkh: 'p2wpkh',\n wsh: 'p2wpkh-p2sh',\n tr: 'p2tr',\n pkh: 'p2pkh',\n sh: 'p2sh',\n};\n\nexport function btcSignerLibPaymentTypeToPaymentTypeMap(\n payment: BtcSignerLibPaymentTypeIdentifers\n) {\n return paymentTypeMap[payment];\n}\n\nexport function isBtcSignerLibPaymentType(\n payment: string\n): payment is BtcSignerLibPaymentTypeIdentifers {\n return payment in paymentTypeMap;\n}\n\nexport function parseKnownPaymentType(payment: BtcSignerLibPaymentTypeIdentifers | PaymentTypes) {\n return isBtcSignerLibPaymentType(payment)\n ? btcSignerLibPaymentTypeToPaymentTypeMap(payment)\n : payment;\n}\n\nexport type PaymentTypeMap<T> = Record<PaymentTypes, T>;\nexport function whenPaymentType(mode: PaymentTypes | BtcSignerLibPaymentTypeIdentifers) {\n return <T extends unknown>(paymentMap: PaymentTypeMap<T>): T =>\n paymentMap[parseKnownPaymentType(mode)];\n}\n\n/**\n * Infers the Bitcoin payment type from the derivation path.\n * Below we see path has 86 in it, per convention, this refers to taproot payments\n * @example\n * `m/86'/1'/0'/0/0`\n */\nexport function inferPaymentTypeFromPath(path: string): PaymentTypes {\n if (path.startsWith('m/84')) return 'p2wpkh';\n if (path.startsWith('m/86')) return 'p2tr';\n if (path.startsWith('m/44')) return 'p2pkh';\n throw new Error(`Unable to infer payment type from path=${path}`);\n}\n\nexport function inferNetworkFromPath(path: string): NetworkModes {\n return path.split('/')[2].startsWith('0') ? 'mainnet' : 'testnet';\n}\n\nexport function extractExtendedPublicKeyFromPolicy(policy: string) {\n return policy.split(']')[1];\n}\n\nexport function createWalletIdDecoratedPath(policy: string, walletId: string) {\n return policy.split(']')[0].replace('[', '').replace('m', walletId);\n}\n\n// Primarily used to get the correct `Version` when passing Ledger Bitcoin\n// extended public keys to the HDKey constructor\nexport function getHdKeyVersionsFromNetwork(network: NetworkModes) {\n return whenNetwork(network)({\n mainnet: undefined,\n testnet: {\n private: 0x00000000,\n public: 0x043587cf,\n } as Versions,\n });\n}\n\nexport function getBitcoinInputAddress(input: TransactionInput, bitcoinNetwork: BtcSignerNetwork) {\n if (isDefined(input.witnessUtxo))\n return getAddressFromOutScript(input.witnessUtxo.script, bitcoinNetwork);\n if (isDefined(input.nonWitnessUtxo) && isDefined(input.index))\n return getAddressFromOutScript(\n input.nonWitnessUtxo.outputs[input.index]?.script,\n bitcoinNetwork\n );\n return '';\n}\n\nexport function getInputPaymentType(\n input: TransactionInput,\n network: BitcoinNetworkModes\n): PaymentTypes {\n const address = getBitcoinInputAddress(input, getBtcSignerLibNetworkConfigByMode(network));\n if (address === '') throw new Error('Input address cannot be empty');\n if (address.startsWith('bc1p') || address.startsWith('tb1p') || address.startsWith('bcrt1p'))\n return 'p2tr';\n if (address.startsWith('bc1q') || address.startsWith('tb1q') || address.startsWith('bcrt1q'))\n return 'p2wpkh';\n throw new Error('Unable to infer payment type from input address');\n}\n\n// Ledger wallets are keyed by their derivation path. To reuse the look up logic\n// between payment types, this factory fn accepts a fn that generates the path\nexport function lookUpLedgerKeysByPath(\n getDerivationPath: (network: BitcoinNetworkModes, accountIndex: number) => string\n) {\n return (\n ledgerKeyMap: Record<string, { policy: string } | undefined>,\n network: BitcoinNetworkModes\n ) =>\n (accountIndex: number) => {\n const path = getDerivationPath(network, accountIndex);\n // Single wallet mode, hardcoded default walletId\n const account = ledgerKeyMap[path.replace('m', defaultWalletKeyId)];\n if (!account) return;\n return initBitcoinAccount(path, account.policy);\n };\n}\n\nexport interface GetTaprootAddressArgs {\n index: number;\n keychain?: HDKey;\n network: BitcoinNetworkModes;\n}\nexport function getTaprootAddress({ index, keychain, network }: GetTaprootAddressArgs) {\n if (!keychain) throw new Error('Expected keychain to be provided');\n\n if (keychain.depth !== DerivationPathDepth.Account)\n throw new Error('Expects keychain to be on the account index');\n\n const addressIndex = deriveAddressIndexKeychainFromAccount(keychain)(index);\n\n if (!addressIndex.publicKey) {\n throw new Error('Expected publicKey to be defined');\n }\n\n const payment = getTaprootPayment(addressIndex.publicKey, network);\n\n if (!payment.address) throw new Error('Expected address to be defined');\n\n return payment.address;\n}\n\n/**\n * @deprecated\n * Use `deriveRootBip32Keychain` in `@leather.io/crypto` instead\n */\nexport function mnemonicToRootNode(secretKey: string) {\n const seed = mnemonicToSeedSync(secretKey);\n return HDKey.fromMasterSeed(seed);\n}\n\nexport function getPsbtTxInputs(psbtTx: btc.Transaction): TransactionInput[] {\n const inputsLength = psbtTx.inputsLength;\n const inputs: TransactionInput[] = [];\n for (let i = 0; i < inputsLength; i++) inputs.push(psbtTx.getInput(i));\n return inputs;\n}\n\nexport function getPsbtTxOutputs(psbtTx: btc.Transaction): TransactionOutput[] {\n const outputsLength = psbtTx.outputsLength;\n const outputs: TransactionOutput[] = [];\n for (let i = 0; i < outputsLength; i++) outputs.push(psbtTx.getOutput(i));\n return outputs;\n}\n","import * as bitcoinJs from 'bitcoinjs-lib';\n\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\n// See this PR https://github.com/paulmillr/@scure/btc-signer/pull/15\n// Atttempting to add these directly to the library\nexport interface BtcSignerNetwork {\n bech32: string;\n pubKeyHash: number;\n scriptHash: number;\n wif: number;\n}\n\nconst bitcoinMainnet: BtcSignerNetwork = {\n bech32: 'bc',\n pubKeyHash: 0x00,\n scriptHash: 0x05,\n wif: 0x80,\n};\n\nconst bitcoinTestnet: BtcSignerNetwork = {\n bech32: 'tb',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n};\n\nconst bitcoinRegtest: BtcSignerNetwork = {\n bech32: 'bcrt',\n pubKeyHash: 0x6f,\n scriptHash: 0xc4,\n wif: 0xef,\n};\n\nconst btcSignerLibNetworks: Record<BitcoinNetworkModes, BtcSignerNetwork> = {\n mainnet: bitcoinMainnet,\n testnet: bitcoinTestnet,\n regtest: bitcoinRegtest,\n // Signet originally was going to have its own prefix but authors decided to\n // copy testnet\n signet: bitcoinTestnet,\n};\n\nexport function getBtcSignerLibNetworkConfigByMode(network: BitcoinNetworkModes) {\n return btcSignerLibNetworks[network];\n}\n\nconst bitcoinJsLibNetworks: Record<BitcoinNetworkModes, bitcoinJs.Network> = {\n mainnet: bitcoinJs.networks.bitcoin,\n testnet: bitcoinJs.networks.testnet,\n regtest: bitcoinJs.networks.regtest,\n signet: bitcoinJs.networks.testnet,\n};\n\nexport function getBitcoinJsLibNetworkConfigByMode(network: BitcoinNetworkModes) {\n return bitcoinJsLibNetworks[network];\n}\n","import { HDKey } from '@scure/bip32';\nimport * as btc from '@scure/btc-signer';\n\nimport { DerivationPathDepth } from '@leather.io/crypto';\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport {\n BitcoinAccount,\n ecdsaPublicKeyToSchnorr,\n getBitcoinCoinTypeIndexByNetwork,\n} from './bitcoin.utils';\n\nexport function makeTaprootAccountDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number\n) {\n return `m/86'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;\n}\n/** @deprecated Use makeTaprootAccountDerivationPath */\nexport const getTaprootAccountDerivationPath = makeTaprootAccountDerivationPath;\n\nexport function makeTaprootAddressIndexDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number,\n addressIndex: number\n) {\n return makeTaprootAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;\n}\n/** @deprecated Use makeTaprootAddressIndexDerivationPath */\nexport const getTaprootAddressIndexDerivationPath = makeTaprootAddressIndexDerivationPath;\n\nexport function deriveTaprootAccount(keychain: HDKey, network: BitcoinNetworkModes) {\n if (keychain.depth !== DerivationPathDepth.Root)\n throw new Error('Keychain passed is not an account');\n\n return (accountIndex: number): BitcoinAccount => ({\n type: 'p2tr',\n network,\n accountIndex,\n derivationPath: makeTaprootAccountDerivationPath(network, accountIndex),\n keychain: keychain.derive(makeTaprootAccountDerivationPath(network, accountIndex)),\n });\n}\n\nexport function getTaprootPayment(publicKey: Uint8Array, network: BitcoinNetworkModes) {\n return btc.p2tr(\n ecdsaPublicKeyToSchnorr(publicKey),\n undefined,\n getBtcSignerLibNetworkConfigByMode(network)\n );\n}\n\nexport function getTaprootPaymentFromAddressIndex(keychain: HDKey, network: BitcoinNetworkModes) {\n if (keychain.depth !== DerivationPathDepth.AddressIndex)\n throw new Error('Keychain passed is not an address index');\n\n if (!keychain.publicKey) throw new Error('Keychain has no public key');\n\n return getTaprootPayment(keychain.publicKey, network);\n}\n","import { base64 } from '@scure/base';\nimport * as btc from '@scure/btc-signer';\nimport * as bitcoin from 'bitcoinjs-lib';\n\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBitcoinJsLibNetworkConfigByMode } from '../bitcoin.network';\nimport {\n bip322TransactionToSignValues,\n ecPairFromPrivateKey,\n encodeMessageWitnessData,\n hashBip322Message,\n tweakSigner,\n} from './bip322-utils';\n\nexport function createNativeSegwitBitcoinJsSigner(privateKey: Buffer) {\n return ecPairFromPrivateKey(privateKey);\n}\n\nexport function createTaprootBitcoinJsSigner(privateKey: Buffer) {\n return tweakSigner(ecPairFromPrivateKey(privateKey));\n}\n\nexport function createToSpendTx(address: string, message: string, network: BitcoinNetworkModes) {\n const { prevoutHash, prevoutIndex, sequence } = bip322TransactionToSignValues;\n\n const script = bitcoin.address.toOutputScript(\n address,\n getBitcoinJsLibNetworkConfigByMode(network)\n );\n\n const hash = hashBip322Message(message);\n const commands = [0, Buffer.from(hash)];\n const scriptSig = bitcoin.script.compile(commands);\n\n const virtualToSpend = new bitcoin.Transaction();\n virtualToSpend.version = 0;\n virtualToSpend.addInput(Buffer.from(prevoutHash), prevoutIndex, sequence, scriptSig);\n virtualToSpend.addOutput(script, 0);\n return { virtualToSpend, script };\n}\n\nfunction createToSignTx(toSpendTxHex: Buffer, script: Buffer, network: BitcoinNetworkModes) {\n const virtualToSign = new bitcoin.Psbt({ network: getBitcoinJsLibNetworkConfigByMode(network) });\n virtualToSign.setVersion(0);\n const prevTxHash = toSpendTxHex;\n const prevOutIndex = 0;\n const toSignScriptSig = bitcoin.script.compile([bitcoin.script.OPS.OP_RETURN]);\n\n virtualToSign.addInput({\n hash: prevTxHash,\n index: prevOutIndex,\n sequence: 0,\n witnessUtxo: { script, value: 0 },\n });\n\n virtualToSign.addOutput({ script: toSignScriptSig, value: 0 });\n return virtualToSign;\n}\n\ninterface SignBip322MessageSimple {\n address: string;\n message: string;\n network: BitcoinNetworkModes;\n signPsbt(psbt: bitcoin.Psbt): Promise<btc.Transaction>;\n}\nexport async function signBip322MessageSimple(args: SignBip322MessageSimple) {\n const { address, message, network, signPsbt } = args;\n\n const { virtualToSpend, script } = createToSpendTx(address, message, network);\n\n const virtualToSign = createToSignTx(virtualToSpend.getHash(), script, network);\n\n const signedTx = await signPsbt(virtualToSign);\n\n const asBitcoinJsTransaction = bitcoin.Psbt.fromBuffer(Buffer.from(signedTx.toPSBT()));\n\n asBitcoinJsTransaction.finalizeInput(0);\n\n // sign the tx\n // section 5.1\n // github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb\n const toSignTx = asBitcoinJsTransaction.extractTransaction();\n\n const result = encodeMessageWitnessData(toSignTx.ins[0].witness);\n\n return {\n virtualToSpend,\n virtualToSign: toSignTx,\n unencodedSig: result,\n signature: base64.encode(result),\n };\n}\n","import { HDKey } from '@scure/bip32';\nimport * as btc from '@scure/btc-signer';\n\nimport { DerivationPathDepth } from '@leather.io/crypto';\nimport { BitcoinNetworkModes } from '@leather.io/models';\n\nimport { getBtcSignerLibNetworkConfigByMode } from './bitcoin.network';\nimport {\n BitcoinAccount,\n deriveAddressIndexZeroFromAccount,\n getBitcoinCoinTypeIndexByNetwork,\n} from './bitcoin.utils';\n\nexport function makeNativeSegwitAccountDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number\n) {\n return `m/84'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;\n}\n/** @deprecated Use makeNativeSegwitAccountDerivationPath */\nexport const getNativeSegwitAccountDerivationPath = makeNativeSegwitAccountDerivationPath;\n\nexport function makeNativeSegwitAddressIndexDerivationPath(\n network: BitcoinNetworkModes,\n accountIndex: number,\n addressIndex: number\n) {\n return makeNativeSegwitAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;\n}\n/** @deprecated Use makeNativeSegwitAddressIndexDerivationPath */\nexport const getNativeSegwitAddressIndexDerivationPath = makeNativeSegwitAddressIndexDerivationPath;\n\nexport function deriveNativeSegwitAccountFromRootKeychain(\n keychain: HDKey,\n network: BitcoinNetworkModes\n) {\n if (keychain.depth !== DerivationPathDepth.Root) throw new Error('Keychain passed is not a root');\n return (accountIndex: number): BitcoinAccount => ({\n type: 'p2wpkh',\n network,\n accountIndex,\n derivationPath: makeNativeSegwitAccountDerivationPath(network, accountIndex),\n keychain: keychain.derive(makeNativeSegwitAccountDerivationPath(network, accountIndex)),\n });\n}\n\nexport function getNativeSegWitPaymentFromAddressIndex(\n keychain: HDKey,\n network: BitcoinNetworkModes\n) {\n if (keychain.depth !== DerivationPathDepth.AddressIndex)\n throw new Error('Keychain passed is not an address index');\n\n if (!keychain.publicKey) throw new Error('Keychain does not have a public key');\n\n return btc.p2wpkh(keychain.publicKey, getBtcSignerLibNetworkConfigByMode(network));\n}\n\ninterface DeriveNativeSegWitReceiveAddressIndexArgs {\n xpub: string;\n network: BitcoinNetworkModes;\n}\nexport function deriveNativeSegWitReceiveAddressIndex({\n xpub,\n network,\n}: DeriveNativeSegWitReceiveAddressIndexArgs) {\n if (!xpub) return;\n const keychain = HDKey.fromExtendedKey(xpub);\n if (!keychain) return;\n const zeroAddressIndex = deriveAddressIndexZeroFromAccount(keychain);\n return getNativeSegWitPaymentFromAddressIndex(zeroAddressIndex, network);\n}\n","import { ripemd160 } from '@noble/hashes/ripemd160';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { base58check } from '@scure/base';\n\nimport { deriveBip39SeedFromMnemonic, deriveRootBip32Keychain } from '@leather.io/crypto';\nimport { NetworkModes } from '@leather.io/models';\n\n/**\n * @deprecated\n * Use `deriveBip39MnemonicFromSeed` from `@leather.io/crypto`\n */\nexport const deriveBtcBip49SeedFromMnemonic = deriveBip39SeedFromMnemonic;\n\n/**\n * @deprecated\n * Use `deriveRootBip32Keychain` from `@leather.io/crypto`\n */\nexport const deriveRootBtcKeychain = deriveRootBip32Keychain;\n\nexport function decodeCompressedWifPrivateKey(key: string) {\n // https://en.bitcoinwiki.org/wiki/Wallet_import_format\n // Decode Compressed WIF format private key\n const compressedWifFormatPrivateKey = base58check(sha256).decode(key);\n // Drop leading network byte, trailing public key SEC format byte\n return compressedWifFormatPrivateKey.slice(1, compressedWifFormatPrivateKey.length - 1);\n}\n\n// https://en.bitcoin.it/wiki/List_of_address_prefixes\nconst payToScriptHashMainnetPrefix = 0x05;\nexport const payToScriptHashTestnetPrefix = 0xc4;\n\nconst payToScriptHashPrefixMap: Record<NetworkModes, number> = {\n mainnet: payToScriptHashMainnetPrefix,\n testnet: payToScriptHashTestnetPrefix,\n};\n\nfunction hash160(input: Uint8Array) {\n return ripemd160(sha256(input));\n}\n\nexport function makePayToScriptHashKeyHash(publicKey: Uint8Array) {\n return hash160(publicKey);\n}\n\nexport function makePayToScriptHashAddressBytes(keyHash: Uint8Array) {\n const redeemScript = Uint8Array.from([\n ...Uint8Array.of(0x00),\n ...Uint8Array.of(keyHash.length),\n ...keyHash,\n ]);\n return hash160(redeemScript);\n}\n\nexport function makePayToScriptHashAddress(addressBytes: Uint8Array, network: NetworkModes) {\n const networkByte = payToScriptHashPrefixMap[network];\n const addressWithPrefix = Uint8Array.from([networkByte, ...addressBytes]);\n return base58check(sha256).encode(addressWithPrefix);\n}\n\nexport function publicKeyToPayToScriptHashAddress(publicKey: Uint8Array, network: NetworkModes) {\n const hash = makePayToScriptHashKeyHash(publicKey);\n const addrBytes = makePayToScriptHashAddressBytes(hash);\n return makePayToScriptHashAddress(addrBytes, network);\n}\n"],"mappings":";AAAA,OAAO,SAAS;AAChB,SAAS,cAAc;AACvB,SAAS,cAAAA,aAAY,mBAAmB;AACxC,YAAY,aAAa;AACzB,SAAS,qBAAqB;AAC9B,SAAS,cAAc;AAGvB,SAAS,gBAAgB;;;ACRzB,SAAS,kBAAkB;AAC3B,SAAS,aAAuB;AAChC,SAAS,0BAA0B;AACnC,YAAYC,UAAS;AAGrB,SAAS,uBAAAC,sBAAqB,mCAAmC;AAGjE,SAAS,oBAAoB,WAAW,mBAAmB;;;ACT3D,YAAY,eAAe;AAa3B,IAAM,iBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,YAAY;AAAA,EACZ,KAAK;AACP;AAEA,IAAM,iBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,YAAY;AAA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SAAuB;AAC9F,QAAM,OAAO,2BAA2B,SAAS;AACjD,QAAM,YAAY,gCAAgC,IAAI;AACtD,SAAO,2BAA2B,WAAW,OAAO;AACtD;","names":["hexToBytes","btc","DerivationPathDepth","DerivationPathDepth","script","address","hexToBytes","bitcoin","address","script","HDKey","btc","DerivationPathDepth","DerivationPathDepth","HDKey","sha256"]}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@leather.io/bitcoin",
|
|
3
3
|
"author": "Leather.io contact@leather.io",
|
|
4
4
|
"description": "Shared bitcoin utilities",
|
|
5
|
-
"version": "0.
|
|
5
|
+
"version": "0.9.1",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://github.com/leather.io/mono/tree/dev/packages/bitcoin",
|
|
8
8
|
"repository": {
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
"bitcoinjs-lib": "6.1.5",
|
|
30
30
|
"ecpair": "2.1.0",
|
|
31
31
|
"varuint-bitcoin": "1.1.2",
|
|
32
|
-
"@leather.io/constants": "0.8.
|
|
33
|
-
"@leather.io/crypto": "1.0.
|
|
34
|
-
"@leather.io/
|
|
35
|
-
"@leather.io/
|
|
32
|
+
"@leather.io/constants": "0.8.2",
|
|
33
|
+
"@leather.io/crypto": "1.0.4",
|
|
34
|
+
"@leather.io/utils": "0.10.2",
|
|
35
|
+
"@leather.io/models": "0.10.2"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@vitest/coverage-istanbul": "0.34.6",
|
|
@@ -41,11 +41,11 @@
|
|
|
41
41
|
"tslib": "2.6.2",
|
|
42
42
|
"tsup": "8.1.0",
|
|
43
43
|
"typescript": "5.4.5",
|
|
44
|
-
"vitest": "0.
|
|
45
|
-
"@leather.io/
|
|
44
|
+
"vitest": "2.0.3",
|
|
45
|
+
"@leather.io/rpc": "2.0.2",
|
|
46
46
|
"@leather.io/eslint-config": "0.6.1",
|
|
47
|
-
"@leather.io/
|
|
48
|
-
"@leather.io/tsconfig-config": "0.5.
|
|
47
|
+
"@leather.io/prettier-config": "0.5.0",
|
|
48
|
+
"@leather.io/tsconfig-config": "0.5.1"
|
|
49
49
|
},
|
|
50
50
|
"keywords": [
|
|
51
51
|
"bitcoin",
|
package/src/bitcoin.utils.ts
CHANGED
|
@@ -34,7 +34,7 @@ export function initBitcoinAccount(derivationPath: string, policy: string): Bitc
|
|
|
34
34
|
/**
|
|
35
35
|
* Represents a map of `BitcoinNetworkModes` to `NetworkModes`. While Bitcoin
|
|
36
36
|
* has a number of networks, its often only necessary to consider the higher
|
|
37
|
-
* level
|
|
37
|
+
* level concept of mainnet and testnet
|
|
38
38
|
*/
|
|
39
39
|
export const bitcoinNetworkToCoreNetworkMap: Record<BitcoinNetworkModes, NetworkModes> = {
|
|
40
40
|
mainnet: 'mainnet',
|
|
@@ -256,6 +256,10 @@ export function getTaprootAddress({ index, keychain, network }: GetTaprootAddres
|
|
|
256
256
|
return payment.address;
|
|
257
257
|
}
|
|
258
258
|
|
|
259
|
+
/**
|
|
260
|
+
* @deprecated
|
|
261
|
+
* Use `deriveRootBip32Keychain` in `@leather.io/crypto` instead
|
|
262
|
+
*/
|
|
259
263
|
export function mnemonicToRootNode(secretKey: string) {
|
|
260
264
|
const seed = mnemonicToSeedSync(secretKey);
|
|
261
265
|
return HDKey.fromMasterSeed(seed);
|
package/src/p2tr-address-gen.ts
CHANGED
|
@@ -11,20 +11,24 @@ import {
|
|
|
11
11
|
getBitcoinCoinTypeIndexByNetwork,
|
|
12
12
|
} from './bitcoin.utils';
|
|
13
13
|
|
|
14
|
-
export function
|
|
14
|
+
export function makeTaprootAccountDerivationPath(
|
|
15
15
|
network: BitcoinNetworkModes,
|
|
16
16
|
accountIndex: number
|
|
17
17
|
) {
|
|
18
18
|
return `m/86'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;
|
|
19
19
|
}
|
|
20
|
+
/** @deprecated Use makeTaprootAccountDerivationPath */
|
|
21
|
+
export const getTaprootAccountDerivationPath = makeTaprootAccountDerivationPath;
|
|
20
22
|
|
|
21
|
-
export function
|
|
23
|
+
export function makeTaprootAddressIndexDerivationPath(
|
|
22
24
|
network: BitcoinNetworkModes,
|
|
23
25
|
accountIndex: number,
|
|
24
26
|
addressIndex: number
|
|
25
27
|
) {
|
|
26
|
-
return
|
|
28
|
+
return makeTaprootAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;
|
|
27
29
|
}
|
|
30
|
+
/** @deprecated Use makeTaprootAddressIndexDerivationPath */
|
|
31
|
+
export const getTaprootAddressIndexDerivationPath = makeTaprootAddressIndexDerivationPath;
|
|
28
32
|
|
|
29
33
|
export function deriveTaprootAccount(keychain: HDKey, network: BitcoinNetworkModes) {
|
|
30
34
|
if (keychain.depth !== DerivationPathDepth.Root)
|
|
@@ -34,8 +38,8 @@ export function deriveTaprootAccount(keychain: HDKey, network: BitcoinNetworkMod
|
|
|
34
38
|
type: 'p2tr',
|
|
35
39
|
network,
|
|
36
40
|
accountIndex,
|
|
37
|
-
derivationPath:
|
|
38
|
-
keychain: keychain.derive(
|
|
41
|
+
derivationPath: makeTaprootAccountDerivationPath(network, accountIndex),
|
|
42
|
+
keychain: keychain.derive(makeTaprootAccountDerivationPath(network, accountIndex)),
|
|
39
43
|
});
|
|
40
44
|
}
|
|
41
45
|
|
|
@@ -11,20 +11,24 @@ import {
|
|
|
11
11
|
getBitcoinCoinTypeIndexByNetwork,
|
|
12
12
|
} from './bitcoin.utils';
|
|
13
13
|
|
|
14
|
-
export function
|
|
14
|
+
export function makeNativeSegwitAccountDerivationPath(
|
|
15
15
|
network: BitcoinNetworkModes,
|
|
16
16
|
accountIndex: number
|
|
17
17
|
) {
|
|
18
18
|
return `m/84'/${getBitcoinCoinTypeIndexByNetwork(network)}'/${accountIndex}'`;
|
|
19
19
|
}
|
|
20
|
+
/** @deprecated Use makeNativeSegwitAccountDerivationPath */
|
|
21
|
+
export const getNativeSegwitAccountDerivationPath = makeNativeSegwitAccountDerivationPath;
|
|
20
22
|
|
|
21
|
-
export function
|
|
23
|
+
export function makeNativeSegwitAddressIndexDerivationPath(
|
|
22
24
|
network: BitcoinNetworkModes,
|
|
23
25
|
accountIndex: number,
|
|
24
26
|
addressIndex: number
|
|
25
27
|
) {
|
|
26
|
-
return
|
|
28
|
+
return makeNativeSegwitAccountDerivationPath(network, accountIndex) + `/0/${addressIndex}`;
|
|
27
29
|
}
|
|
30
|
+
/** @deprecated Use makeNativeSegwitAddressIndexDerivationPath */
|
|
31
|
+
export const getNativeSegwitAddressIndexDerivationPath = makeNativeSegwitAddressIndexDerivationPath;
|
|
28
32
|
|
|
29
33
|
export function deriveNativeSegwitAccountFromRootKeychain(
|
|
30
34
|
keychain: HDKey,
|
|
@@ -35,8 +39,8 @@ export function deriveNativeSegwitAccountFromRootKeychain(
|
|
|
35
39
|
type: 'p2wpkh',
|
|
36
40
|
network,
|
|
37
41
|
accountIndex,
|
|
38
|
-
derivationPath:
|
|
39
|
-
keychain: keychain.derive(
|
|
42
|
+
derivationPath: makeNativeSegwitAccountDerivationPath(network, accountIndex),
|
|
43
|
+
keychain: keychain.derive(makeNativeSegwitAccountDerivationPath(network, accountIndex)),
|
|
40
44
|
});
|
|
41
45
|
}
|
|
42
46
|
|
|
@@ -7,7 +7,7 @@ import { hashP2WPKH } from '@stacks/transactions';
|
|
|
7
7
|
import { BIP32Factory } from 'bip32';
|
|
8
8
|
import * as bitcoin from 'bitcoinjs-lib';
|
|
9
9
|
|
|
10
|
-
import {
|
|
10
|
+
import { deriveBip39SeedFromMnemonic, deriveRootBip32Keychain } from '@leather.io/crypto';
|
|
11
11
|
|
|
12
12
|
import {
|
|
13
13
|
decodeCompressedWifPrivateKey,
|
|
@@ -112,7 +112,7 @@ describe('Bitcoin SegWit (P2WPKH-P2SH) address generation', () => {
|
|
|
112
112
|
let child: HDKey;
|
|
113
113
|
|
|
114
114
|
beforeAll(async () => {
|
|
115
|
-
seed = await
|
|
115
|
+
seed = await deriveBip39SeedFromMnemonic(phrase);
|
|
116
116
|
root = deriveRootBip32Keychain(seed);
|
|
117
117
|
child = root.derive(key.path);
|
|
118
118
|
});
|
|
@@ -2,14 +2,14 @@ import { ripemd160 } from '@noble/hashes/ripemd160';
|
|
|
2
2
|
import { sha256 } from '@noble/hashes/sha256';
|
|
3
3
|
import { base58check } from '@scure/base';
|
|
4
4
|
|
|
5
|
-
import {
|
|
5
|
+
import { deriveBip39SeedFromMnemonic, deriveRootBip32Keychain } from '@leather.io/crypto';
|
|
6
6
|
import { NetworkModes } from '@leather.io/models';
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* @deprecated
|
|
10
10
|
* Use `deriveBip39MnemonicFromSeed` from `@leather.io/crypto`
|
|
11
11
|
*/
|
|
12
|
-
export const deriveBtcBip49SeedFromMnemonic =
|
|
12
|
+
export const deriveBtcBip49SeedFromMnemonic = deriveBip39SeedFromMnemonic;
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* @deprecated
|