@exodus/bip322-js 1.1.0-exodus.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Ken Sze <acken2@outlook.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # BIP322-JS
2
+
3
+ ![Unit Test Status](https://github.com/ACken2/bip322-js/actions/workflows/unit_test.yml/badge.svg)
4
+ [![Coverage Status](https://coveralls.io/repos/github/ACken2/bip322-js/badge.svg?branch=main)](https://coveralls.io/github/ACken2/bip322-js?branch=main)
5
+
6
+ A Javascript library that provides utility functions related to the BIP-322 signature scheme.
7
+ **This is a fork of https://github.com/ACken2/bip322-js with dependencies change in order to reduce audit load.**
8
+ No API changes present at the moment.
9
+
10
+ ## Current status
11
+
12
+ **What else can be improved**:
13
+ - We decided to keep using `bitcoinjs-lib` and take an audit from scratch. ~~Update `@exodus/bitcoinjs-lib` so that the skipped tests in `Verifier.test.js` work.
14
+ A description of the existing challenges available in https://exodusio.slack.com/archives/C05DQN4DW4D/p1695295752637329.~~
15
+ - Replace `@bitcoinerlab/secp256k1` with an audited library.
16
+
17
+ ## Limitations
18
+
19
+ Only P2PKH, P2SH-P2WPKH, P2WPKH, and single-key-spend P2TR are supported in this library.
20
+
21
+ ## Documentation
22
+
23
+ Available at https://acken2.github.io/bip322-js/
24
+
25
+ ## Supported Features
26
+
27
+ 1. Generate raw toSpend and toSign BIP-322 transactions
28
+ 2. Sign a BIP-322 signature using a private key
29
+ 3. Verify a simple BIP-322 signature
30
+
31
+ ## Example
32
+
33
+ ```js
34
+ // Import modules that are useful to you
35
+ const { BIP322, Signer, Verifier } = require('bip322-js');
36
+
37
+ // Signing a BIP-322 signature with a private key
38
+ const privateKey = 'L3VFeEujGtevx9w18HD1fhRbCH67Az2dpCymeRE1SoPK6XQtaN2k';
39
+ const address = 'bc1q9vza2e8x573nczrlzms0wvx3gsqjx7vavgkx0l';
40
+ const message = 'Hello World';
41
+ const signature = Signer.sign(privateKey, address, message);
42
+ console.log(signature);
43
+
44
+ // Verifying a simple BIP-322 signature
45
+ const validity = Verifier.verifySignature(address, message, signature);
46
+ console.log(validity); // True
47
+
48
+ // You can also get the raw unsigned BIP-322 toSpend and toSign transaction directly
49
+ const scriptPubKey = Buffer.from('00142b05d564e6a7a33c087f16e0f730d1440123799d', 'hex');
50
+ const toSpend = BIP322.buildToSpendTx(message, scriptPubKey); // bitcoin.Transaction
51
+ const toSpendTxId = toSpend.getId();
52
+ const toSign = BIP322.buildToSignTx(toSpendTxId, scriptPubKey); // bitcoin.Psbt
53
+ // Do whatever you want to do with the PSBT
54
+ ```
55
+
56
+ More working examples can be found within the unit test for BIP322, Signer, and Verifier.
@@ -0,0 +1,40 @@
1
+ /// <reference types="node" />
2
+ import * as bitcoin from 'bitcoinjs-lib';
3
+ /**
4
+ * Class that handles BIP-322 related operations.
5
+ * Reference: https://github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb
6
+ */
7
+ declare class BIP322 {
8
+ static TAG: Buffer;
9
+ /**
10
+ * Compute the message hash as specified in the BIP-322.
11
+ * The standard is specified in BIP-340 as:
12
+ * The function hashtag(x) where tag is a UTF-8 encoded tag name and x is a byte array returns the 32-byte hash SHA256(SHA256(tag) || SHA256(tag) || x).
13
+ * @param message Message to be hashed
14
+ * @returns Hashed message
15
+ */
16
+ static hashMessage(message: string): any;
17
+ /**
18
+ * Build a to_spend transaction using simple signature in accordance to the BIP-322.
19
+ * @param message Message to be signed using BIP-322
20
+ * @param scriptPublicKey The script public key for the signing wallet
21
+ * @returns Bitcoin transaction that correspond to the to_spend transaction
22
+ */
23
+ static buildToSpendTx(message: string, scriptPublicKey: Buffer): bitcoin.Transaction;
24
+ /**
25
+ * Build a to_sign transaction using simple signature in accordance to the BIP-322.
26
+ * @param toSpendTxId Transaction ID of the to_spend transaction as constructed by buildToSpendTx
27
+ * @param witnessScript The script public key for the signing wallet, or the redeemScript for P2SH-P2WPKH address
28
+ * @param isRedeemScript Set to true if the provided witnessScript is a redeemScript for P2SH-P2WPKH address, default to false
29
+ * @param tapInternalKey Used to set the taproot internal public key of a taproot signing address when provided, default to undefined
30
+ * @returns Ready-to-be-signed bitcoinjs.Psbt transaction
31
+ */
32
+ static buildToSignTx(toSpendTxId: string, witnessScript: Buffer, isRedeemScript?: boolean, tapInternalKey?: Buffer): bitcoin.Psbt;
33
+ /**
34
+ * Encode witness stack in a signed BIP-322 PSBT into its base-64 encoded format.
35
+ * @param signedPsbt Signed PSBT
36
+ * @returns Base-64 encoded witness data
37
+ */
38
+ static encodeWitness(signedPsbt: bitcoin.Psbt): string;
39
+ }
40
+ export default BIP322;
package/dist/BIP322.js ADDED
@@ -0,0 +1,155 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ // Import dependencies
30
+ const create_hash_1 = __importDefault(require("create-hash"));
31
+ const bitcoin = __importStar(require("bitcoinjs-lib"));
32
+ /**
33
+ * Class that handles BIP-322 related operations.
34
+ * Reference: https://github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb
35
+ */
36
+ class BIP322 {
37
+ /**
38
+ * Compute the message hash as specified in the BIP-322.
39
+ * The standard is specified in BIP-340 as:
40
+ * The function hashtag(x) where tag is a UTF-8 encoded tag name and x is a byte array returns the 32-byte hash SHA256(SHA256(tag) || SHA256(tag) || x).
41
+ * @param message Message to be hashed
42
+ * @returns Hashed message
43
+ */
44
+ static hashMessage(message) {
45
+ // Compute the message hash - SHA256(SHA256(tag) || SHA256(tag) || message)
46
+ const tagHasher = (0, create_hash_1.default)('sha256');
47
+ tagHasher.update(this.TAG);
48
+ const tagHash = tagHasher.digest();
49
+ const messageHasher = (0, create_hash_1.default)('sha256');
50
+ messageHasher.update(tagHash);
51
+ messageHasher.update(tagHash);
52
+ messageHasher.update(Buffer.from(message));
53
+ const messageHash = messageHasher.digest();
54
+ return messageHash;
55
+ }
56
+ /**
57
+ * Build a to_spend transaction using simple signature in accordance to the BIP-322.
58
+ * @param message Message to be signed using BIP-322
59
+ * @param scriptPublicKey The script public key for the signing wallet
60
+ * @returns Bitcoin transaction that correspond to the to_spend transaction
61
+ */
62
+ static buildToSpendTx(message, scriptPublicKey) {
63
+ // Create PSBT object for constructing the transaction
64
+ const psbt = new bitcoin.Psbt();
65
+ // Set default value for nVersion and nLockTime
66
+ psbt.setVersion(0); // nVersion = 0
67
+ psbt.setLocktime(0); // nLockTime = 0
68
+ // Compute the message hash - SHA256(SHA256(tag) || SHA256(tag) || message)
69
+ const messageHash = this.hashMessage(message);
70
+ // Construct the scriptSig - OP_0 PUSH32[ message_hash ]
71
+ const scriptSigPartOne = new Uint8Array([0x00, 0x20]); // OP_0 PUSH32
72
+ const scriptSig = new Uint8Array(scriptSigPartOne.length + messageHash.length);
73
+ scriptSig.set(scriptSigPartOne);
74
+ scriptSig.set(messageHash, scriptSigPartOne.length);
75
+ // Set the input
76
+ psbt.addInput({
77
+ hash: '0'.repeat(64),
78
+ index: 0xFFFFFFFF,
79
+ sequence: 0,
80
+ finalScriptSig: Buffer.from(scriptSig),
81
+ witnessScript: Buffer.from([]) // vin[0].scriptWitness = []
82
+ });
83
+ // Set the output
84
+ psbt.addOutput({
85
+ value: 0,
86
+ script: scriptPublicKey // vout[0].scriptPubKey = message_challenge
87
+ });
88
+ // Return transaction
89
+ return psbt.extractTransaction();
90
+ }
91
+ /**
92
+ * Build a to_sign transaction using simple signature in accordance to the BIP-322.
93
+ * @param toSpendTxId Transaction ID of the to_spend transaction as constructed by buildToSpendTx
94
+ * @param witnessScript The script public key for the signing wallet, or the redeemScript for P2SH-P2WPKH address
95
+ * @param isRedeemScript Set to true if the provided witnessScript is a redeemScript for P2SH-P2WPKH address, default to false
96
+ * @param tapInternalKey Used to set the taproot internal public key of a taproot signing address when provided, default to undefined
97
+ * @returns Ready-to-be-signed bitcoinjs.Psbt transaction
98
+ */
99
+ static buildToSignTx(toSpendTxId, witnessScript, isRedeemScript = false, tapInternalKey = undefined) {
100
+ // Create PSBT object for constructing the transaction
101
+ const psbt = new bitcoin.Psbt();
102
+ // Set default value for nVersion and nLockTime
103
+ psbt.setVersion(0); // nVersion = 0
104
+ psbt.setLocktime(0); // nLockTime = 0
105
+ // Set the input
106
+ psbt.addInput({
107
+ hash: toSpendTxId,
108
+ index: 0,
109
+ sequence: 0,
110
+ witnessUtxo: {
111
+ script: witnessScript,
112
+ value: 0
113
+ }
114
+ });
115
+ // Set redeemScript as witnessScript if isRedeemScript
116
+ if (isRedeemScript) {
117
+ psbt.updateInput(0, {
118
+ redeemScript: witnessScript
119
+ });
120
+ }
121
+ // Set tapInternalKey if provided
122
+ if (tapInternalKey) {
123
+ psbt.updateInput(0, {
124
+ tapInternalKey: tapInternalKey
125
+ });
126
+ }
127
+ // Set the output
128
+ psbt.addOutput({
129
+ value: 0,
130
+ script: Buffer.from([0x6a]) // vout[0].scriptPubKey = OP_RETURN
131
+ });
132
+ return psbt;
133
+ }
134
+ /**
135
+ * Encode witness stack in a signed BIP-322 PSBT into its base-64 encoded format.
136
+ * @param signedPsbt Signed PSBT
137
+ * @returns Base-64 encoded witness data
138
+ */
139
+ static encodeWitness(signedPsbt) {
140
+ // Obtain the signed witness data
141
+ const witness = signedPsbt.data.inputs[0].finalScriptWitness;
142
+ // Check if the witness data is present
143
+ if (witness) {
144
+ // Return the base-64 encoded witness stack
145
+ return witness.toString('base64');
146
+ }
147
+ else {
148
+ throw new Error('Cannot encode empty witness stack.');
149
+ }
150
+ }
151
+ }
152
+ // BIP322 message tag
153
+ BIP322.TAG = Buffer.from("BIP0322-signed-message");
154
+ exports.default = BIP322;
155
+ //# sourceMappingURL=BIP322.js.map
@@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CAAC,CAAC;QACH,sDAAsD;QACtD,IAAI,cAAc,EAAE;YAChB,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE;gBAChB,YAAY,EAAE,aAAa;aAC9B,CAAC,CAAC;SACN;QACD,iCAAiC;QACjC,IAAI,cAAc,EAAE;YAChB,IAAI,CAAC,WAAW,CAAC,CAAC,EAAE;gBAChB,cAAc,EAAE,cAAc;aACjC,CAAC,CAAC;SACN;QACD,iBAAiB;QACjB,IAAI,CAAC,SAAS,CAAC;YACX,KAAK,EAAE,CAAC;YACR,MAAM,EAAE,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,mCAAmC;SAClE,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACI,MAAM,CAAC,aAAa,CAAC,UAAwB;QAChD,iCAAiC;QACjC,MAAM,OAAO,GAAG,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC;QAC7D,uCAAuC;QACvC,IAAI,OAAO,EAAE;YACT,2CAA2C;YAC3C,OAAO,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;SACrC;aACI;YACD,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;SACzD;IACL,CAAC;;AAvHD,qBAAqB;AACd,UAAG,GAAG,MAAM,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;AA0HvD,kBAAe,MAAM,CAAC"}
@@ -0,0 +1,25 @@
1
+ /// <reference types="node" />
2
+ import * as bitcoin from 'bitcoinjs-lib';
3
+ /**
4
+ * Class that signs BIP-322 signature using a private key.
5
+ * Reference: https://github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb
6
+ */
7
+ declare class Signer {
8
+ /**
9
+ * Sign a BIP-322 signature from P2WPKH, P2SH-P2WPKH, and single-key-spend P2TR address and its corresponding private key.
10
+ * @param privateKey Private key used to sign the message
11
+ * @param address Address to be signing the message
12
+ * @param message message_challenge to be signed by the address
13
+ * @param network Network that the address is located, defaults to the Bitcoin mainnet
14
+ * @returns BIP-322 simple signature, encoded in base-64
15
+ */
16
+ static sign(privateKey: string, address: string, message: string, network?: bitcoin.Network): string | Buffer;
17
+ /**
18
+ * Check if a given public key is the public key for a claimed address.
19
+ * @param publicKey Public key to be tested
20
+ * @param claimedAddress Address claimed to be derived based on the provided public key
21
+ * @returns True if the claimedAddress can be derived by the provided publicKey, false if otherwise
22
+ */
23
+ private static checkPubKeyCorrespondToAddress;
24
+ }
25
+ export default Signer;
package/dist/Signer.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ // Import dependencies
30
+ const BIP322_1 = __importDefault(require("./BIP322"));
31
+ const ecpair_1 = __importDefault(require("ecpair"));
32
+ const helpers_1 = require("./helpers");
33
+ const bitcoin = __importStar(require("bitcoinjs-lib"));
34
+ const secp256k1_1 = __importDefault(require("@bitcoinerlab/secp256k1"));
35
+ const bitcoinMessage = __importStar(require("bitcoinjs-message"));
36
+ /**
37
+ * Class that signs BIP-322 signature using a private key.
38
+ * Reference: https://github.com/LegReq/bip0322-signatures/blob/master/BIP0322_signing.ipynb
39
+ */
40
+ class Signer {
41
+ /**
42
+ * Sign a BIP-322 signature from P2WPKH, P2SH-P2WPKH, and single-key-spend P2TR address and its corresponding private key.
43
+ * @param privateKey Private key used to sign the message
44
+ * @param address Address to be signing the message
45
+ * @param message message_challenge to be signed by the address
46
+ * @param network Network that the address is located, defaults to the Bitcoin mainnet
47
+ * @returns BIP-322 simple signature, encoded in base-64
48
+ */
49
+ static sign(privateKey, address, message, network = bitcoin.networks.bitcoin) {
50
+ // Initialize private key used to sign the transaction
51
+ const ECPair = (0, ecpair_1.default)(secp256k1_1.default);
52
+ let signer = ECPair.fromWIF(privateKey, network);
53
+ // Check if the private key can sign message for the given address
54
+ if (!this.checkPubKeyCorrespondToAddress(signer.publicKey, address)) {
55
+ throw new Error(`Invalid private key provided for signing message for ${address}.`);
56
+ }
57
+ // Handle legacy P2PKH signature
58
+ if (helpers_1.Address.isP2PKH(address)) {
59
+ // For P2PKH address, sign a legacy signature
60
+ // Reference: https://github.com/bitcoinjs/bitcoinjs-message/blob/c43430f4c03c292c719e7801e425d887cbdf7464/README.md?plain=1#L21
61
+ return bitcoinMessage.sign(message, signer.privateKey, signer.compressed);
62
+ }
63
+ // Convert address into corresponding script pubkey
64
+ const scriptPubKey = helpers_1.Address.convertAdressToScriptPubkey(address);
65
+ // Draft corresponding toSpend using the message and script pubkey
66
+ const toSpendTx = BIP322_1.default.buildToSpendTx(message, scriptPubKey);
67
+ // Draft corresponding toSign transaction based on the address type
68
+ let toSignTx;
69
+ if (helpers_1.Address.isP2SH(address)) {
70
+ // P2SH-P2WPKH signing path
71
+ // Derive the P2SH-P2WPKH redeemScript from the corresponding hashed public key
72
+ const redeemScript = bitcoin.payments.p2wpkh({
73
+ hash: bitcoin.crypto.hash160(signer.publicKey),
74
+ network: network
75
+ }).output;
76
+ toSignTx = BIP322_1.default.buildToSignTx(toSpendTx.getId(), redeemScript, true);
77
+ }
78
+ else if (helpers_1.Address.isP2WPKH(address)) {
79
+ // P2WPKH signing path
80
+ toSignTx = BIP322_1.default.buildToSignTx(toSpendTx.getId(), scriptPubKey);
81
+ }
82
+ else {
83
+ // P2TR signing path
84
+ // Extract the taproot internal public key
85
+ const internalPublicKey = signer.publicKey.subarray(1, 33);
86
+ // Tweak the private key for signing, since the output and address uses tweaked key
87
+ // Reference: https://github.com/bitcoinjs/bitcoinjs-lib/blob/1a9119b53bcea4b83a6aa8b948f0e6370209b1b4/test/integration/taproot.spec.ts#L55
88
+ signer = signer.tweak(bitcoin.crypto.taggedHash('TapTweak', signer.publicKey.subarray(1, 33)));
89
+ // Draft a toSign transaction that spends toSpend transaction
90
+ toSignTx = BIP322_1.default.buildToSignTx(toSpendTx.getId(), scriptPubKey, false, internalPublicKey);
91
+ // Set the sighashType to bitcoin.Transaction.SIGHASH_ALL since it defaults to SIGHASH_DEFAULT
92
+ toSignTx.updateInput(0, {
93
+ sighashType: bitcoin.Transaction.SIGHASH_ALL
94
+ });
95
+ }
96
+ // Sign the toSign transaction
97
+ const toSignTxSigned = toSignTx.signAllInputs(signer, [bitcoin.Transaction.SIGHASH_ALL]).finalizeAllInputs();
98
+ // Extract and return the signature
99
+ return BIP322_1.default.encodeWitness(toSignTxSigned);
100
+ }
101
+ /**
102
+ * Check if a given public key is the public key for a claimed address.
103
+ * @param publicKey Public key to be tested
104
+ * @param claimedAddress Address claimed to be derived based on the provided public key
105
+ * @returns True if the claimedAddress can be derived by the provided publicKey, false if otherwise
106
+ */
107
+ static checkPubKeyCorrespondToAddress(publicKey, claimedAddress) {
108
+ // Derive the same address type from the provided public key
109
+ let derivedAddresses;
110
+ if (helpers_1.Address.isP2PKH(claimedAddress)) {
111
+ derivedAddresses = helpers_1.Address.convertPubKeyIntoAddress(publicKey, 'p2pkh');
112
+ }
113
+ else if (helpers_1.Address.isP2SH(claimedAddress)) {
114
+ derivedAddresses = helpers_1.Address.convertPubKeyIntoAddress(publicKey, 'p2sh-p2wpkh');
115
+ }
116
+ else if (helpers_1.Address.isP2WPKH(claimedAddress)) {
117
+ derivedAddresses = helpers_1.Address.convertPubKeyIntoAddress(publicKey, 'p2wpkh');
118
+ }
119
+ else if (helpers_1.Address.isP2TR(claimedAddress)) {
120
+ derivedAddresses = helpers_1.Address.convertPubKeyIntoAddress(publicKey, 'p2tr');
121
+ }
122
+ else {
123
+ throw new Error('Unable to sign BIP-322 message for unsupported address type.'); // Unsupported address type
124
+ }
125
+ // Check if the derived address correspond to the claimedAddress
126
+ return (derivedAddresses.mainnet === claimedAddress) || (derivedAddresses.testnet === claimedAddress);
127
+ }
128
+ }
129
+ exports.default = Signer;
130
+ //# sourceMappingURL=Signer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Signer.js","sourceRoot":"","sources":["../src/Signer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sBAAsB;AACtB,sDAA8B;AAC9B,oDAAmC;AACnC,uCAAoC;AACpC,uDAAyC;AACzC,wEAA0C;AAC1C,kEAAoD;AAEpD;;;GAGG;AACH,MAAM,MAAM;IAER;;;;;;;OAOG;IACI,MAAM,CAAC,IAAI,CAAC,UAAkB,EAAE,OAAe,EAAE,OAAe,EAAE,UAA2B,OAAO,CAAC,QAAQ,CAAC,OAAO;QACxH,sDAAsD;QACtD,MAAM,MAAM,GAAG,IAAA,gBAAa,EAAC,mBAAG,CAAC,CAAC;QAClC,IAAI,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QACjD,kEAAkE;QAClE,IAAI,CAAC,IAAI,CAAC,8BAA8B,CAAC,MAAM,CAAC,SAAS,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O,CAAC,MAAM,CAAC,cAAc,CAAC,EAAE;YACrC,gBAAgB,GAAG,iBAAO,CAAC,wBAAwB,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;SAC1E;aACI;YACD,MAAM,IAAI,KAAK,CAAC,8DAA8D,CAAC,CAAC,CAAC,2BAA2B;SAC/G;QACD,gEAAgE;QAChE,OAAO,CAAC,gBAAgB,CAAC,OAAO,KAAK,cAAc,CAAC,IAAI,CAAC,gBAAgB,CAAC,OAAO,KAAK,cAAc,CAAC,CAAC;IAC1G,CAAC;CAEJ;AAED,kBAAe,MAAM,CAAC"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Class that handles BIP-322 signature verification.
3
+ * Reference: https://github.com/LegReq/bip0322-signatures/blob/master/BIP0322_verification.ipynb
4
+ */
5
+ declare class Verifier {
6
+ /**
7
+ * Verify a BIP-322 signature from P2WPKH, P2SH-P2WPKH, and single-key-spend P2TR address.
8
+ * @param signerAddress Address of the signing address
9
+ * @param message message_challenge signed by the address
10
+ * @param signatureBase64 Signature produced by the signing address
11
+ * @returns True if the provided signature is a valid BIP-322 signature for the given message and address, false if otherwise
12
+ * @throws If the provided signature fails basic validation, or if unsupported address and signature are provided
13
+ */
14
+ static verifySignature(signerAddress: string, message: string, signatureBase64: string): boolean;
15
+ /**
16
+ * Verify a legacy BIP-137 signature.
17
+ * Note that a signature is considered valid for all types of addresses that can be derived from the recovered public key.
18
+ * @param signerAddress Address of the signing address
19
+ * @param message message_challenge signed by the address
20
+ * @param signatureBase64 Signature produced by the signing address
21
+ * @returns True if the provided signature is a valid BIP-137 signature for the given message and address, false if otherwise
22
+ * @throws If the provided signature fails basic validation, or if unsupported address and signature are provided
23
+ */
24
+ private static verifyBIP137Signature;
25
+ /**
26
+ * Compute the hash to be signed for a given P2WPKH BIP-322 toSign transaction.
27
+ * @param toSignTx PSBT instance of the toSign transaction
28
+ * @returns Computed transaction hash that requires signing
29
+ */
30
+ private static getHashForSigP2WPKH;
31
+ /**
32
+ * Compute the hash to be signed for a given P2SH-P2WPKH BIP-322 toSign transaction.
33
+ * @param toSignTx PSBT instance of the toSign transaction
34
+ * @param hashedPubkey Hashed public key of the signing address
35
+ * @returns Computed transaction hash that requires signing
36
+ */
37
+ private static getHashForSigP2SHInP2WPKH;
38
+ /**
39
+ * Compute the hash to be signed for a given P2TR BIP-322 toSign transaction.
40
+ * @param toSignTx PSBT instance of the toSign transaction
41
+ * @param hashType Hash type used to sign the toSign transaction, must be either 0x00 or 0x01
42
+ * @returns Computed transaction hash that requires signing
43
+ * @throws Error if hashType is anything other than 0x00 or 0x01
44
+ */
45
+ private static getHashForSigP2TR;
46
+ }
47
+ export default Verifier;