@airgap/bitcoin 0.13.41-beta.10 → 0.13.41-beta.11

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.
Files changed (36) hide show
  1. package/package.json +8 -6
  2. package/v0/protocol/BitcoinSegwitProtocol.d.ts +1 -0
  3. package/v0/protocol/BitcoinSegwitProtocol.js +22 -15
  4. package/v0/protocol/BitcoinSegwitProtocol.js.map +1 -1
  5. package/v1/data/BitcoinSegwitAddress.d.ts +2 -1
  6. package/v1/data/BitcoinSegwitAddress.js.map +1 -1
  7. package/v1/data/BitcoinTaprootAddress.d.ts +9 -0
  8. package/v1/data/BitcoinTaprootAddress.js +57 -0
  9. package/v1/data/BitcoinTaprootAddress.js.map +1 -0
  10. package/v1/index.d.ts +2 -1
  11. package/v1/index.js +3 -1
  12. package/v1/index.js.map +1 -1
  13. package/v1/module/BitcoinModule.d.ts +1 -1
  14. package/v1/module/BitcoinModule.js +4 -0
  15. package/v1/module/BitcoinModule.js.map +1 -1
  16. package/v1/protocol/BitcoinSegwitProtocol.d.ts +3 -2
  17. package/v1/protocol/BitcoinSegwitProtocol.js +28 -17
  18. package/v1/protocol/BitcoinSegwitProtocol.js.map +1 -1
  19. package/v1/protocol/BitcoinTaprootProtocol.d.ts +56 -0
  20. package/v1/protocol/BitcoinTaprootProtocol.js +806 -0
  21. package/v1/protocol/BitcoinTaprootProtocol.js.map +1 -0
  22. package/v1/serializer/v3/schemas/converter/transaction-converter.d.ts +7 -1
  23. package/v1/serializer/v3/schemas/converter/transaction-converter.js +22 -1
  24. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -1
  25. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-taproot.d.ts +4 -0
  26. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-taproot.js +3 -0
  27. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-taproot.js.map +1 -0
  28. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-taproot.d.ts +3 -0
  29. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-taproot.js +3 -0
  30. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-taproot.js.map +1 -0
  31. package/v1/serializer/v3/schemas/generated/transaction-sign-request-bitcoin-taproot.json +29 -0
  32. package/v1/serializer/v3/schemas/generated/transaction-sign-response-bitcoin-taproot.json +19 -0
  33. package/v1/serializer/v3/serializer-companion.js +26 -4
  34. package/v1/serializer/v3/serializer-companion.js.map +1 -1
  35. package/v1/types/bitcoinjs.d.ts +6 -0
  36. package/v1/types/transaction.d.ts +10 -0
@@ -0,0 +1,806 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
37
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
38
+ return new (P || (P = Promise))(function (resolve, reject) {
39
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
40
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
41
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
42
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
43
+ });
44
+ };
45
+ var __generator = (this && this.__generator) || function (thisArg, body) {
46
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
47
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
48
+ function verb(n) { return function (v) { return step([n, v]); }; }
49
+ function step(op) {
50
+ if (f) throw new TypeError("Generator is already executing.");
51
+ while (_) try {
52
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
53
+ if (y = 0, t) op = [op[0] & 2, t.value];
54
+ switch (op[0]) {
55
+ case 0: case 1: t = op; break;
56
+ case 4: _.label++; return { value: op[1], done: false };
57
+ case 5: _.label++; y = op[1]; op = [0]; continue;
58
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
59
+ default:
60
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
61
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
62
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
63
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
64
+ if (t[2]) _.ops.pop();
65
+ _.trys.pop(); continue;
66
+ }
67
+ op = body.call(thisArg, _);
68
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
69
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
70
+ }
71
+ };
72
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
73
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
74
+ if (ar || !(i in from)) {
75
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
76
+ ar[i] = from[i];
77
+ }
78
+ }
79
+ return to.concat(ar || Array.prototype.slice.call(from));
80
+ };
81
+ var __importDefault = (this && this.__importDefault) || function (mod) {
82
+ return (mod && mod.__esModule) ? mod : { "default": mod };
83
+ };
84
+ Object.defineProperty(exports, "__esModule", { value: true });
85
+ exports.createBitcoinTaprootProtocol = exports.BitcoinTaprootProtocolImpl = void 0;
86
+ var coinlib_core_1 = require("@airgap/coinlib-core");
87
+ var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
88
+ var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
89
+ var errors_1 = require("@airgap/coinlib-core/errors");
90
+ var module_kit_1 = require("@airgap/module-kit");
91
+ var bitcoin = __importStar(require("bitcoinjs-lib"));
92
+ var BitcoinTaprootAddress_1 = require("../data/BitcoinTaprootAddress");
93
+ var common_1 = require("../utils/common");
94
+ var key_1 = require("../utils/key");
95
+ var network_1 = require("../utils/network");
96
+ var BitcoinProtocol_1 = require("./BitcoinProtocol");
97
+ var bip32_1 = require("bip32");
98
+ var tiny_secp256k1_1 = __importDefault(require("tiny-secp256k1"));
99
+ var BitcoinSegwitProtocol_1 = require("./BitcoinSegwitProtocol");
100
+ var crypto_1 = require("@airgap/crypto");
101
+ // Implementation
102
+ var DUST_AMOUNT = 50;
103
+ var BitcoinTaprootProtocolImpl = /** @class */ (function () {
104
+ function BitcoinTaprootProtocolImpl(options, bitcoinJS) {
105
+ if (options === void 0) { options = {}; }
106
+ if (bitcoinJS === void 0) { bitcoinJS = bitcoin; }
107
+ var _a, _b, _c;
108
+ this._isBitcoinProtocol = true;
109
+ this._isBitcoinTaprootProtocol = true;
110
+ this.bip32 = (0, bip32_1.BIP32Factory)(tiny_secp256k1_1.default);
111
+ this.options = (0, BitcoinProtocol_1.createBitcoinProtocolOptions)(options.network);
112
+ this.bitcoinJS = {
113
+ lib: bitcoinJS,
114
+ config: {
115
+ network: (0, network_1.getBitcoinJSNetwork)(this.options.network, bitcoinJS)
116
+ }
117
+ };
118
+ this.segwit = new BitcoinSegwitProtocol_1.BitcoinSegwitProtocolImpl(options);
119
+ this.metadata = __assign(__assign({}, this.segwit.legacy.metadata), { identifier: coinlib_core_1.MainProtocolSymbols.BTC_TAPROOT, name: 'Bitcoin (Taproot)', account: __assign(__assign({}, ((_a = this.segwit.legacy.metadata.account) !== null && _a !== void 0 ? _a : {})), { standardDerivationPath: "m/86'/0'/0'", address: __assign(__assign({}, ((_c = (_b = this.segwit.legacy.metadata.account) === null || _b === void 0 ? void 0 : _b.address) !== null && _c !== void 0 ? _c : {})), { regex: '^bc1[pq][a-z0-9]{39,59}$' }) }) });
120
+ }
121
+ BitcoinTaprootProtocolImpl.prototype.prepareTransactionWithPublicKey = function (publicKey, details, configuration) {
122
+ return __awaiter(this, void 0, void 0, function () {
123
+ return __generator(this, function (_a) {
124
+ switch (publicKey.type) {
125
+ case 'pub':
126
+ return [2 /*return*/, this.prepareTransactionWithNonExtendedPublicKey(publicKey, details, configuration)];
127
+ case 'xpub':
128
+ return [2 /*return*/, this.prepareTransactionWithExtendedPublicKey(publicKey, details, configuration)];
129
+ default:
130
+ (0, coinlib_core_1.assertNever)(publicKey);
131
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Unsupported public key type.');
132
+ }
133
+ return [2 /*return*/];
134
+ });
135
+ });
136
+ };
137
+ BitcoinTaprootProtocolImpl.prototype.prepareTransactionWithNonExtendedPublicKey = function (publicKey, details, configuration) {
138
+ return __awaiter(this, void 0, void 0, function () {
139
+ return __generator(this, function (_a) {
140
+ throw new Error('Method not implemented.');
141
+ });
142
+ });
143
+ };
144
+ BitcoinTaprootProtocolImpl.prototype.getCryptoConfiguration = function () {
145
+ return __awaiter(this, void 0, void 0, function () {
146
+ return __generator(this, function (_a) {
147
+ return [2 /*return*/, this.segwit.getCryptoConfiguration()];
148
+ });
149
+ });
150
+ };
151
+ BitcoinTaprootProtocolImpl.prototype.getKeyPairFromDerivative = function (derivative) {
152
+ return __awaiter(this, void 0, void 0, function () {
153
+ return __generator(this, function (_a) {
154
+ return [2 /*return*/, this.segwit.getKeyPairFromDerivative(derivative)];
155
+ });
156
+ });
157
+ };
158
+ BitcoinTaprootProtocolImpl.prototype.signTransactionWithSecretKey = function (transaction, secretKey) {
159
+ return __awaiter(this, void 0, void 0, function () {
160
+ return __generator(this, function (_a) {
161
+ switch (secretKey.type) {
162
+ case 'priv':
163
+ return [2 /*return*/, this.signTransactionWithNonExtendedSecretKey(transaction, secretKey)];
164
+ case 'xpriv':
165
+ return [2 /*return*/, this.signTransactionWithExtendedSecretKey(transaction, secretKey)];
166
+ default:
167
+ (0, coinlib_core_1.assertNever)(secretKey);
168
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Secret key type not supported.');
169
+ }
170
+ return [2 /*return*/];
171
+ });
172
+ });
173
+ };
174
+ BitcoinTaprootProtocolImpl.prototype.signTransactionWithExtendedSecretKey = function (transaction, secretKey) {
175
+ return __awaiter(this, void 0, void 0, function () {
176
+ var encodedExtendedSecretKey, bip32, decodedPSBT;
177
+ return __generator(this, function (_a) {
178
+ encodedExtendedSecretKey = (0, key_1.convertExtendedSecretKey)(secretKey, { format: 'encoded', type: 'xprv' });
179
+ bip32 = this.bip32.fromBase58(encodedExtendedSecretKey.value);
180
+ decodedPSBT = this.bitcoinJS.lib.Psbt.fromHex(transaction.psbt);
181
+ decodedPSBT.data.inputs.forEach(function (input, index) {
182
+ var _a;
183
+ (_a = input.bip32Derivation) === null || _a === void 0 ? void 0 : _a.forEach(function (deriv) {
184
+ try {
185
+ // This uses the same logic to find child key as the "findWalletByFingerprintDerivationPathAndProtocolIdentifier" method in the Vault
186
+ var cutoffFrom = deriv.path.lastIndexOf("'") || deriv.path.lastIndexOf('h');
187
+ var childPath = deriv.path.substr(cutoffFrom + 2);
188
+ var childNode_1 = bip32.derivePath(childPath);
189
+ // Wrap publicKey as Buffer to match Signer interface
190
+ decodedPSBT.signInput(index, {
191
+ publicKey: Buffer.from(childNode_1.publicKey),
192
+ sign: function (hash, lowR) { return Buffer.from(childNode_1.sign(hash, lowR)); }
193
+ });
194
+ console.log("Signed input ".concat(index, " with path ").concat(deriv.path));
195
+ }
196
+ catch (e) {
197
+ console.log("Error signing input ".concat(index), e);
198
+ }
199
+ });
200
+ });
201
+ return [2 /*return*/, (0, module_kit_1.newSignedTransaction)({ psbt: decodedPSBT.toHex() })];
202
+ });
203
+ });
204
+ };
205
+ BitcoinTaprootProtocolImpl.prototype.signTransactionWithNonExtendedSecretKey = function (transaction, secretKey) {
206
+ return __awaiter(this, void 0, void 0, function () {
207
+ return __generator(this, function (_a) {
208
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Sign with non extended secret key not supported (Taproot).');
209
+ });
210
+ });
211
+ };
212
+ BitcoinTaprootProtocolImpl.prototype.getMetadata = function () {
213
+ return __awaiter(this, void 0, void 0, function () {
214
+ return __generator(this, function (_a) {
215
+ return [2 /*return*/, this.metadata];
216
+ });
217
+ });
218
+ };
219
+ BitcoinTaprootProtocolImpl.prototype.getAddressFromPublicKey = function (publicKey) {
220
+ switch (publicKey.type) {
221
+ case 'pub':
222
+ return this.getAddressFromNonExtendedPublicKey(publicKey);
223
+ case 'xpub':
224
+ return this.getAddressFromExtendedPublicKey(publicKey);
225
+ default:
226
+ (0, coinlib_core_1.assertNever)(publicKey);
227
+ throw new errors_1.UnsupportedError(coinlib_core_1.Domain.BITCOIN, 'Public key type is not supported.');
228
+ }
229
+ };
230
+ BitcoinTaprootProtocolImpl.prototype.getAddressFromExtendedPublicKey = function (extendedPublicKey) {
231
+ return __awaiter(this, void 0, void 0, function () {
232
+ var encodedExtendedPublicKey, payment;
233
+ return __generator(this, function (_a) {
234
+ encodedExtendedPublicKey = (0, key_1.convertExtendedPublicKey)(extendedPublicKey, { format: 'encoded', type: 'xpub' });
235
+ payment = this.bitcoinJS.lib.payments.p2tr({
236
+ internalPubkey: Buffer.from(encodedExtendedPublicKey.value, 'hex').subarray(1, 33),
237
+ network: this.bitcoinJS.config.network
238
+ });
239
+ return [2 /*return*/, BitcoinTaprootAddress_1.BitcoinTaprootAddress.fromPayment(payment).asString()];
240
+ });
241
+ });
242
+ };
243
+ BitcoinTaprootProtocolImpl.prototype.getDetailsFromTransaction = function (transaction, _publicKey) {
244
+ return __awaiter(this, void 0, void 0, function () {
245
+ return __generator(this, function (_a) {
246
+ return [2 /*return*/, this.getDetailsFromPSBT(transaction.psbt, _publicKey)];
247
+ });
248
+ });
249
+ };
250
+ BitcoinTaprootProtocolImpl.prototype.getDetailsFromPSBT = function (psbt, publicKey) {
251
+ var _a, _b;
252
+ return __awaiter(this, void 0, void 0, function () {
253
+ var decodedPSBT, fee, _i, _c, txIn, _d, _e, txOut, alerts, clonedPSBT, amount, changeAddressDatas, changeAddressInfo;
254
+ var _this = this;
255
+ return __generator(this, function (_f) {
256
+ switch (_f.label) {
257
+ case 0:
258
+ decodedPSBT = this.bitcoinJS.lib.Psbt.fromHex(psbt);
259
+ fee = new bignumber_1.default(0);
260
+ for (_i = 0, _c = decodedPSBT.data.inputs; _i < _c.length; _i++) {
261
+ txIn = _c[_i];
262
+ fee = fee.plus(new bignumber_1.default((_b = (_a = txIn.witnessUtxo) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : 0));
263
+ }
264
+ for (_d = 0, _e = decodedPSBT.txOutputs; _d < _e.length; _d++) {
265
+ txOut = _e[_d];
266
+ fee = fee.minus(new bignumber_1.default(txOut.value));
267
+ }
268
+ alerts = [];
269
+ clonedPSBT = decodedPSBT.clone();
270
+ (0, common_1.eachRecursive)(clonedPSBT); // Convert all buffers to hex strings
271
+ amount = (function () {
272
+ if (decodedPSBT.txOutputs.length === 1) {
273
+ return new bignumber_1.default(decodedPSBT.txOutputs[0].value);
274
+ }
275
+ var unknownKeyVals = decodedPSBT.data.globalMap.unknownKeyVals;
276
+ if (unknownKeyVals) {
277
+ var amountArray = unknownKeyVals.filter(function (kv) { return kv.key.equals(Buffer.from('amount')); });
278
+ if (amountArray.length > 0) {
279
+ return new bignumber_1.default(amountArray[0].value.toString());
280
+ }
281
+ }
282
+ var accumulated = new bignumber_1.default(0);
283
+ var useAccumulated = false;
284
+ decodedPSBT.data.outputs.forEach(function (outputKeyValues, index) {
285
+ if (outputKeyValues.unknownKeyVals) {
286
+ var derivationPaths = outputKeyValues.unknownKeyVals
287
+ .filter(function (kv) { return kv.key.equals(Buffer.from('dp')); })
288
+ .map(function (kv) { return kv.value.toString(); });
289
+ if (derivationPaths.length > 0) {
290
+ useAccumulated = true;
291
+ return;
292
+ }
293
+ }
294
+ var output = decodedPSBT.txOutputs[index];
295
+ accumulated = accumulated.plus(output.value);
296
+ });
297
+ if (useAccumulated) {
298
+ return accumulated;
299
+ }
300
+ return decodedPSBT.txOutputs
301
+ .map(function (obj) { return new bignumber_1.default(obj.value); })
302
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); });
303
+ })();
304
+ return [4 /*yield*/, Promise.all(decodedPSBT.data.outputs.map(function (obj, index) { return __awaiter(_this, void 0, void 0, function () {
305
+ var isChangeAddress, isOwned, addressIndex, address, amount, ourGeneratedAddress, getIndexes, ourPublickey, x, ourPublickey, x, ourPublickey;
306
+ return __generator(this, function (_a) {
307
+ switch (_a.label) {
308
+ case 0:
309
+ isChangeAddress = false;
310
+ isOwned = false;
311
+ addressIndex = 0;
312
+ address = decodedPSBT.txOutputs[index].address;
313
+ amount = decodedPSBT.txOutputs[index].value;
314
+ if (!obj.bip32Derivation) return [3 /*break*/, 11];
315
+ isChangeAddress = true;
316
+ getIndexes = obj.bip32Derivation[0].path.split('/');
317
+ if (!(publicKey.type === 'xpub')) return [3 /*break*/, 3];
318
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(publicKey, 1, +getIndexes[getIndexes.length - 1])];
319
+ case 1:
320
+ ourPublickey = _a.sent();
321
+ return [4 /*yield*/, this.getAddressFromPublicKey(ourPublickey)];
322
+ case 2:
323
+ ourGeneratedAddress = _a.sent();
324
+ return [3 /*break*/, 5];
325
+ case 3: return [4 /*yield*/, this.getAddressFromNonExtendedPublicKey(publicKey)];
326
+ case 4:
327
+ ourGeneratedAddress = _a.sent();
328
+ _a.label = 5;
329
+ case 5:
330
+ if (ourGeneratedAddress === address) {
331
+ isOwned = true;
332
+ addressIndex = +getIndexes[getIndexes.length - 1];
333
+ }
334
+ x = 0;
335
+ _a.label = 6;
336
+ case 6:
337
+ if (!(x < 1000)) return [3 /*break*/, 10];
338
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(publicKey, 1, x)];
339
+ case 7:
340
+ ourPublickey = _a.sent();
341
+ return [4 /*yield*/, this.getAddressFromPublicKey(ourPublickey)];
342
+ case 8:
343
+ ourGeneratedAddress = _a.sent();
344
+ if (ourGeneratedAddress === address) {
345
+ isOwned = true;
346
+ addressIndex = x;
347
+ return [3 /*break*/, 10];
348
+ }
349
+ _a.label = 9;
350
+ case 9:
351
+ x++;
352
+ return [3 /*break*/, 6];
353
+ case 10: return [3 /*break*/, 16];
354
+ case 11:
355
+ if (!obj.unknownKeyVals) return [3 /*break*/, 16];
356
+ x = 0;
357
+ _a.label = 12;
358
+ case 12:
359
+ if (!(x < 1000)) return [3 /*break*/, 16];
360
+ isChangeAddress = true;
361
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(publicKey, 1, x)];
362
+ case 13:
363
+ ourPublickey = _a.sent();
364
+ return [4 /*yield*/, this.getAddressFromPublicKey(ourPublickey)];
365
+ case 14:
366
+ ourGeneratedAddress = _a.sent();
367
+ if (ourGeneratedAddress === address) {
368
+ isOwned = true;
369
+ addressIndex = x;
370
+ return [3 /*break*/, 16];
371
+ }
372
+ _a.label = 15;
373
+ case 15:
374
+ x++;
375
+ return [3 /*break*/, 12];
376
+ case 16:
377
+ if (isChangeAddress && isOwned) {
378
+ alerts.push({
379
+ type: 'success',
380
+ title: { type: 'plain', value: '' },
381
+ description: { type: 'plain', value: 'Note: your change address has been verified' },
382
+ icon: undefined,
383
+ actions: undefined
384
+ });
385
+ }
386
+ else if (isChangeAddress && !isOwned) {
387
+ alerts.push({
388
+ type: 'warning',
389
+ title: { type: 'plain', value: '' },
390
+ description: { type: 'plain', value: 'Note: your change address has not been verified' },
391
+ icon: undefined,
392
+ actions: undefined
393
+ });
394
+ }
395
+ return [2 /*return*/, [
396
+ address,
397
+ {
398
+ isChangeAddress: isChangeAddress,
399
+ isOwned: isOwned,
400
+ path: addressIndex === 0 ? '' : "m/86'/0'/0'/1/".concat(addressIndex),
401
+ amount: amount
402
+ }
403
+ ]];
404
+ }
405
+ });
406
+ }); }))];
407
+ case 1:
408
+ changeAddressDatas = _f.sent();
409
+ changeAddressInfo = {};
410
+ changeAddressDatas.forEach(function (changeAddressData) {
411
+ changeAddressInfo[changeAddressData[0]] = changeAddressData[1];
412
+ });
413
+ return [2 /*return*/, [
414
+ {
415
+ from: decodedPSBT.data.inputs.map(function (obj) {
416
+ var _a, _b;
417
+ return (_b = (_a = obj.bip32Derivation) === null || _a === void 0 ? void 0 : _a.map(function (el) {
418
+ return _this.bitcoinJS.lib.payments.p2tr({
419
+ internalPubkey: el.pubkey.subarray(1, 33),
420
+ network: _this.bitcoinJS.lib.networks.bitcoin
421
+ }).address;
422
+ }).join(' ')) !== null && _b !== void 0 ? _b : 'INVALID';
423
+ }),
424
+ to: decodedPSBT.txOutputs.map(function (obj) {
425
+ return obj.address || "Script: ".concat(obj.script.toString('hex')) || 'unknown';
426
+ }),
427
+ isInbound: false,
428
+ amount: (0, module_kit_1.newAmount)(amount, 'blockchain'),
429
+ fee: (0, module_kit_1.newAmount)(fee, 'blockchain'),
430
+ network: this.options.network,
431
+ changeAddressInfo: changeAddressInfo,
432
+ uiAlerts: alerts,
433
+ json: {
434
+ inputTx: (0, common_1.eachRecursive)(clonedPSBT.txInputs),
435
+ outputTx: (0, common_1.eachRecursive)(clonedPSBT.txOutputs),
436
+ inputData: clonedPSBT.data.inputs,
437
+ outputData: clonedPSBT.data.outputs,
438
+ PSBTVersion: clonedPSBT.version,
439
+ PSBTLocktime: clonedPSBT.locktime,
440
+ PSBTGlobalMap: clonedPSBT.data.globalMap,
441
+ rawPSBT: psbt
442
+ }
443
+ }
444
+ ]];
445
+ }
446
+ });
447
+ });
448
+ };
449
+ BitcoinTaprootProtocolImpl.prototype.getNetwork = function () {
450
+ return __awaiter(this, void 0, void 0, function () {
451
+ return __generator(this, function (_a) {
452
+ return [2 /*return*/, this.options.network];
453
+ });
454
+ });
455
+ };
456
+ BitcoinTaprootProtocolImpl.prototype.getTransactionsForPublicKey = function (publicKey, limit, cursor) {
457
+ return this.segwit.getTransactionsForPublicKey(publicKey, limit, cursor);
458
+ };
459
+ BitcoinTaprootProtocolImpl.prototype.getBalanceOfPublicKey = function (publicKey, configuration) {
460
+ return __awaiter(this, void 0, void 0, function () {
461
+ return __generator(this, function (_a) {
462
+ return [2 /*return*/, this.segwit.getBalanceOfPublicKey(publicKey)];
463
+ });
464
+ });
465
+ };
466
+ BitcoinTaprootProtocolImpl.prototype.getTransactionMaxAmountWithPublicKey = function (publicKey, to, configuration) {
467
+ return __awaiter(this, void 0, void 0, function () {
468
+ return __generator(this, function (_a) {
469
+ return [2 /*return*/, this.segwit.getTransactionMaxAmountWithPublicKey(publicKey, to, configuration)];
470
+ });
471
+ });
472
+ };
473
+ BitcoinTaprootProtocolImpl.prototype.getTransactionFeeWithPublicKey = function (publicKey, details, configuration) {
474
+ return __awaiter(this, void 0, void 0, function () {
475
+ return __generator(this, function (_a) {
476
+ return [2 /*return*/, this.segwit.getTransactionFeeWithPublicKey(publicKey, details, configuration)];
477
+ });
478
+ });
479
+ };
480
+ BitcoinTaprootProtocolImpl.prototype.broadcastTransaction = function (transaction) {
481
+ return __awaiter(this, void 0, void 0, function () {
482
+ var hexTransaction, data;
483
+ return __generator(this, function (_a) {
484
+ switch (_a.label) {
485
+ case 0:
486
+ hexTransaction = this.bitcoinJS.lib.Psbt.fromHex(transaction.psbt).finalizeAllInputs().extractTransaction().toHex();
487
+ return [4 /*yield*/, index_1.default.post("".concat(this.options.network.indexerApi, "/api/v2/sendtx/"), hexTransaction)];
488
+ case 1:
489
+ data = (_a.sent()).data;
490
+ return [2 /*return*/, data.result];
491
+ }
492
+ });
493
+ });
494
+ };
495
+ BitcoinTaprootProtocolImpl.prototype.getExtendedKeyPairFromDerivative = function (derivative) {
496
+ return __awaiter(this, void 0, void 0, function () {
497
+ var bip32;
498
+ return __generator(this, function (_a) {
499
+ bip32 = this.derivativeToBip32Node(derivative);
500
+ return [2 /*return*/, {
501
+ secretKey: (0, module_kit_1.newExtendedSecretKey)(bip32.toBase58(), 'encoded'),
502
+ publicKey: (0, key_1.convertExtendedPublicKey)((0, module_kit_1.newExtendedPublicKey)(bip32.neutered().toBase58(), 'encoded'), {
503
+ format: 'encoded',
504
+ type: 'xpub'
505
+ })
506
+ }];
507
+ });
508
+ });
509
+ };
510
+ BitcoinTaprootProtocolImpl.prototype.derivativeToBip32Node = function (derivative) {
511
+ var extendedSecretKey = this.convertCryptoDerivative(derivative);
512
+ return this.bip32.fromBase58(extendedSecretKey.value, this.bitcoinJS.config.network);
513
+ };
514
+ BitcoinTaprootProtocolImpl.prototype.convertCryptoDerivative = function (derivative) {
515
+ var hexNode = (0, crypto_1.encodeDerivative)('hex', __assign(__assign({}, derivative), { secretKey: "00".concat(derivative.secretKey) }));
516
+ var extendedSecretKey = {
517
+ type: 'xpriv',
518
+ format: 'hex',
519
+ value: hexNode.secretKey
520
+ };
521
+ return (0, key_1.convertExtendedSecretKey)(extendedSecretKey, { format: 'encoded', type: 'xprv' });
522
+ };
523
+ BitcoinTaprootProtocolImpl.prototype.deriveFromExtendedSecretKey = function (extendedSecretKey, visibilityIndex, addressIndex) {
524
+ return __awaiter(this, void 0, void 0, function () {
525
+ return __generator(this, function (_a) {
526
+ return [2 /*return*/, this.segwit.deriveFromExtendedSecretKey(extendedSecretKey, visibilityIndex, addressIndex)];
527
+ });
528
+ });
529
+ };
530
+ BitcoinTaprootProtocolImpl.prototype.deriveFromExtendedPublicKey = function (extendedPublicKey, visibilityIndex, addressIndex) {
531
+ return __awaiter(this, void 0, void 0, function () {
532
+ var encodedPublicKey, derivedBip32;
533
+ return __generator(this, function (_a) {
534
+ encodedPublicKey = (0, key_1.convertExtendedPublicKey)(extendedPublicKey, { format: 'encoded', type: 'xpub' });
535
+ derivedBip32 = this.bip32
536
+ .fromBase58(encodedPublicKey.value, this.bitcoinJS.config.network)
537
+ .derive(visibilityIndex)
538
+ .derive(addressIndex);
539
+ return [2 /*return*/, (0, module_kit_1.newPublicKey)(derivedBip32.publicKey.toString(), 'hex')];
540
+ });
541
+ });
542
+ };
543
+ BitcoinTaprootProtocolImpl.prototype.signMessageWithKeyPair = function (message, keyPair) {
544
+ return __awaiter(this, void 0, void 0, function () {
545
+ return __generator(this, function (_a) {
546
+ return [2 /*return*/, this.segwit.signMessageWithKeyPair(message, keyPair)];
547
+ });
548
+ });
549
+ };
550
+ BitcoinTaprootProtocolImpl.prototype.verifyMessageWithPublicKey = function (message, signature, publicKey) {
551
+ return __awaiter(this, void 0, void 0, function () {
552
+ return __generator(this, function (_a) {
553
+ return [2 /*return*/, this.segwit.verifyMessageWithPublicKey(message, signature, publicKey)];
554
+ });
555
+ });
556
+ };
557
+ BitcoinTaprootProtocolImpl.prototype.decryptAsymmetricWithKeyPair = function (payload, keyPair) {
558
+ return __awaiter(this, void 0, void 0, function () {
559
+ return __generator(this, function (_a) {
560
+ return [2 /*return*/, this.segwit.decryptAsymmetricWithKeyPair(payload, keyPair)];
561
+ });
562
+ });
563
+ };
564
+ BitcoinTaprootProtocolImpl.prototype.encryptAsymmetricWithPublicKey = function (payload, publicKey) {
565
+ return __awaiter(this, void 0, void 0, function () {
566
+ return __generator(this, function (_a) {
567
+ return [2 /*return*/, this.segwit.encryptAsymmetricWithPublicKey(payload, publicKey)];
568
+ });
569
+ });
570
+ };
571
+ BitcoinTaprootProtocolImpl.prototype.encryptAESWithSecretKey = function (payload, secretKey) {
572
+ return __awaiter(this, void 0, void 0, function () {
573
+ return __generator(this, function (_a) {
574
+ return [2 /*return*/, this.segwit.encryptAESWithSecretKey(payload, secretKey)];
575
+ });
576
+ });
577
+ };
578
+ BitcoinTaprootProtocolImpl.prototype.decryptAESWithSecretKey = function (payload, secretKey) {
579
+ return this.segwit.decryptAESWithSecretKey(payload, secretKey);
580
+ };
581
+ BitcoinTaprootProtocolImpl.prototype.getTransactionsForAddress = function (address, limit, cursor) {
582
+ return __awaiter(this, void 0, void 0, function () {
583
+ return __generator(this, function (_a) {
584
+ return [2 /*return*/, this.segwit.getTransactionsForAddress(address, limit, cursor)];
585
+ });
586
+ });
587
+ };
588
+ BitcoinTaprootProtocolImpl.prototype.getBalanceOfAddress = function (address, configuration) {
589
+ return __awaiter(this, void 0, void 0, function () {
590
+ return __generator(this, function (_a) {
591
+ return [2 /*return*/, this.segwit.getBalanceOfAddress(address)];
592
+ });
593
+ });
594
+ };
595
+ BitcoinTaprootProtocolImpl.prototype.getTransactionsForAddresses = function (addresses, limit, cursor) {
596
+ return __awaiter(this, void 0, void 0, function () {
597
+ return __generator(this, function (_a) {
598
+ return [2 /*return*/, this.segwit.getTransactionsForAddresses(addresses, limit, cursor)];
599
+ });
600
+ });
601
+ };
602
+ BitcoinTaprootProtocolImpl.prototype.getBalanceOfAddresses = function (addresses, configuration) {
603
+ return __awaiter(this, void 0, void 0, function () {
604
+ return __generator(this, function (_a) {
605
+ return [2 /*return*/, this.segwit.getBalanceOfAddresses(addresses)];
606
+ });
607
+ });
608
+ };
609
+ // Common methods similar to Segwit implementation
610
+ // ... [Include all the common methods from Segwit implementation but modify for Taproot]
611
+ BitcoinTaprootProtocolImpl.prototype.getAddressFromNonExtendedPublicKey = function (publicKey) {
612
+ return __awaiter(this, void 0, void 0, function () {
613
+ var hexPublicKey, payment;
614
+ return __generator(this, function (_a) {
615
+ hexPublicKey = (0, key_1.convertPublicKey)(publicKey, 'hex');
616
+ payment = this.bitcoinJS.lib.payments.p2tr({
617
+ internalPubkey: Buffer.from(hexPublicKey.value, 'hex').subarray(1, 33),
618
+ network: this.bitcoinJS.config.network
619
+ });
620
+ return [2 /*return*/, BitcoinTaprootAddress_1.BitcoinTaprootAddress.fromPayment(payment).asString()];
621
+ });
622
+ });
623
+ };
624
+ // Transaction preparation with Taproot-specific logic
625
+ BitcoinTaprootProtocolImpl.prototype.prepareTransactionWithExtendedPublicKey = function (extendedPublicKey, details, configuration) {
626
+ return __awaiter(this, void 0, void 0, function () {
627
+ var fee, estimatedFee, wrappedFee, transaction, utxos, totalRequiredBalance, valueAccumulator, getPathIndexes, _i, utxos_1, utxo, indexes, derivedPublicKey, derivedAddress, i, value, lastUsedInternalAddress, changeValue, changeAddressIndex, derivedPublicKey, derivedAddress, psbt, xpubExtendedPublicKey, keyPair, replaceByFee;
628
+ var _this = this;
629
+ return __generator(this, function (_a) {
630
+ switch (_a.label) {
631
+ case 0:
632
+ if ((configuration === null || configuration === void 0 ? void 0 : configuration.masterFingerprint) === undefined) {
633
+ throw new errors_1.ConditionViolationError(coinlib_core_1.Domain.BITCOIN, 'Master fingerprint not set.');
634
+ }
635
+ if (!((configuration === null || configuration === void 0 ? void 0 : configuration.fee) !== undefined)) return [3 /*break*/, 1];
636
+ fee = configuration.fee;
637
+ return [3 /*break*/, 3];
638
+ case 1: return [4 /*yield*/, this.getTransactionFeeWithPublicKey(extendedPublicKey, details)];
639
+ case 2:
640
+ estimatedFee = _a.sent();
641
+ fee = estimatedFee.medium;
642
+ _a.label = 3;
643
+ case 3:
644
+ wrappedFee = new bignumber_1.default((0, module_kit_1.newAmount)(fee).blockchain(this.segwit.legacy.units).value);
645
+ transaction = (0, module_kit_1.newUnsignedTransaction)({
646
+ ins: [],
647
+ outs: []
648
+ });
649
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.indexerApi, "/api/v2/utxo/").concat(extendedPublicKey.value, "?confirmed=true"), {
650
+ responseType: 'json'
651
+ })];
652
+ case 4:
653
+ utxos = (_a.sent()).data;
654
+ if (utxos.length <= 0) {
655
+ throw new errors_1.BalanceError(coinlib_core_1.Domain.BITCOIN, 'Not enough balance.');
656
+ }
657
+ totalRequiredBalance = details
658
+ .map(function (_a) {
659
+ var amount = _a.amount;
660
+ return new bignumber_1.default((0, module_kit_1.newAmount)(amount).blockchain(_this.segwit.legacy.units).value);
661
+ })
662
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
663
+ .plus(wrappedFee);
664
+ valueAccumulator = new bignumber_1.default(0);
665
+ getPathIndexes = function (path) {
666
+ var result = path
667
+ .split('/')
668
+ .slice(-2)
669
+ .map(function (item) { return parseInt(item); })
670
+ .filter(function (item) { return !isNaN(item); });
671
+ if (result.length !== 2) {
672
+ throw new Error('Unexpected path format');
673
+ }
674
+ return [result[0], result[1]];
675
+ };
676
+ _i = 0, utxos_1 = utxos;
677
+ _a.label = 5;
678
+ case 5:
679
+ if (!(_i < utxos_1.length)) return [3 /*break*/, 9];
680
+ utxo = utxos_1[_i];
681
+ valueAccumulator = valueAccumulator.plus(utxo.value);
682
+ indexes = getPathIndexes(utxo.path);
683
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(extendedPublicKey, indexes[0], indexes[1])];
684
+ case 6:
685
+ derivedPublicKey = _a.sent();
686
+ return [4 /*yield*/, this.getAddressFromPublicKey(derivedPublicKey)];
687
+ case 7:
688
+ derivedAddress = _a.sent();
689
+ if (derivedAddress === utxo.address) {
690
+ transaction.ins.push({
691
+ txId: utxo.txid,
692
+ value: new bignumber_1.default(utxo.value).toString(10),
693
+ vout: utxo.vout,
694
+ address: utxo.address,
695
+ derivationPath: utxo.path
696
+ });
697
+ }
698
+ else {
699
+ throw new Error('Invalid address returned from API');
700
+ }
701
+ if (valueAccumulator.isGreaterThanOrEqualTo(totalRequiredBalance)) {
702
+ return [3 /*break*/, 9];
703
+ }
704
+ _a.label = 8;
705
+ case 8:
706
+ _i++;
707
+ return [3 /*break*/, 5];
708
+ case 9:
709
+ if (valueAccumulator.isLessThan(totalRequiredBalance)) {
710
+ throw new Error('not enough balance 2');
711
+ }
712
+ for (i = 0; i < details.length; i++) {
713
+ value = (0, module_kit_1.newAmount)(details[i].amount).blockchain(this.segwit.legacy.units).value;
714
+ transaction.outs.push({
715
+ recipient: details[i].to,
716
+ isChange: false,
717
+ value: value
718
+ });
719
+ valueAccumulator = valueAccumulator.minus(value);
720
+ }
721
+ lastUsedInternalAddress = Math.max.apply(Math, __spreadArray([-1], utxos
722
+ .map(function (utxo) { return getPathIndexes(utxo.path); })
723
+ .filter(function (indexes) { return indexes[0] === 1; })
724
+ .map(function (indexes) { return indexes[1]; }), false));
725
+ changeValue = valueAccumulator.minus(wrappedFee);
726
+ if (!changeValue.isGreaterThan(new bignumber_1.default(DUST_AMOUNT))) return [3 /*break*/, 12];
727
+ changeAddressIndex = lastUsedInternalAddress + 1;
728
+ return [4 /*yield*/, this.deriveFromExtendedPublicKey(extendedPublicKey, 1, changeAddressIndex)];
729
+ case 10:
730
+ derivedPublicKey = _a.sent();
731
+ return [4 /*yield*/, this.getAddressFromPublicKey(derivedPublicKey)];
732
+ case 11:
733
+ derivedAddress = _a.sent();
734
+ transaction.outs.push({
735
+ recipient: derivedAddress,
736
+ isChange: true,
737
+ value: changeValue.toString(10),
738
+ derivationPath: "1/".concat(changeAddressIndex)
739
+ });
740
+ _a.label = 12;
741
+ case 12:
742
+ psbt = new this.bitcoinJS.lib.Psbt();
743
+ psbt.addUnknownKeyValToGlobal({
744
+ key: Buffer.from('amount'),
745
+ value: Buffer.from(details
746
+ .reduce(function (accumulator, next) {
747
+ return accumulator.plus((0, module_kit_1.newAmount)(next.amount).blockchain(_this.segwit.legacy.units).value);
748
+ }, new bignumber_1.default(0))
749
+ .toString())
750
+ });
751
+ xpubExtendedPublicKey = (0, key_1.convertExtendedPublicKey)(extendedPublicKey, { format: 'encoded', type: 'xpub' });
752
+ keyPair = this.bip32.fromBase58(xpubExtendedPublicKey.value);
753
+ replaceByFee = (configuration === null || configuration === void 0 ? void 0 : configuration.replaceByFee) ? true : false;
754
+ transaction.ins.forEach(function (tx) {
755
+ var indexes = getPathIndexes(tx.derivationPath);
756
+ var childNode = keyPair.derivePath(indexes.join('/'));
757
+ var p2tr = _this.bitcoinJS.lib.payments.p2tr({
758
+ internalPubkey: Buffer.from(childNode.publicKey.subarray(1, 33)),
759
+ network: _this.bitcoinJS.config.network
760
+ });
761
+ var p2trOutput = p2tr.output;
762
+ if (!p2trOutput) {
763
+ throw new Error('no p2tr output');
764
+ }
765
+ psbt.addInput({
766
+ hash: tx.txId,
767
+ index: tx.vout,
768
+ sequence: replaceByFee ? 0xfffffffd : undefined,
769
+ witnessUtxo: {
770
+ script: p2trOutput,
771
+ value: parseInt(tx.value, 10)
772
+ },
773
+ tapInternalKey: Buffer.from(childNode.publicKey.subarray(1, 33)),
774
+ bip32Derivation: [
775
+ {
776
+ masterFingerprint: Buffer.from(configuration.masterFingerprint.value, 'hex'),
777
+ pubkey: Buffer.from(childNode.publicKey),
778
+ path: tx.derivationPath
779
+ }
780
+ ]
781
+ });
782
+ });
783
+ transaction.outs.forEach(function (out, index) {
784
+ psbt.addOutput({ address: out.recipient, value: parseInt(out.value, 10) });
785
+ if (out.derivationPath) {
786
+ psbt.addUnknownKeyValToOutput(index, {
787
+ key: Buffer.from('dp'),
788
+ value: Buffer.from(out.derivationPath, 'utf8')
789
+ });
790
+ }
791
+ });
792
+ return [2 /*return*/, (0, module_kit_1.newUnsignedTransaction)({ psbt: psbt.toHex() })];
793
+ }
794
+ });
795
+ });
796
+ };
797
+ return BitcoinTaprootProtocolImpl;
798
+ }());
799
+ exports.BitcoinTaprootProtocolImpl = BitcoinTaprootProtocolImpl;
800
+ // Factory
801
+ function createBitcoinTaprootProtocol(options) {
802
+ if (options === void 0) { options = {}; }
803
+ return new BitcoinTaprootProtocolImpl(options);
804
+ }
805
+ exports.createBitcoinTaprootProtocol = createBitcoinTaprootProtocol;
806
+ //# sourceMappingURL=BitcoinTaprootProtocol.js.map