@atomicfinance/bitcoin-wallet-provider 2.5.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,388 +22,479 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- const provider_1 = __importDefault(require("@atomicfinance/provider"));
25
+ exports.AddressSearchType = void 0;
26
+ const bitcoin_utils_1 = require("@atomicfinance/bitcoin-utils");
27
+ const errors_1 = require("@atomicfinance/errors");
26
28
  const types_1 = require("@atomicfinance/types");
27
- const bitcoin_utils_1 = require("@liquality/bitcoin-utils");
28
- const assert_1 = __importDefault(require("assert"));
29
+ const utils_1 = require("@atomicfinance/utils");
29
30
  const bitcoin = __importStar(require("bitcoinjs-lib"));
30
- const secp256k1_1 = __importDefault(require("secp256k1"));
31
- const FEE_PER_BYTE_FALLBACK = 5;
31
+ const memoizee_1 = __importDefault(require("memoizee"));
32
32
  const ADDRESS_GAP = 20;
33
33
  const NONCHANGE_ADDRESS = 0;
34
34
  const CHANGE_ADDRESS = 1;
35
35
  const NONCHANGE_OR_CHANGE_ADDRESS = 2;
36
- class BitcoinWalletProvider extends provider_1.default {
37
- constructor(network) {
38
- super();
39
- this._network = network;
40
- this._unusedAddressesBlacklist = {};
41
- this._maxAddressesToDerive = 5000;
42
- }
43
- async buildSweepTransactionWithSetOutputs(externalChangeAddress, feePerByte, _outputs, fixedInputs) {
44
- return this._buildSweepTransaction(externalChangeAddress, feePerByte, _outputs, fixedInputs);
45
- }
46
- getUnusedAddressesBlacklist() {
47
- return this._unusedAddressesBlacklist;
48
- }
49
- setUnusedAddressesBlacklist(unusedAddressesBlacklist) {
50
- this._unusedAddressesBlacklist = unusedAddressesBlacklist;
51
- }
52
- setMaxAddressesToDerive(maxAddressesToDerive) {
53
- this._maxAddressesToDerive = maxAddressesToDerive;
54
- }
55
- getMaxAddressesToDerive() {
56
- return this._maxAddressesToDerive;
57
- }
58
- _createMultisigPayment(m, pubkeys) {
59
- if (m > pubkeys.length) {
60
- throw new Error(`not enough keys supplied (got ${pubkeys.length} keys, but need at least ${m} to redeem)`);
36
+ var AddressSearchType;
37
+ (function (AddressSearchType) {
38
+ AddressSearchType[AddressSearchType["EXTERNAL"] = 0] = "EXTERNAL";
39
+ AddressSearchType[AddressSearchType["CHANGE"] = 1] = "CHANGE";
40
+ AddressSearchType[AddressSearchType["EXTERNAL_OR_CHANGE"] = 2] = "EXTERNAL_OR_CHANGE";
41
+ })(AddressSearchType = exports.AddressSearchType || (exports.AddressSearchType = {}));
42
+ exports.default = (superclass) => {
43
+ class BitcoinWalletProvider extends superclass {
44
+ constructor(...args) {
45
+ const options = args[0];
46
+ const { network, baseDerivationPath, addressType = types_1.bitcoin.AddressType.BECH32, } = options;
47
+ const addressTypes = Object.values(types_1.bitcoin.AddressType);
48
+ if (!addressTypes.includes(addressType)) {
49
+ throw new Error(`addressType must be one of ${addressTypes.join(',')}`);
50
+ }
51
+ super(options);
52
+ this._baseDerivationPath = baseDerivationPath;
53
+ this._network = network;
54
+ this._addressType = addressType;
55
+ this._derivationCache = {};
56
+ this._unusedAddressesBlacklist = {};
57
+ this._maxAddressesToDerive = 5000;
61
58
  }
62
- // Create m-of-n multisig
63
- const p2ms = bitcoin.payments.p2ms({
64
- m: m,
65
- pubkeys: pubkeys.map((key) => Buffer.from(key, 'hex')),
66
- network: this._network,
67
- });
68
- // Create p2wsh for multisig
69
- const p2wsh = bitcoin.payments.p2wsh({
70
- redeem: p2ms,
71
- network: this._network,
72
- });
73
- return p2wsh;
74
- }
75
- /**
76
- * Creates a native-segwit multi-signature address (P2MS in P2WSH) with n signatures of m required keys
77
- * https://developer.bitcoin.org/reference/rpc/createmultisig.html
78
- * @param m the number of required signatures
79
- * @param pubkeys n possible pubkeys in total
80
- * @returns a json object containing the `address` and `redeemScript`
81
- */
82
- createMultisig(m, pubkeys) {
83
- const p2wsh = this._createMultisigPayment(m, pubkeys);
84
- return {
85
- address: p2wsh.address,
86
- redeemScript: p2wsh.redeem?.output?.toString('hex'),
87
- };
88
- }
89
- /**
90
- * Creates a PSBT of a native-segwit multi-signature address (P2MS in P2WSH) with n signatures of m required keys
91
- * https://developer.bitcoin.org/reference/rpc/createmultisig.html
92
- * https://developer.bitcoin.org/reference/rpc/createpsbt.html
93
- * @param m the number of required signatures
94
- * @param pubkeys n possible pubkeys in total
95
- * @param inputs the Inputs to the PSBT
96
- * @param ouputs the Outputs to the PSBT
97
- * @returns a base64 encoded psbt string
98
- */
99
- buildMultisigPSBT(m, pubkeys, inputs, outputs) {
100
- assert_1.default(inputs.length > 0, 'no inputs found');
101
- assert_1.default(outputs.length > 0, 'no outputs found');
102
- const p2wsh = this._createMultisigPayment(m, pubkeys);
103
- // Verify pubkeyhash for all inputs matches the p2wsh hash
104
- assert_1.default(inputs.every((input) => p2wsh.output.toString('hex') === input.scriptPubKey), 'address pubkeyhash does not match input scriptPubKey');
105
- // creator
106
- const psbt = new bitcoin.Psbt({ network: this._network });
107
- // updater
108
- inputs.forEach((input) => {
109
- psbt.addInput({
110
- hash: input.txid,
111
- index: input.vout,
112
- witnessUtxo: { script: p2wsh.output, value: input.value },
113
- witnessScript: p2wsh.redeem.output,
114
- });
115
- });
116
- outputs.forEach((output) => {
117
- psbt.addOutput({
118
- address: output.to,
119
- value: output.value,
59
+ getDerivationCache() {
60
+ return this._derivationCache;
61
+ }
62
+ async setDerivationCache(derivationCache) {
63
+ const address = await this.getDerivationPathAddress(Object.keys(derivationCache)[0]);
64
+ if (derivationCache[address.derivationPath].address !== address.address) {
65
+ throw new Error(`derivationCache at ${address.derivationPath} does not match`);
66
+ }
67
+ this._derivationCache = derivationCache;
68
+ }
69
+ sendOptionsToOutputs(transactions) {
70
+ const targets = [];
71
+ transactions.forEach((tx) => {
72
+ if (tx.to && tx.value && tx.value.gt(0)) {
73
+ targets.push({
74
+ address: utils_1.addressToString(tx.to),
75
+ value: tx.value.toNumber(),
76
+ });
77
+ }
78
+ if (tx.data) {
79
+ const scriptBuffer = bitcoin.script.compile([
80
+ bitcoin.script.OPS.OP_RETURN,
81
+ Buffer.from(tx.data, 'hex'),
82
+ ]);
83
+ targets.push({
84
+ value: 0,
85
+ script: scriptBuffer,
86
+ });
87
+ }
120
88
  });
121
- });
122
- return psbt.toBase64();
123
- }
124
- /**
125
- * Update a PSBT with input information from our wallet and then sign inputs that we can sign for
126
- * https://developer.bitcoin.org/reference/rpc/walletprocesspsbt.html
127
- * @param psbt a base64 encoded psbt string (P2WSH only)
128
- * @returns a base64 encoded signed psbt string
129
- */
130
- async walletProcessPSBT(psbtString) {
131
- const psbt = bitcoin.Psbt.fromBase64(psbtString);
132
- await Promise.all(psbt.data.inputs.map(async (input, i) => {
133
- assert_1.default(psbt.getInputType(i).slice(0, 5) === 'p2wsh', 'only accepts P2WSH inputs');
134
- const scriptStack = bitcoin.script.decompile(input.witnessScript);
135
- const pubkeys = scriptStack.filter((data) => Buffer.isBuffer(data) && secp256k1_1.default.publicKeyVerify(data));
136
- await Promise.all(pubkeys.map(async (key) => {
137
- // create address using pubkey
138
- const { address: addressString } = bitcoin.payments.p2wpkh({
139
- pubkey: key,
140
- network: this._network,
141
- });
142
- // Retrieve address object from wallet using address
143
- const address = await this.quickFindAddress([
144
- addressString,
145
- ]);
146
- // exit if address doesn't exist in wallet
147
- if (!address)
148
- return;
149
- // derive keypair
150
- const keyPair = await this.getMethod('keyPair')(address.derivationPath);
151
- // sign PSBT using keypair
152
- psbt.signInput(i, keyPair);
153
- }));
154
- }));
155
- psbt.validateSignaturesOfAllInputs(); // ensure all signatures are valid!
156
- return psbt.toBase64();
157
- }
158
- /**
159
- * Finalize the inputs of a PSBT. If the transaction is fully signed, it will
160
- * produce a network serialized transaction which can be broadcast with sendrawtransaction
161
- * https://developer.bitcoin.org/reference/rpc/finalizepsbt.html
162
- * @param psbt a base64 encoded psbt string
163
- * @returns a json object containing `psbt` in base64, `hex` for transaction and `complete` for if
164
- * the transaction has a complete set of signatures
165
- */
166
- finalizePSBT(psbtString) {
167
- const psbt = bitcoin.Psbt.fromBase64(psbtString);
168
- try {
169
- psbt.validateSignaturesOfAllInputs(); // ensure all signatures are valid!
170
- psbt.finalizeAllInputs();
89
+ return targets;
171
90
  }
172
- catch (error) {
173
- return {
174
- psbt: psbt.toBase64(),
175
- complete: false,
176
- };
91
+ async buildTransaction(output, feePerByte) {
92
+ return this._buildTransaction([output], feePerByte);
177
93
  }
178
- return {
179
- psbt: psbt.toBase64(),
180
- hex: psbt.extractTransaction().toHex(),
181
- complete: true,
182
- };
183
- }
184
- async getUnusedAddress(change = false, numAddressPerCall = 100) {
185
- const addressType = change ? CHANGE_ADDRESS : NONCHANGE_ADDRESS;
186
- const key = change ? 'change' : 'nonChange';
187
- const address = await this._getUsedUnusedAddresses(numAddressPerCall, addressType).then(({ unusedAddress }) => unusedAddress[key]);
188
- this._unusedAddressesBlacklist[address.address] = true;
189
- return address;
190
- }
191
- async _getUsedUnusedAddresses(numAddressPerCall = 100, addressType) {
192
- const usedAddresses = [];
193
- const addressCountMap = { change: 0, nonChange: 0 };
194
- const unusedAddressMap = { change: null, nonChange: null };
195
- let addrList;
196
- let addressIndex = 0;
197
- let changeAddresses = [];
198
- let nonChangeAddresses = [];
199
- /* eslint-disable no-unmodified-loop-condition */
200
- while ((addressType === NONCHANGE_OR_CHANGE_ADDRESS &&
201
- (addressCountMap.change < ADDRESS_GAP ||
202
- addressCountMap.nonChange < ADDRESS_GAP)) ||
203
- (addressType === NONCHANGE_ADDRESS &&
204
- addressCountMap.nonChange < ADDRESS_GAP) ||
205
- (addressType === CHANGE_ADDRESS && addressCountMap.change < ADDRESS_GAP)) {
206
- /* eslint-enable no-unmodified-loop-condition */
207
- addrList = [];
208
- if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
209
- addressType === CHANGE_ADDRESS) &&
210
- addressCountMap.change < ADDRESS_GAP) {
211
- // Scanning for change addr
212
- changeAddresses = await this.client.wallet.getAddresses(addressIndex, numAddressPerCall, true);
213
- addrList = addrList.concat(changeAddresses);
214
- }
215
- else {
216
- changeAddresses = [];
217
- }
218
- if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
219
- addressType === NONCHANGE_ADDRESS) &&
220
- addressCountMap.nonChange < ADDRESS_GAP) {
221
- // Scanning for non change addr
222
- nonChangeAddresses = await this.quickGetAddresses(addressIndex, numAddressPerCall, false);
223
- addrList = addrList.concat(nonChangeAddresses);
94
+ async buildBatchTransaction(outputs) {
95
+ return this._buildTransaction(outputs);
96
+ }
97
+ async _sendTransaction(transactions, feePerByte) {
98
+ const { hex, fee } = await this._buildTransaction(transactions, feePerByte);
99
+ await this.getMethod('sendRawTransaction')(hex);
100
+ return bitcoin_utils_1.normalizeTransactionObject(bitcoin_utils_1.decodeRawTransaction(hex, this._network), fee);
101
+ }
102
+ async sendTransaction(options) {
103
+ return this._sendTransaction(this.sendOptionsToOutputs([options]), options.fee);
104
+ }
105
+ async sendBatchTransaction(transactions) {
106
+ return this._sendTransaction(this.sendOptionsToOutputs(transactions));
107
+ }
108
+ async buildSweepTransaction(externalChangeAddress, feePerByte) {
109
+ return this._buildSweepTransaction(externalChangeAddress, feePerByte);
110
+ }
111
+ async sendSweepTransaction(externalChangeAddress, feePerByte) {
112
+ const { hex, fee } = await this._buildSweepTransaction(utils_1.addressToString(externalChangeAddress), feePerByte);
113
+ await this.getMethod('sendRawTransaction')(hex);
114
+ return bitcoin_utils_1.normalizeTransactionObject(bitcoin_utils_1.decodeRawTransaction(hex, this._network), fee);
115
+ }
116
+ getUnusedAddressesBlacklist() {
117
+ return this._unusedAddressesBlacklist;
118
+ }
119
+ setUnusedAddressesBlacklist(unusedAddressesBlacklist) {
120
+ this._unusedAddressesBlacklist = unusedAddressesBlacklist;
121
+ }
122
+ setMaxAddressesToDerive(maxAddressesToDerive) {
123
+ this._maxAddressesToDerive = maxAddressesToDerive;
124
+ }
125
+ getMaxAddressesToDerive() {
126
+ return this._maxAddressesToDerive;
127
+ }
128
+ async updateTransactionFee(tx, newFeePerByte) {
129
+ const txHash = typeof tx === 'string' ? tx : tx.hash;
130
+ const transaction = (await this.getMethod('getTransactionByHash')(txHash))._raw;
131
+ const fixedInputs = [transaction.vin[0]]; // TODO: should this pick more than 1 input? RBF doesn't mandate it
132
+ const lookupAddresses = transaction.vout.map((vout) => vout.scriptPubKey.addresses[0]);
133
+ const changeAddress = await this.findAddress(lookupAddresses, true);
134
+ const changeOutput = transaction.vout.find((vout) => vout.scriptPubKey.addresses[0] === changeAddress.address);
135
+ let outputs = transaction.vout;
136
+ if (changeOutput) {
137
+ outputs = outputs.filter((vout) => vout.scriptPubKey.addresses[0] !==
138
+ changeOutput.scriptPubKey.addresses[0]);
224
139
  }
225
- const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
226
- for (const address of addrList) {
227
- const isUsed = transactionCounts[address.address] > 0 ||
228
- this._unusedAddressesBlacklist[address.address];
229
- const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
230
- const key = isChangeAddress ? 'change' : 'nonChange';
231
- if (isUsed) {
232
- usedAddresses.push(address);
233
- addressCountMap[key] = 0;
234
- unusedAddressMap[key] = null;
140
+ // TODO more checks?
141
+ const transactions = outputs.map((output) => ({
142
+ address: output.scriptPubKey.addresses[0],
143
+ value: new types_1.BigNumber(output.value).times(1e8).toNumber(),
144
+ }));
145
+ const { hex, fee } = await this._buildTransaction(transactions, newFeePerByte, fixedInputs);
146
+ await this.getMethod('sendRawTransaction')(hex);
147
+ return bitcoin_utils_1.normalizeTransactionObject(bitcoin_utils_1.decodeRawTransaction(hex, this._network), fee);
148
+ }
149
+ async getUnusedAddress(change = false, numAddressPerCall = 100) {
150
+ const addressType = change ? CHANGE_ADDRESS : NONCHANGE_ADDRESS;
151
+ const key = change ? 'change' : 'nonChange';
152
+ const address = await this._getUsedUnusedAddresses(numAddressPerCall, addressType).then(({ unusedAddress }) => unusedAddress[key]);
153
+ this._unusedAddressesBlacklist[address.address] = true;
154
+ return address;
155
+ }
156
+ async _getUsedUnusedAddresses(numAddressPerCall = 100, addressType) {
157
+ const usedAddresses = [];
158
+ const addressCountMap = { change: 0, nonChange: 0 };
159
+ const unusedAddressMap = { change: null, nonChange: null };
160
+ let addrList;
161
+ let addressIndex = 0;
162
+ let changeAddresses = [];
163
+ let nonChangeAddresses = [];
164
+ /* eslint-disable no-unmodified-loop-condition */
165
+ while ((addressType === NONCHANGE_OR_CHANGE_ADDRESS &&
166
+ (addressCountMap.change < ADDRESS_GAP ||
167
+ addressCountMap.nonChange < ADDRESS_GAP)) ||
168
+ (addressType === NONCHANGE_ADDRESS &&
169
+ addressCountMap.nonChange < ADDRESS_GAP) ||
170
+ (addressType === CHANGE_ADDRESS && addressCountMap.change < ADDRESS_GAP)) {
171
+ /* eslint-enable no-unmodified-loop-condition */
172
+ addrList = [];
173
+ if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
174
+ addressType === CHANGE_ADDRESS) &&
175
+ addressCountMap.change < ADDRESS_GAP) {
176
+ // Scanning for change addr
177
+ changeAddresses = await this.client.wallet.getAddresses(addressIndex, numAddressPerCall, true);
178
+ addrList = addrList.concat(changeAddresses);
235
179
  }
236
180
  else {
237
- addressCountMap[key]++;
238
- if (!unusedAddressMap[key]) {
239
- unusedAddressMap[key] = address;
181
+ changeAddresses = [];
182
+ }
183
+ if ((addressType === NONCHANGE_OR_CHANGE_ADDRESS ||
184
+ addressType === NONCHANGE_ADDRESS) &&
185
+ addressCountMap.nonChange < ADDRESS_GAP) {
186
+ // Scanning for non change addr
187
+ nonChangeAddresses = await this.getAddresses(addressIndex, numAddressPerCall, false);
188
+ addrList = addrList.concat(nonChangeAddresses);
189
+ }
190
+ const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
191
+ for (const address of addrList) {
192
+ const isUsed = transactionCounts[address.address] > 0 ||
193
+ this._unusedAddressesBlacklist[address.address];
194
+ const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
195
+ const key = isChangeAddress ? 'change' : 'nonChange';
196
+ if (isUsed) {
197
+ usedAddresses.push(address);
198
+ addressCountMap[key] = 0;
199
+ unusedAddressMap[key] = null;
200
+ }
201
+ else {
202
+ addressCountMap[key]++;
203
+ if (!unusedAddressMap[key]) {
204
+ unusedAddressMap[key] = address;
205
+ }
240
206
  }
241
207
  }
208
+ addressIndex += numAddressPerCall;
242
209
  }
243
- addressIndex += numAddressPerCall;
210
+ let firstUnusedAddress;
211
+ const indexNonChange = unusedAddressMap.nonChange
212
+ ? unusedAddressMap.nonChange.index
213
+ : Infinity;
214
+ const indexChange = unusedAddressMap.change
215
+ ? unusedAddressMap.change.index
216
+ : Infinity;
217
+ if (indexNonChange <= indexChange)
218
+ firstUnusedAddress = unusedAddressMap.nonChange;
219
+ else
220
+ firstUnusedAddress = unusedAddressMap.change;
221
+ return {
222
+ usedAddresses,
223
+ unusedAddress: unusedAddressMap,
224
+ firstUnusedAddress,
225
+ };
244
226
  }
245
- let firstUnusedAddress;
246
- const indexNonChange = unusedAddressMap.nonChange
247
- ? unusedAddressMap.nonChange.index
248
- : Infinity;
249
- const indexChange = unusedAddressMap.change
250
- ? unusedAddressMap.change.index
251
- : Infinity;
252
- if (indexNonChange <= indexChange)
253
- firstUnusedAddress = unusedAddressMap.nonChange;
254
- else
255
- firstUnusedAddress = unusedAddressMap.change;
256
- return {
257
- usedAddresses,
258
- unusedAddress: unusedAddressMap,
259
- firstUnusedAddress,
260
- };
261
- }
262
- async sendSweepTransactionWithSetOutputs(externalChangeAddress, feePerByte, _outputs, fixedInputs) {
263
- const { hex, fee } = await this._buildSweepTransaction(externalChangeAddress, feePerByte, _outputs, fixedInputs);
264
- await this.getMethod('sendRawTransaction')(hex);
265
- return bitcoin_utils_1.normalizeTransactionObject(bitcoin_utils_1.decodeRawTransaction(hex, this._network), fee);
266
- }
267
- async _buildSweepTransaction(externalChangeAddress, feePerByte, _outputs = [], fixedInputs) {
268
- const _feePerByte = feePerByte ||
269
- (await this.getMethod('getFeePerByte')()) ||
270
- FEE_PER_BYTE_FALLBACK;
271
- const inputs = [];
272
- const outputs = [];
273
- try {
274
- const inputsForAmount = await this.getMethod('getInputsForAmount')(_outputs, _feePerByte, fixedInputs, 100, true);
275
- if (inputsForAmount.change) {
276
- throw Error('There should not be any change for sweeping transaction');
227
+ async getWalletAddress(address) {
228
+ const foundAddress = await this.findAddress([address]);
229
+ if (foundAddress)
230
+ return foundAddress;
231
+ throw new Error('Wallet does not contain address');
232
+ }
233
+ getAddressFromPublicKey(publicKey) {
234
+ return this.getPaymentVariantFromPublicKey(publicKey).address;
235
+ }
236
+ getPaymentVariantFromPublicKey(publicKey) {
237
+ if (this._addressType === types_1.bitcoin.AddressType.LEGACY) {
238
+ return bitcoin.payments.p2pkh({
239
+ pubkey: publicKey,
240
+ network: this._network,
241
+ });
242
+ }
243
+ else if (this._addressType === types_1.bitcoin.AddressType.P2SH_SEGWIT) {
244
+ return bitcoin.payments.p2sh({
245
+ redeem: bitcoin.payments.p2wpkh({
246
+ pubkey: publicKey,
247
+ network: this._network,
248
+ }),
249
+ network: this._network,
250
+ });
251
+ }
252
+ else if (this._addressType === types_1.bitcoin.AddressType.BECH32) {
253
+ return bitcoin.payments.p2wpkh({
254
+ pubkey: publicKey,
255
+ network: this._network,
256
+ });
277
257
  }
278
- inputs.push(...(inputsForAmount.inputs || []));
279
- outputs.push(...(inputsForAmount.outputs || []));
280
258
  }
281
- catch (e) {
282
- if (fixedInputs.length === 0) {
283
- throw Error(`Inputs for amount doesn't exist and no fixedInputs provided`);
259
+ async getDerivationPathAddress(path) {
260
+ if (path in this._derivationCache) {
261
+ return this._derivationCache[path];
284
262
  }
285
- const inputsForAmount = await this._getInputForAmountWithoutUtxoCheck(_outputs, _feePerByte, fixedInputs);
286
- inputs.push(...(inputsForAmount.inputs.map((utxo) => types_1.Input.fromUTXO(utxo)) || []));
287
- outputs.push(...(inputsForAmount.outputs || []));
263
+ const baseDerivationNode = await this.baseDerivationNode();
264
+ const subPath = path.replace(this._baseDerivationPath + '/', '');
265
+ const publicKey = baseDerivationNode.derivePath(subPath).publicKey;
266
+ const address = this.getAddressFromPublicKey(publicKey);
267
+ const addressObject = new types_1.Address({
268
+ address,
269
+ publicKey: publicKey.toString('hex'),
270
+ derivationPath: path,
271
+ });
272
+ this._derivationCache[path] = addressObject;
273
+ return addressObject;
288
274
  }
289
- _outputs.forEach((output) => {
290
- const spliceIndex = outputs.findIndex((sweepOutput) => output.value === sweepOutput.value);
291
- outputs.splice(spliceIndex, 1);
292
- });
293
- _outputs.push({
294
- to: externalChangeAddress,
295
- value: outputs[0].value,
296
- });
297
- return this._buildTransactionWithoutUtxoCheck(_outputs, _feePerByte, inputs);
298
- }
299
- _getInputForAmountWithoutUtxoCheck(_outputs, _feePerByte, fixedInputs) {
300
- const utxoBalance = fixedInputs.reduce((a, b) => a + (b['value'] || 0), 0);
301
- const outputBalance = _outputs.reduce((a, b) => a + (b['value'] || 0), 0);
302
- const amountToSend = utxoBalance -
303
- _feePerByte * ((_outputs.length + 1) * 39 + fixedInputs.length * 153); // todo better calculation
304
- const targets = _outputs.map((target, i) => ({
305
- id: 'main',
306
- value: target.value,
307
- }));
308
- if (amountToSend - outputBalance > 0) {
309
- targets.push({ id: 'main', value: amountToSend - outputBalance });
275
+ /**
276
+ * getAddresses is an optimized version of upstream CAL's getAddresses.
277
+ * It removes the call to `asyncSetImmediate()`, speeding up the function by a factor of 6x.
278
+ *
279
+ * @param startingIndex
280
+ * @param numAddresses
281
+ * @param change
282
+ * @returns {Promise<Address[]>}
283
+ */
284
+ async getAddresses(startingIndex = 0, numAddresses = 1, change = false) {
285
+ if (numAddresses < 1) {
286
+ throw new Error('You must return at least one address');
287
+ }
288
+ const addresses = [];
289
+ const lastIndex = startingIndex + numAddresses;
290
+ const changeVal = change ? '1' : '0';
291
+ for (let currentIndex = startingIndex; currentIndex < lastIndex; currentIndex++) {
292
+ const subPath = changeVal + '/' + currentIndex;
293
+ const path = this._baseDerivationPath + '/' + subPath;
294
+ const addressObject = await this.getDerivationPathAddress(path);
295
+ addresses.push(addressObject);
296
+ }
297
+ return addresses;
310
298
  }
311
- return bitcoin_utils_1.selectCoins(fixedInputs, targets, Math.ceil(_feePerByte), fixedInputs);
312
- }
313
- async _buildTransactionWithoutUtxoCheck(outputs, feePerByte, fixedInputs) {
314
- const network = this._network;
315
- const { fee } = this._getInputForAmountWithoutUtxoCheck(outputs, feePerByte, fixedInputs);
316
- const inputs = fixedInputs;
317
- const txb = new bitcoin.TransactionBuilder(network);
318
- for (const output of outputs) {
319
- const to = output.to; // Allow for OP_RETURN
320
- txb.addOutput(to, output.value);
299
+ /**
300
+ * findAddress is an optimized version of upstream CAL's findAddress.
301
+ *
302
+ * It searches through both change and non-change addresses (if change arg is not provided) each iteration.
303
+ *
304
+ * This is in contrast to the original findAddress function which searches
305
+ * through all non-change addresses before moving on to change addresses.
306
+ *
307
+ * @param addresses
308
+ * @returns {Promise<Address>}
309
+ */
310
+ async findAddress(addresses, change = null) {
311
+ const addressesPerCall = 20;
312
+ let index = 0;
313
+ while (index < this._maxAddressesToDerive) {
314
+ const walletAddresses = [];
315
+ if (change === null || change === false) {
316
+ walletAddresses.push(...(await this.getAddresses(index, addressesPerCall, false)));
317
+ }
318
+ if (change === null || change === true) {
319
+ walletAddresses.push(...(await this.getAddresses(index, addressesPerCall, true)));
320
+ }
321
+ const walletAddress = walletAddresses.find((walletAddr) => addresses.find((addr) => walletAddr.address === addr));
322
+ if (walletAddress) {
323
+ // Increment max addresses to derive by 100 if found within 100 addresses of maxAddressesToDerive
324
+ this._maxAddressesToDerive = Math.max(this._maxAddressesToDerive, index + 100);
325
+ return walletAddress;
326
+ }
327
+ index += addressesPerCall;
328
+ }
321
329
  }
322
- const prevOutScriptType = 'p2wpkh';
323
- for (let i = 0; i < inputs.length; i++) {
324
- const wallet = await this.getMethod('getWalletAddress')(inputs[i].address);
325
- const keyPair = await this.getMethod('keyPair')(wallet.derivationPath);
326
- const paymentVariant = this.getMethod('getPaymentVariantFromPublicKey')(keyPair.publicKey);
327
- txb.addInput(inputs[i].txid, inputs[i].vout, 0, paymentVariant.output);
330
+ async getUsedAddresses(numAddressPerCall = 100) {
331
+ return this._getUsedUnusedAddresses(numAddressPerCall, AddressSearchType.EXTERNAL_OR_CHANGE).then(({ usedAddresses }) => usedAddresses);
328
332
  }
329
- for (let i = 0; i < inputs.length; i++) {
330
- const wallet = await this.getMethod('getWalletAddress')(inputs[i].address);
331
- const keyPair = await this.getMethod('keyPair')(wallet.derivationPath);
332
- const paymentVariant = this.getMethod('getPaymentVariantFromPublicKey')(keyPair.publicKey);
333
- const needsWitness = true;
334
- const signParams = {
335
- prevOutScriptType,
336
- vin: i,
337
- keyPair,
338
- witnessValue: 0,
333
+ async withCachedUtxos(func) {
334
+ const originalGetMethod = this.getMethod;
335
+ const memoizedGetFeePerByte = memoizee_1.default(this.getMethod('getFeePerByte'), {
336
+ primitive: true,
337
+ });
338
+ const memoizedGetUnspentTransactions = memoizee_1.default(this.getMethod('getUnspentTransactions'), { primitive: true });
339
+ const memoizedGetAddressTransactionCounts = memoizee_1.default(this.getMethod('getAddressTransactionCounts'), {
340
+ primitive: true,
341
+ });
342
+ this.getMethod = (method, requestor = this) => {
343
+ if (method === 'getFeePerByte')
344
+ return memoizedGetFeePerByte;
345
+ if (method === 'getUnspentTransactions')
346
+ return memoizedGetUnspentTransactions;
347
+ else if (method === 'getAddressTransactionCounts')
348
+ return memoizedGetAddressTransactionCounts;
349
+ else
350
+ return originalGetMethod.bind(this)(method, requestor);
339
351
  };
340
- if (needsWitness) {
341
- signParams.witnessValue = inputs[i].value;
342
- }
343
- txb.sign(signParams);
352
+ const result = await func.bind(this)();
353
+ this.getMethod = originalGetMethod;
354
+ return result;
344
355
  }
345
- return { hex: txb.build().toHex(), fee };
346
- }
347
- /**
348
- * quickGetAddresses is an optimized version of getAddresses.
349
- * It removes the call to `asyncSetImmediate()`, speeding up the function by a factor of 6x.
350
- *
351
- * @param startingIndex
352
- * @param numAddresses
353
- * @param change
354
- * @returns {Promise<Address[]>}
355
- */
356
- async quickGetAddresses(startingIndex = 0, numAddresses = 1, change = false) {
357
- if (numAddresses < 1) {
358
- throw new Error('You must return at least one address');
356
+ async getTotalFee(opts, max) {
357
+ const targets = this.sendOptionsToOutputs([opts]);
358
+ if (!max) {
359
+ const { fee } = await this.getInputsForAmount(targets, opts.fee);
360
+ return fee;
361
+ }
362
+ else {
363
+ const { fee } = await this.getInputsForAmount(targets.filter((t) => !t.value), opts.fee, [], 100, true);
364
+ return fee;
365
+ }
359
366
  }
360
- const addresses = [];
361
- const lastIndex = startingIndex + numAddresses;
362
- const changeVal = change ? '1' : '0';
363
- // Original wallet provider is fetched to get the base derivation path
364
- const originalProvider = this.client.getProviderForMethod('getAddresses');
365
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
366
- const baseDerivationPath = originalProvider
367
- ._baseDerivationPath;
368
- const getDerivationPathAddressFn = this.client.getMethod('getDerivationPathAddress');
369
- for (let currentIndex = startingIndex; currentIndex < lastIndex; currentIndex++) {
370
- const subPath = changeVal + '/' + currentIndex;
371
- const path = baseDerivationPath + '/' + subPath;
372
- const addressObject = await getDerivationPathAddressFn(path);
373
- addresses.push(addressObject);
367
+ async getTotalFees(transactions, max) {
368
+ const fees = await this.withCachedUtxos(async () => {
369
+ const fees = {};
370
+ for (const tx of transactions) {
371
+ const fee = await this.getTotalFee(tx, max);
372
+ fees[tx.fee] = new types_1.BigNumber(fee);
373
+ }
374
+ return fees;
375
+ });
376
+ return fees;
374
377
  }
375
- return addresses;
376
- }
377
- /**
378
- * quickFindAddress is an optimized version of findAddress.
379
- *
380
- * It searches through both change and non-change addresses each iteration.
381
- *
382
- * This is in contrast to the original findAddress function which searches
383
- * through all non-change addresses before moving on to change addresses.
384
- *
385
- * @param addresses
386
- * @returns {Promise<Address[]>}
387
- */
388
- async quickFindAddress(addresses) {
389
- const addressesPerCall = 20;
390
- let index = 0;
391
- while (index < this._maxAddressesToDerive) {
392
- const walletNonChangeAddresses = await this.quickGetAddresses(index, addressesPerCall, true);
393
- const walletChangeAddresses = await this.quickGetAddresses(index, addressesPerCall, false);
394
- const walletAddresses = [
395
- ...walletNonChangeAddresses,
396
- ...walletChangeAddresses,
397
- ];
398
- const walletAddress = walletAddresses.find((walletAddr) => addresses.find((addr) => walletAddr.address === addr));
399
- if (walletAddress) {
400
- // Increment max addresses to derive by 100 if found within 100 addresses of maxAddressesToDerive
401
- this._maxAddressesToDerive = Math.max(this._maxAddressesToDerive, index + 100);
402
- return walletAddress;
378
+ async getInputsForAmount(_targets, feePerByte, fixedInputs = [], numAddressPerCall = 100, sweep = false) {
379
+ let addressIndex = 0;
380
+ let changeAddresses = [];
381
+ let externalAddresses = [];
382
+ const addressCountMap = {
383
+ change: 0,
384
+ nonChange: 0,
385
+ };
386
+ const feePerBytePromise = this.getMethod('getFeePerByte')();
387
+ let utxos = [];
388
+ while (addressCountMap.change < ADDRESS_GAP ||
389
+ addressCountMap.nonChange < ADDRESS_GAP) {
390
+ let addrList = [];
391
+ if (addressCountMap.change < ADDRESS_GAP) {
392
+ // Scanning for change addr
393
+ changeAddresses = await this.getAddresses(addressIndex, numAddressPerCall, true);
394
+ addrList = addrList.concat(changeAddresses);
395
+ }
396
+ else {
397
+ changeAddresses = [];
398
+ }
399
+ if (addressCountMap.nonChange < ADDRESS_GAP) {
400
+ // Scanning for non change addr
401
+ externalAddresses = await this.getAddresses(addressIndex, numAddressPerCall, false);
402
+ addrList = addrList.concat(externalAddresses);
403
+ }
404
+ const fixedUtxos = [];
405
+ if (fixedInputs.length > 0) {
406
+ for (const input of fixedInputs) {
407
+ const txHex = await this.getMethod('getRawTransactionByHash')(input.txid);
408
+ const tx = bitcoin_utils_1.decodeRawTransaction(txHex, this._network);
409
+ const value = new types_1.BigNumber(tx.vout[input.vout].value)
410
+ .times(1e8)
411
+ .toNumber();
412
+ const address = tx.vout[input.vout].scriptPubKey.addresses[0];
413
+ const walletAddress = await this.getWalletAddress(address);
414
+ const utxo = {
415
+ ...input,
416
+ value,
417
+ address,
418
+ derivationPath: walletAddress.derivationPath,
419
+ };
420
+ fixedUtxos.push(utxo);
421
+ }
422
+ }
423
+ if (!sweep || fixedUtxos.length === 0) {
424
+ const _utxos = await this.getMethod('getUnspentTransactions')(addrList);
425
+ utxos.push(..._utxos.map((utxo) => {
426
+ const addr = addrList.find((a) => a.address === utxo.address);
427
+ return {
428
+ ...utxo,
429
+ derivationPath: addr.derivationPath,
430
+ };
431
+ }));
432
+ }
433
+ else {
434
+ utxos = fixedUtxos;
435
+ }
436
+ const utxoBalance = utxos.reduce((a, b) => a + (b.value || 0), 0);
437
+ const transactionCounts = await this.getMethod('getAddressTransactionCounts')(addrList);
438
+ if (!feePerByte)
439
+ feePerByte = await feePerBytePromise;
440
+ const minRelayFee = await this.getMethod('getMinRelayFee')();
441
+ if (feePerByte < minRelayFee) {
442
+ throw new Error(`Fee supplied (${feePerByte} sat/b) too low. Minimum relay fee is ${minRelayFee} sat/b`);
443
+ }
444
+ let targets;
445
+ if (sweep) {
446
+ const outputBalance = _targets.reduce((a, b) => a + (b['value'] || 0), 0);
447
+ const sweepOutputSize = 39;
448
+ const paymentOutputSize = _targets.filter((t) => t.value && t.address).length * 39;
449
+ const scriptOutputSize = _targets
450
+ .filter((t) => !t.value && t.script)
451
+ .reduce((size, t) => size + 39 + t.script.byteLength, 0);
452
+ const outputSize = sweepOutputSize + paymentOutputSize + scriptOutputSize;
453
+ const inputSize = utxos.length * 153;
454
+ const sweepFee = feePerByte * (inputSize + outputSize);
455
+ const amountToSend = new types_1.BigNumber(utxoBalance).minus(sweepFee);
456
+ targets = _targets.map((target) => ({
457
+ id: 'main',
458
+ value: target.value,
459
+ script: target.script,
460
+ }));
461
+ targets.push({
462
+ id: 'main',
463
+ value: amountToSend.minus(outputBalance).toNumber(),
464
+ });
465
+ }
466
+ else {
467
+ targets = _targets.map((target) => ({
468
+ id: 'main',
469
+ value: target.value,
470
+ script: target.script,
471
+ }));
472
+ }
473
+ const { inputs, outputs, change, fee } = bitcoin_utils_1.selectCoins(utxos, targets, Math.ceil(feePerByte), fixedUtxos);
474
+ if (inputs && outputs) {
475
+ return {
476
+ inputs,
477
+ change,
478
+ outputs,
479
+ fee,
480
+ };
481
+ }
482
+ for (const address of addrList) {
483
+ const isUsed = transactionCounts[address.address];
484
+ const isChangeAddress = changeAddresses.find((a) => address.address === a.address);
485
+ const key = isChangeAddress ? 'change' : 'nonChange';
486
+ if (isUsed) {
487
+ addressCountMap[key] = 0;
488
+ }
489
+ else {
490
+ addressCountMap[key]++;
491
+ }
492
+ }
493
+ addressIndex += numAddressPerCall;
403
494
  }
404
- index += addressesPerCall;
495
+ throw new errors_1.InsufficientBalanceError('Not enough balance');
405
496
  }
406
497
  }
407
- }
408
- exports.default = BitcoinWalletProvider;
498
+ return BitcoinWalletProvider;
499
+ };
409
500
  //# sourceMappingURL=BitcoinWalletProvider.js.map