@airgap/bitcoin 0.13.11-beta.1 → 0.13.11-beta.10

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 (148) hide show
  1. package/index.d.ts +1 -0
  2. package/index.js +18 -0
  3. package/index.js.map +1 -0
  4. package/package.json +1 -5
  5. package/v0/index.d.ts +14 -0
  6. package/v0/index.js +34 -0
  7. package/v0/index.js.map +1 -0
  8. package/v0/protocol/BitcoinAddress.d.ts +9 -0
  9. package/v0/protocol/BitcoinAddress.js +23 -0
  10. package/v0/protocol/BitcoinAddress.js.map +1 -0
  11. package/v0/protocol/BitcoinCryptoClient.d.ts +11 -0
  12. package/v0/protocol/BitcoinCryptoClient.js +91 -0
  13. package/v0/protocol/BitcoinCryptoClient.js.map +1 -0
  14. package/v0/protocol/BitcoinProtocol.d.ts +167 -0
  15. package/v0/protocol/BitcoinProtocol.js +1063 -0
  16. package/v0/protocol/BitcoinProtocol.js.map +1 -0
  17. package/v0/protocol/BitcoinProtocolOptions.d.ts +26 -0
  18. package/v0/protocol/BitcoinProtocolOptions.js +148 -0
  19. package/v0/protocol/BitcoinProtocolOptions.js.map +1 -0
  20. package/v0/protocol/BitcoinSegwitAddress.d.ts +7 -0
  21. package/v0/protocol/BitcoinSegwitAddress.js +41 -0
  22. package/v0/protocol/BitcoinSegwitAddress.js.map +1 -0
  23. package/v0/protocol/BitcoinSegwitProtocol.d.ts +28 -0
  24. package/v0/protocol/BitcoinSegwitProtocol.js +541 -0
  25. package/v0/protocol/BitcoinSegwitProtocol.js.map +1 -0
  26. package/v0/protocol/BitcoinTestnetProtocol.d.ts +7 -0
  27. package/v0/protocol/BitcoinTestnetProtocol.js +58 -0
  28. package/v0/protocol/BitcoinTestnetProtocol.js.map +1 -0
  29. package/v0/protocol/BitcoinTypes.d.ts +21 -0
  30. package/v0/protocol/BitcoinTypes.js +3 -0
  31. package/v0/protocol/BitcoinTypes.js.map +1 -0
  32. package/v0/serializer/schemas/v2/transaction-sign-request-bitcoin-segwit.json +0 -0
  33. package/v0/serializer/schemas/v2/transaction-sign-request-bitcoin.json +73 -0
  34. package/v0/serializer/schemas/v2/transaction-sign-response-bitcoin-segwit.json +0 -0
  35. package/v0/serializer/schemas/v2/transaction-sign-response-bitcoin.json +37 -0
  36. package/v0/serializer/schemas/v3/transaction-sign-request-bitcoin-segwit.json +29 -0
  37. package/v0/serializer/schemas/v3/transaction-sign-request-bitcoin.json +73 -0
  38. package/v0/serializer/schemas/v3/transaction-sign-response-bitcoin-segwit.json +19 -0
  39. package/v0/serializer/schemas/v3/transaction-sign-response-bitcoin.json +37 -0
  40. package/v0/serializer/validators/transaction-validator.d.ts +15 -0
  41. package/v0/serializer/validators/transaction-validator.js +81 -0
  42. package/v0/serializer/validators/transaction-validator.js.map +1 -0
  43. package/v0/serializer/validators/validators.d.ts +1 -0
  44. package/v0/serializer/validators/validators.js +151 -0
  45. package/v0/serializer/validators/validators.js.map +1 -0
  46. package/v0/types/signed-transaction-bitcoin-segwit.d.ts +5 -0
  47. package/v0/types/signed-transaction-bitcoin-segwit.js +3 -0
  48. package/v0/types/signed-transaction-bitcoin-segwit.js.map +1 -0
  49. package/v0/types/signed-transaction-bitcoin.d.ts +9 -0
  50. package/v0/types/signed-transaction-bitcoin.js +3 -0
  51. package/v0/types/signed-transaction-bitcoin.js.map +1 -0
  52. package/v0/types/transaction-bitcoin.d.ts +20 -0
  53. package/v0/types/transaction-bitcoin.js +3 -0
  54. package/v0/types/transaction-bitcoin.js.map +1 -0
  55. package/v0/types/unsigned-transaction-bitcoin-segwit.d.ts +7 -0
  56. package/v0/types/unsigned-transaction-bitcoin-segwit.js +3 -0
  57. package/v0/types/unsigned-transaction-bitcoin-segwit.js.map +1 -0
  58. package/v0/types/unsigned-transaction-bitcoin.d.ts +22 -0
  59. package/v0/types/unsigned-transaction-bitcoin.js +3 -0
  60. package/v0/types/unsigned-transaction-bitcoin.js.map +1 -0
  61. package/v1/block-explorer/BlockCypherBlockExplorer.d.ts +9 -0
  62. package/v1/block-explorer/BlockCypherBlockExplorer.js +74 -0
  63. package/v1/block-explorer/BlockCypherBlockExplorer.js.map +1 -0
  64. package/v1/data/BitcoinAddress.d.ts +7 -0
  65. package/v1/data/BitcoinAddress.js +20 -0
  66. package/v1/data/BitcoinAddress.js.map +1 -0
  67. package/v1/data/BitcoinSegwitAddress.d.ts +8 -0
  68. package/v1/data/BitcoinSegwitAddress.js +25 -0
  69. package/v1/data/BitcoinSegwitAddress.js.map +1 -0
  70. package/v1/index.d.ts +20 -0
  71. package/v1/index.js +24 -0
  72. package/v1/index.js.map +1 -0
  73. package/v1/module/BitcoinModule.d.ts +16 -0
  74. package/v1/module/BitcoinModule.js +112 -0
  75. package/v1/module/BitcoinModule.js.map +1 -0
  76. package/v1/module.d.ts +3 -0
  77. package/v1/module.js +24 -0
  78. package/v1/module.js.map +1 -0
  79. package/v1/protocol/BitcoinCryptoClient.d.ts +12 -0
  80. package/v1/protocol/BitcoinCryptoClient.js +96 -0
  81. package/v1/protocol/BitcoinCryptoClient.js.map +1 -0
  82. package/v1/protocol/BitcoinProtocol.d.ts +72 -0
  83. package/v1/protocol/BitcoinProtocol.js +1193 -0
  84. package/v1/protocol/BitcoinProtocol.js.map +1 -0
  85. package/v1/protocol/BitcoinSegwitProtocol.d.ts +52 -0
  86. package/v1/protocol/BitcoinSegwitProtocol.js +720 -0
  87. package/v1/protocol/BitcoinSegwitProtocol.js.map +1 -0
  88. package/v1/protocol/BitcoinTestnetProtocol.d.ts +12 -0
  89. package/v1/protocol/BitcoinTestnetProtocol.js +73 -0
  90. package/v1/protocol/BitcoinTestnetProtocol.js.map +1 -0
  91. package/v1/serializer/v3/schemas/converter/transaction-converter.d.ts +13 -0
  92. package/v1/serializer/v3/schemas/converter/transaction-converter.js +75 -0
  93. package/v1/serializer/v3/schemas/converter/transaction-converter.js.map +1 -0
  94. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.d.ts +4 -0
  95. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.js +3 -0
  96. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin-segwit.js.map +1 -0
  97. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.d.ts +4 -0
  98. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.js +3 -0
  99. package/v1/serializer/v3/schemas/definitions/transaction-sign-request-bitcoin.js.map +1 -0
  100. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.d.ts +3 -0
  101. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.js +3 -0
  102. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin-segwit.js.map +1 -0
  103. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.d.ts +7 -0
  104. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.js +3 -0
  105. package/v1/serializer/v3/schemas/definitions/transaction-sign-response-bitcoin.js.map +1 -0
  106. package/v1/serializer/v3/schemas/generated/transaction-sign-request-bitcoin-segwit.json +29 -0
  107. package/v1/serializer/v3/schemas/generated/transaction-sign-request-bitcoin.json +79 -0
  108. package/v1/serializer/v3/schemas/generated/transaction-sign-response-bitcoin-segwit.json +19 -0
  109. package/v1/serializer/v3/schemas/generated/transaction-sign-response-bitcoin.json +37 -0
  110. package/v1/serializer/v3/serializer-companion.d.ts +14 -0
  111. package/v1/serializer/v3/serializer-companion.js +197 -0
  112. package/v1/serializer/v3/serializer-companion.js.map +1 -0
  113. package/v1/serializer/v3/validators/transaction-validator.d.ts +7 -0
  114. package/v1/serializer/v3/validators/transaction-validator.js +56 -0
  115. package/v1/serializer/v3/validators/transaction-validator.js.map +1 -0
  116. package/v1/serializer/v3/validators/validators.d.ts +7 -0
  117. package/v1/serializer/v3/validators/validators.js +238 -0
  118. package/v1/serializer/v3/validators/validators.js.map +1 -0
  119. package/v1/types/bitcoinjs.d.ts +14 -0
  120. package/v1/types/bitcoinjs.js +3 -0
  121. package/v1/types/bitcoinjs.js.map +1 -0
  122. package/v1/types/crypto.d.ts +2 -0
  123. package/v1/types/crypto.js +3 -0
  124. package/v1/types/crypto.js.map +1 -0
  125. package/v1/types/indexer.d.ts +81 -0
  126. package/v1/types/indexer.js +3 -0
  127. package/v1/types/indexer.js.map +1 -0
  128. package/v1/types/key.d.ts +6 -0
  129. package/v1/types/key.js +3 -0
  130. package/v1/types/key.js.map +1 -0
  131. package/v1/types/protocol.d.ts +17 -0
  132. package/v1/types/protocol.js +3 -0
  133. package/v1/types/protocol.js.map +1 -0
  134. package/v1/types/transaction.d.ts +39 -0
  135. package/v1/types/transaction.js +3 -0
  136. package/v1/types/transaction.js.map +1 -0
  137. package/v1/utils/common.d.ts +2 -0
  138. package/v1/utils/common.js +28 -0
  139. package/v1/utils/common.js.map +1 -0
  140. package/v1/utils/key.d.ts +34 -0
  141. package/v1/utils/key.js +190 -0
  142. package/v1/utils/key.js.map +1 -0
  143. package/v1/utils/network.d.ts +2 -0
  144. package/v1/utils/network.js +22 -0
  145. package/v1/utils/network.js.map +1 -0
  146. package/v1/utils/signature.d.ts +2 -0
  147. package/v1/utils/signature.js +34 -0
  148. package/v1/utils/signature.js.map +1 -0
@@ -0,0 +1,1063 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __generator = (this && this.__generator) || function (thisArg, body) {
35
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
+ function verb(n) { return function (v) { return step([n, v]); }; }
38
+ function step(op) {
39
+ if (f) throw new TypeError("Generator is already executing.");
40
+ while (_) try {
41
+ 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;
42
+ if (y = 0, t) op = [op[0] & 2, t.value];
43
+ switch (op[0]) {
44
+ case 0: case 1: t = op; break;
45
+ case 4: _.label++; return { value: op[1], done: false };
46
+ case 5: _.label++; y = op[1]; op = [0]; continue;
47
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
+ default:
49
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
+ if (t[2]) _.ops.pop();
54
+ _.trys.pop(); continue;
55
+ }
56
+ op = body.call(thisArg, _);
57
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
+ }
60
+ };
61
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
62
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
63
+ if (ar || !(i in from)) {
64
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
65
+ ar[i] = from[i];
66
+ }
67
+ }
68
+ return to.concat(ar || Array.prototype.slice.call(from));
69
+ };
70
+ var __importDefault = (this && this.__importDefault) || function (mod) {
71
+ return (mod && mod.__esModule) ? mod : { "default": mod };
72
+ };
73
+ Object.defineProperty(exports, "__esModule", { value: true });
74
+ exports.BitcoinProtocol = void 0;
75
+ var index_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/axios-0.19.0/index"));
76
+ var bignumber_1 = __importDefault(require("@airgap/coinlib-core/dependencies/src/bignumber.js-9.0.0/bignumber"));
77
+ var index_2 = require("@airgap/coinlib-core/dependencies/src/bip39-2.5.0/index");
78
+ var bitcoinJSMessage = __importStar(require("@airgap/coinlib-core/dependencies/src/bitcoinjs-message-2.1.1/index"));
79
+ var errors_1 = require("@airgap/coinlib-core/errors");
80
+ var coinlib_error_1 = require("@airgap/coinlib-core/errors/coinlib-error");
81
+ var ProtocolSymbols_1 = require("@airgap/coinlib-core/utils/ProtocolSymbols");
82
+ var BitcoinAddress_1 = require("./BitcoinAddress");
83
+ var BitcoinCryptoClient_1 = require("./BitcoinCryptoClient");
84
+ var BitcoinProtocolOptions_1 = require("./BitcoinProtocolOptions");
85
+ var DUST_AMOUNT = 50;
86
+ var BitcoinProtocol = /** @class */ (function () {
87
+ function BitcoinProtocol(options) {
88
+ if (options === void 0) { options = new BitcoinProtocolOptions_1.BitcoinProtocolOptions(); }
89
+ this.options = options;
90
+ this.symbol = 'BTC';
91
+ this.name = 'Bitcoin (Legacy)';
92
+ this.marketSymbol = 'btc';
93
+ this.feeSymbol = 'btc';
94
+ this.feeDefaults = {
95
+ low: '0.00002',
96
+ medium: '0.00004',
97
+ high: '0.00005'
98
+ };
99
+ this.decimals = 8;
100
+ this.feeDecimals = 8;
101
+ this.identifier = ProtocolSymbols_1.MainProtocolSymbols.BTC;
102
+ this.units = [
103
+ {
104
+ unitSymbol: 'BTC',
105
+ factor: '1'
106
+ },
107
+ {
108
+ unitSymbol: 'mBTC',
109
+ factor: '0.0001'
110
+ },
111
+ {
112
+ unitSymbol: 'Satoshi',
113
+ factor: '0.00000001'
114
+ }
115
+ ];
116
+ this.supportsHD = true;
117
+ this.standardDerivationPath = "m/44'/0'/0'";
118
+ this.addressIsCaseSensitive = true;
119
+ this.addressValidationPattern = '^(?:[13]{1}[a-km-zA-HJ-NP-Z1-9]{25,34}|bc1[a-z0-9]{39,59})$';
120
+ this.addressPlaceholder = '1ABC...';
121
+ this.cryptoClient = new BitcoinCryptoClient_1.BitcoinCryptoClient(this, bitcoinJSMessage);
122
+ }
123
+ BitcoinProtocol.prototype.getSymbol = function () {
124
+ return __awaiter(this, void 0, void 0, function () {
125
+ return __generator(this, function (_a) {
126
+ return [2 /*return*/, this.symbol];
127
+ });
128
+ });
129
+ };
130
+ BitcoinProtocol.prototype.getName = function () {
131
+ return __awaiter(this, void 0, void 0, function () {
132
+ return __generator(this, function (_a) {
133
+ return [2 /*return*/, this.name];
134
+ });
135
+ });
136
+ };
137
+ BitcoinProtocol.prototype.getMarketSymbol = function () {
138
+ return __awaiter(this, void 0, void 0, function () {
139
+ return __generator(this, function (_a) {
140
+ return [2 /*return*/, this.marketSymbol];
141
+ });
142
+ });
143
+ };
144
+ BitcoinProtocol.prototype.getFeeSymbol = function () {
145
+ return __awaiter(this, void 0, void 0, function () {
146
+ return __generator(this, function (_a) {
147
+ return [2 /*return*/, this.feeSymbol];
148
+ });
149
+ });
150
+ };
151
+ BitcoinProtocol.prototype.getFeeDefaults = function () {
152
+ return __awaiter(this, void 0, void 0, function () {
153
+ return __generator(this, function (_a) {
154
+ return [2 /*return*/, this.feeDefaults];
155
+ });
156
+ });
157
+ };
158
+ BitcoinProtocol.prototype.getDecimals = function () {
159
+ return __awaiter(this, void 0, void 0, function () {
160
+ return __generator(this, function (_a) {
161
+ return [2 /*return*/, this.decimals];
162
+ });
163
+ });
164
+ };
165
+ BitcoinProtocol.prototype.getFeeDecimals = function () {
166
+ return __awaiter(this, void 0, void 0, function () {
167
+ return __generator(this, function (_a) {
168
+ return [2 /*return*/, this.feeDecimals];
169
+ });
170
+ });
171
+ };
172
+ BitcoinProtocol.prototype.getIdentifier = function () {
173
+ return __awaiter(this, void 0, void 0, function () {
174
+ return __generator(this, function (_a) {
175
+ return [2 /*return*/, this.identifier];
176
+ });
177
+ });
178
+ };
179
+ BitcoinProtocol.prototype.getUnits = function () {
180
+ return __awaiter(this, void 0, void 0, function () {
181
+ return __generator(this, function (_a) {
182
+ return [2 /*return*/, this.units];
183
+ });
184
+ });
185
+ };
186
+ BitcoinProtocol.prototype.getSupportsHD = function () {
187
+ return __awaiter(this, void 0, void 0, function () {
188
+ return __generator(this, function (_a) {
189
+ return [2 /*return*/, this.supportsHD];
190
+ });
191
+ });
192
+ };
193
+ BitcoinProtocol.prototype.getStandardDerivationPath = function () {
194
+ return __awaiter(this, void 0, void 0, function () {
195
+ return __generator(this, function (_a) {
196
+ return [2 /*return*/, this.standardDerivationPath];
197
+ });
198
+ });
199
+ };
200
+ BitcoinProtocol.prototype.getAddressIsCaseSensitive = function () {
201
+ return __awaiter(this, void 0, void 0, function () {
202
+ return __generator(this, function (_a) {
203
+ return [2 /*return*/, this.addressIsCaseSensitive];
204
+ });
205
+ });
206
+ };
207
+ BitcoinProtocol.prototype.getAddressValidationPattern = function () {
208
+ return __awaiter(this, void 0, void 0, function () {
209
+ return __generator(this, function (_a) {
210
+ return [2 /*return*/, this.addressValidationPattern];
211
+ });
212
+ });
213
+ };
214
+ BitcoinProtocol.prototype.getAddressPlaceholder = function () {
215
+ return __awaiter(this, void 0, void 0, function () {
216
+ return __generator(this, function (_a) {
217
+ return [2 /*return*/, this.addressPlaceholder];
218
+ });
219
+ });
220
+ };
221
+ BitcoinProtocol.prototype.getOptions = function () {
222
+ return __awaiter(this, void 0, void 0, function () {
223
+ return __generator(this, function (_a) {
224
+ return [2 /*return*/, this.options];
225
+ });
226
+ });
227
+ };
228
+ BitcoinProtocol.prototype.getBlockExplorerLinkForAddress = function (address) {
229
+ return __awaiter(this, void 0, void 0, function () {
230
+ return __generator(this, function (_a) {
231
+ return [2 /*return*/, this.options.network.blockExplorer.getAddressLink(address)];
232
+ });
233
+ });
234
+ };
235
+ BitcoinProtocol.prototype.getBlockExplorerLinkForTxId = function (txId) {
236
+ return __awaiter(this, void 0, void 0, function () {
237
+ return __generator(this, function (_a) {
238
+ return [2 /*return*/, this.options.network.blockExplorer.getTransactionLink(txId)];
239
+ });
240
+ });
241
+ };
242
+ BitcoinProtocol.prototype.getPublicKeyFromMnemonic = function (mnemonic, derivationPath, password) {
243
+ return __awaiter(this, void 0, void 0, function () {
244
+ var secret;
245
+ return __generator(this, function (_a) {
246
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
247
+ return [2 /*return*/, this.getPublicKeyFromHexSecret(secret, derivationPath)];
248
+ });
249
+ });
250
+ };
251
+ BitcoinProtocol.prototype.getPrivateKeyFromMnemonic = function (mnemonic, derivationPath, password) {
252
+ return __awaiter(this, void 0, void 0, function () {
253
+ var secret;
254
+ return __generator(this, function (_a) {
255
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
256
+ return [2 /*return*/, this.getPrivateKeyFromHexSecret(secret, derivationPath)];
257
+ });
258
+ });
259
+ };
260
+ BitcoinProtocol.prototype.getExtendedPublicKeyFromMnemonic = function (mnemonic, derivationPath, password) {
261
+ return __awaiter(this, void 0, void 0, function () {
262
+ var secret;
263
+ return __generator(this, function (_a) {
264
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
265
+ return [2 /*return*/, this.getExtendedPublicKeyFromHexSecret(secret, derivationPath)];
266
+ });
267
+ });
268
+ };
269
+ BitcoinProtocol.prototype.getExtendedPrivateKeyFromMnemonic = function (mnemonic, derivationPath, password) {
270
+ return __awaiter(this, void 0, void 0, function () {
271
+ var secret;
272
+ return __generator(this, function (_a) {
273
+ secret = (0, index_2.mnemonicToSeed)(mnemonic, password);
274
+ return [2 /*return*/, this.getExtendedPrivateKeyFromHexSecret(secret, derivationPath)];
275
+ });
276
+ });
277
+ };
278
+ BitcoinProtocol.prototype.getPublicKeyFromHexSecret = function (secret, derivationPath) {
279
+ return __awaiter(this, void 0, void 0, function () {
280
+ var bitcoinNode;
281
+ return __generator(this, function (_a) {
282
+ bitcoinNode = this.options.config.bitcoinJSLib.HDNode.fromSeedHex(secret, this.options.network.extras.network);
283
+ return [2 /*return*/, bitcoinNode.derivePath(derivationPath).neutered().toBase58()];
284
+ });
285
+ });
286
+ };
287
+ BitcoinProtocol.prototype.getPrivateKeyFromHexSecret = function (secret, derivationPath) {
288
+ return __awaiter(this, void 0, void 0, function () {
289
+ var bitcoinNode;
290
+ return __generator(this, function (_a) {
291
+ bitcoinNode = this.options.config.bitcoinJSLib.HDNode.fromSeedHex(secret, this.options.network.extras.network);
292
+ return [2 /*return*/, bitcoinNode.derivePath(derivationPath).keyPair.d.toBuffer(32).toString('hex')];
293
+ });
294
+ });
295
+ };
296
+ BitcoinProtocol.prototype.getExtendedPublicKeyFromHexSecret = function (secret, derivationPath) {
297
+ return __awaiter(this, void 0, void 0, function () {
298
+ return __generator(this, function (_a) {
299
+ return [2 /*return*/, this.getPublicKeyFromHexSecret(secret, derivationPath)];
300
+ });
301
+ });
302
+ };
303
+ BitcoinProtocol.prototype.getExtendedPrivateKeyFromHexSecret = function (secret, derivationPath) {
304
+ return __awaiter(this, void 0, void 0, function () {
305
+ var bitcoinNode;
306
+ return __generator(this, function (_a) {
307
+ bitcoinNode = this.options.config.bitcoinJSLib.HDNode.fromSeedHex(secret, this.options.network.extras.network);
308
+ return [2 /*return*/, bitcoinNode.derivePath(derivationPath).toBase58()];
309
+ });
310
+ });
311
+ };
312
+ BitcoinProtocol.prototype.getAddressFromPublicKey = function (publicKey, cursor) {
313
+ return __awaiter(this, void 0, void 0, function () {
314
+ var node, address;
315
+ return __generator(this, function (_a) {
316
+ node = this.options.config.bitcoinJSLib.HDNode.fromBase58(publicKey, this.options.network.extras.network);
317
+ address = BitcoinAddress_1.BitcoinAddress.from(node);
318
+ return [2 /*return*/, {
319
+ address: address.asString(),
320
+ cursor: { hasNext: false }
321
+ }];
322
+ });
323
+ });
324
+ };
325
+ BitcoinProtocol.prototype.getAddressesFromPublicKey = function (publicKey, cursor) {
326
+ return __awaiter(this, void 0, void 0, function () {
327
+ return __generator(this, function (_a) {
328
+ switch (_a.label) {
329
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey, cursor)];
330
+ case 1: return [2 /*return*/, [_a.sent()]];
331
+ }
332
+ });
333
+ });
334
+ };
335
+ BitcoinProtocol.prototype.getAddressFromExtendedPublicKey = function (extendedPublicKey, visibilityDerivationIndex, addressDerivationIndex) {
336
+ return __awaiter(this, void 0, void 0, function () {
337
+ var node, address;
338
+ return __generator(this, function (_a) {
339
+ node = this.options.config.bitcoinJSLib.HDNode.fromBase58(extendedPublicKey, this.options.network.extras.network);
340
+ address = BitcoinAddress_1.BitcoinAddress.from(node, visibilityDerivationIndex, addressDerivationIndex);
341
+ return [2 /*return*/, {
342
+ address: address.asString(),
343
+ cursor: { hasNext: false }
344
+ }];
345
+ });
346
+ });
347
+ };
348
+ BitcoinProtocol.prototype.getAddressesFromExtendedPublicKey = function (extendedPublicKey, visibilityDerivationIndex, addressCount, offset) {
349
+ return __awaiter(this, void 0, void 0, function () {
350
+ var node, generatorArray;
351
+ return __generator(this, function (_a) {
352
+ node = this.options.config.bitcoinJSLib.HDNode.fromBase58(extendedPublicKey, this.options.network.extras.network);
353
+ generatorArray = Array.from(new Array(addressCount), function (_, i) { return i + offset; });
354
+ return [2 /*return*/, Promise.all(generatorArray.map(function (x) {
355
+ var address = BitcoinAddress_1.BitcoinAddress.from(node, visibilityDerivationIndex, x);
356
+ return {
357
+ address: address.asString(),
358
+ cursor: { hasNext: false }
359
+ };
360
+ }))];
361
+ });
362
+ });
363
+ };
364
+ BitcoinProtocol.prototype.signWithPrivateKey = function (privateKey, transaction) {
365
+ return __awaiter(this, void 0, void 0, function () {
366
+ var transactionBuilder, _i, _a, input, _b, _c, output, generatedChangeAddress, i;
367
+ return __generator(this, function (_d) {
368
+ switch (_d.label) {
369
+ case 0:
370
+ transactionBuilder = new this.options.config.bitcoinJSLib.TransactionBuilder(this.options.network.extras.network);
371
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
372
+ input = _a[_i];
373
+ transactionBuilder.addInput(input.txId, input.vout);
374
+ }
375
+ _b = 0, _c = transaction.outs;
376
+ _d.label = 1;
377
+ case 1:
378
+ if (!(_b < _c.length)) return [3 /*break*/, 5];
379
+ output = _c[_b];
380
+ if (!output.isChange) return [3 /*break*/, 3];
381
+ return [4 /*yield*/, this.getAddressFromPublicKey(privateKey)];
382
+ case 2:
383
+ generatedChangeAddress = (_d.sent()).address;
384
+ if (generatedChangeAddress !== output.recipient) {
385
+ throw new errors_1.ConditionViolationError(coinlib_error_1.Domain.BITCOIN, 'Change address could not be verified.');
386
+ }
387
+ _d.label = 3;
388
+ case 3:
389
+ transactionBuilder.addOutput(output.recipient, new bignumber_1.default(output.value).toNumber());
390
+ _d.label = 4;
391
+ case 4:
392
+ _b++;
393
+ return [3 /*break*/, 1];
394
+ case 5:
395
+ for (i = 0; i < transaction.ins.length; i++) {
396
+ // 2. `privateKey` is used as a hex string
397
+ transactionBuilder.sign(i, Buffer.from(privateKey, 'hex'));
398
+ }
399
+ // TODO: given 1 & 2, check if it works
400
+ return [2 /*return*/, transactionBuilder.build().toHex()];
401
+ }
402
+ });
403
+ });
404
+ };
405
+ BitcoinProtocol.prototype.signWithExtendedPrivateKey = function (extendedPrivateKey, transaction) {
406
+ return __awaiter(this, void 0, void 0, function () {
407
+ var transactionBuilder, node, _i, _a, input, changeAddressBatchSize, changeAddressMaxAddresses, _b, _c, output, changeAddressIsValid, generatedChangeAddress, x, addresses, i;
408
+ return __generator(this, function (_d) {
409
+ switch (_d.label) {
410
+ case 0:
411
+ transactionBuilder = new this.options.config.bitcoinJSLib.TransactionBuilder(this.options.network.extras.network);
412
+ node = this.options.config.bitcoinJSLib.HDNode.fromBase58(extendedPrivateKey, this.options.network.extras.network);
413
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
414
+ input = _a[_i];
415
+ transactionBuilder.addInput(input.txId, input.vout);
416
+ }
417
+ changeAddressBatchSize = 10;
418
+ changeAddressMaxAddresses = 500;
419
+ _b = 0, _c = transaction.outs;
420
+ _d.label = 1;
421
+ case 1:
422
+ if (!(_b < _c.length)) return [3 /*break*/, 10];
423
+ output = _c[_b];
424
+ changeAddressIsValid = false;
425
+ if (!output.isChange) return [3 /*break*/, 8];
426
+ if (!output.derivationPath) return [3 /*break*/, 3];
427
+ return [4 /*yield*/, this.getAddressesFromExtendedPublicKey(extendedPrivateKey, 1, 1, parseInt(output.derivationPath, 10))];
428
+ case 2:
429
+ generatedChangeAddress = (_d.sent()).map(function (address) { return address.address; });
430
+ changeAddressIsValid = generatedChangeAddress.includes(output.recipient);
431
+ return [3 /*break*/, 7];
432
+ case 3:
433
+ x = 0;
434
+ _d.label = 4;
435
+ case 4:
436
+ if (!(x < changeAddressMaxAddresses)) return [3 /*break*/, 7];
437
+ return [4 /*yield*/, this.getAddressesFromExtendedPublicKey(extendedPrivateKey, 1, changeAddressBatchSize, x)];
438
+ case 5:
439
+ addresses = (_d.sent()).map(function (address) { return address.address; });
440
+ if (addresses.indexOf(output.recipient) >= 0) {
441
+ changeAddressIsValid = true;
442
+ x = changeAddressMaxAddresses;
443
+ }
444
+ _d.label = 6;
445
+ case 6:
446
+ x += changeAddressBatchSize;
447
+ return [3 /*break*/, 4];
448
+ case 7:
449
+ if (!changeAddressIsValid) {
450
+ throw new errors_1.InvalidValueError(coinlib_error_1.Domain.BITCOIN, 'Change address could not be verified.');
451
+ }
452
+ _d.label = 8;
453
+ case 8:
454
+ transactionBuilder.addOutput(output.recipient, new bignumber_1.default(output.value).toNumber());
455
+ _d.label = 9;
456
+ case 9:
457
+ _b++;
458
+ return [3 /*break*/, 1];
459
+ case 10:
460
+ for (i = 0; i < transaction.ins.length; i++) {
461
+ transactionBuilder.sign(i, node.derivePath(transaction.ins[i].derivationPath));
462
+ }
463
+ return [2 /*return*/, transactionBuilder.build().toHex()];
464
+ }
465
+ });
466
+ });
467
+ };
468
+ BitcoinProtocol.prototype.getTransactionDetails = function (unsignedTx) {
469
+ return __awaiter(this, void 0, void 0, function () {
470
+ var transaction, feeCalculator, _i, _a, txIn, _b, _c, txOut, warnings;
471
+ return __generator(this, function (_d) {
472
+ transaction = unsignedTx.transaction;
473
+ feeCalculator = new bignumber_1.default(0);
474
+ for (_i = 0, _a = transaction.ins; _i < _a.length; _i++) {
475
+ txIn = _a[_i];
476
+ feeCalculator = feeCalculator.plus(new bignumber_1.default(txIn.value));
477
+ }
478
+ for (_b = 0, _c = transaction.outs; _b < _c.length; _b++) {
479
+ txOut = _c[_b];
480
+ feeCalculator = feeCalculator.minus(new bignumber_1.default(txOut.value));
481
+ }
482
+ warnings = [];
483
+ return [2 /*return*/, [
484
+ {
485
+ from: transaction.ins.map(function (obj) { return obj.address; }),
486
+ to: transaction.outs.filter(function (obj) { return !obj.isChange; }).map(function (obj) { return obj.recipient; }),
487
+ amount: transaction.outs
488
+ .filter(function (obj) { return !obj.isChange; })
489
+ .map(function (obj) { return new bignumber_1.default(obj.value); })
490
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
491
+ .toString(10),
492
+ fee: feeCalculator.toString(10),
493
+ protocolIdentifier: this.identifier,
494
+ network: this.options.network,
495
+ isInbound: false,
496
+ transactionDetails: unsignedTx.transaction,
497
+ warnings: warnings
498
+ }
499
+ ]];
500
+ });
501
+ });
502
+ };
503
+ BitcoinProtocol.prototype.getTransactionDetailsFromSigned = function (signedTx) {
504
+ return __awaiter(this, void 0, void 0, function () {
505
+ var tx, bitcoinTx;
506
+ var _this = this;
507
+ return __generator(this, function (_a) {
508
+ tx = {
509
+ to: [],
510
+ from: signedTx.from,
511
+ amount: signedTx.amount,
512
+ fee: signedTx.fee,
513
+ protocolIdentifier: this.identifier,
514
+ network: this.options.network,
515
+ isInbound: false,
516
+ transactionDetails: signedTx.transaction
517
+ };
518
+ bitcoinTx = this.options.config.bitcoinJSLib.Transaction.fromHex(signedTx.transaction);
519
+ bitcoinTx.outs.forEach(function (output) {
520
+ var address = _this.options.config.bitcoinJSLib.address.fromOutputScript(output.script, _this.options.network.extras.network);
521
+ // only works if one output is target and rest is change, but this way we can filter out change addresses
522
+ if (new bignumber_1.default(output.value).isEqualTo(signedTx.amount)) {
523
+ tx.to.push(address);
524
+ }
525
+ });
526
+ return [2 /*return*/, [tx]];
527
+ });
528
+ });
529
+ };
530
+ BitcoinProtocol.prototype.getBalanceOfAddresses = function (addresses) {
531
+ return __awaiter(this, void 0, void 0, function () {
532
+ var valueAccumulator, _i, addresses_1, address, data;
533
+ return __generator(this, function (_a) {
534
+ switch (_a.label) {
535
+ case 0:
536
+ valueAccumulator = new bignumber_1.default(0);
537
+ _i = 0, addresses_1 = addresses;
538
+ _a.label = 1;
539
+ case 1:
540
+ if (!(_i < addresses_1.length)) return [3 /*break*/, 4];
541
+ address = addresses_1[_i];
542
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.extras.indexerApi, "/api/v2/address/").concat(address, "?details=basic"), {
543
+ responseType: 'json'
544
+ })];
545
+ case 2:
546
+ data = (_a.sent()).data;
547
+ valueAccumulator = valueAccumulator.plus(new bignumber_1.default(data.balance));
548
+ _a.label = 3;
549
+ case 3:
550
+ _i++;
551
+ return [3 /*break*/, 1];
552
+ case 4: return [2 /*return*/, valueAccumulator.toString(10)];
553
+ }
554
+ });
555
+ });
556
+ };
557
+ BitcoinProtocol.prototype.getBalanceOfPublicKey = function (publicKey) {
558
+ return __awaiter(this, void 0, void 0, function () {
559
+ var address;
560
+ return __generator(this, function (_a) {
561
+ switch (_a.label) {
562
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
563
+ case 1:
564
+ address = _a.sent();
565
+ return [2 /*return*/, this.getBalanceOfAddresses([address.address])];
566
+ }
567
+ });
568
+ });
569
+ };
570
+ BitcoinProtocol.prototype.getBalanceOfExtendedPublicKey = function (extendedPublicKey, offset) {
571
+ if (offset === void 0) { offset = 0; }
572
+ return __awaiter(this, void 0, void 0, function () {
573
+ var data;
574
+ return __generator(this, function (_a) {
575
+ switch (_a.label) {
576
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.extras.indexerApi, "/api/v2/xpub/").concat(extendedPublicKey, "?pageSize=1"), {
577
+ responseType: 'json'
578
+ })];
579
+ case 1:
580
+ data = (_a.sent()).data;
581
+ return [2 /*return*/, data.balance];
582
+ }
583
+ });
584
+ });
585
+ };
586
+ BitcoinProtocol.prototype.getBalanceOfPublicKeyForSubProtocols = function (publicKey, subProtocols) {
587
+ return __awaiter(this, void 0, void 0, function () {
588
+ return __generator(this, function (_a) {
589
+ throw Promise.reject('get balance of sub protocols not supported');
590
+ });
591
+ });
592
+ };
593
+ BitcoinProtocol.prototype.getAvailableBalanceOfAddresses = function (addresses) {
594
+ return __awaiter(this, void 0, void 0, function () {
595
+ return __generator(this, function (_a) {
596
+ return [2 /*return*/, this.getBalanceOfAddresses(addresses)];
597
+ });
598
+ });
599
+ };
600
+ BitcoinProtocol.prototype.estimateMaxTransactionValueFromExtendedPublicKey = function (extendedPublicKey, recipients, fee) {
601
+ return __awaiter(this, void 0, void 0, function () {
602
+ return __generator(this, function (_a) {
603
+ return [2 /*return*/, this.getBalanceOfExtendedPublicKey(extendedPublicKey)];
604
+ });
605
+ });
606
+ };
607
+ BitcoinProtocol.prototype.estimateMaxTransactionValueFromPublicKey = function (publicKey, recipients, fee) {
608
+ return __awaiter(this, void 0, void 0, function () {
609
+ return __generator(this, function (_a) {
610
+ return [2 /*return*/, this.getBalanceOfPublicKey(publicKey)];
611
+ });
612
+ });
613
+ };
614
+ BitcoinProtocol.prototype.estimateFeeDefaultsFromExtendedPublicKey = function (publicKey, recipients, values, data) {
615
+ return __awaiter(this, void 0, void 0, function () {
616
+ var result, estimatedFee, feeStepFactor, mediumFee, lowFee, highFee;
617
+ return __generator(this, function (_a) {
618
+ switch (_a.label) {
619
+ case 0: return [4 /*yield*/, index_1.default.get("".concat(this.options.network.extras.indexerApi, "/api/v2/estimatefee/5"))];
620
+ case 1:
621
+ result = (_a.sent()).data.result;
622
+ estimatedFee = new bignumber_1.default(result).shiftedBy(this.feeDecimals);
623
+ if (estimatedFee.isZero()) {
624
+ return [2 /*return*/, this.feeDefaults];
625
+ }
626
+ feeStepFactor = new bignumber_1.default(0.5);
627
+ mediumFee = estimatedFee;
628
+ lowFee = mediumFee.minus(mediumFee.times(feeStepFactor)).integerValue(bignumber_1.default.ROUND_FLOOR);
629
+ highFee = mediumFee.plus(mediumFee.times(feeStepFactor)).integerValue(bignumber_1.default.ROUND_FLOOR);
630
+ return [2 /*return*/, {
631
+ low: lowFee.shiftedBy(-this.feeDecimals).toFixed(),
632
+ medium: mediumFee.shiftedBy(-this.feeDecimals).toFixed(),
633
+ high: highFee.shiftedBy(-this.feeDecimals).toFixed()
634
+ }];
635
+ }
636
+ });
637
+ });
638
+ };
639
+ BitcoinProtocol.prototype.estimateFeeDefaultsFromPublicKey = function (publicKey, recipients, values, data) {
640
+ return __awaiter(this, void 0, void 0, function () {
641
+ return __generator(this, function (_a) {
642
+ return [2 /*return*/, Promise.reject('estimating fee defaults using non extended public key not implemented')];
643
+ });
644
+ });
645
+ };
646
+ BitcoinProtocol.prototype.prepareTransactionFromExtendedPublicKey = function (extendedPublicKey, offset, recipients, values, fee, extras) {
647
+ return __awaiter(this, void 0, void 0, function () {
648
+ var wrappedValues, wrappedFee, transaction, utxos, totalRequiredBalance, valueAccumulator, getPathIndexes, _i, utxos_1, utxo, indexes, derivedAddress, i, lastUsedInternalAddress, changeValue, changeAddressIndex, derivedAddress;
649
+ return __generator(this, function (_a) {
650
+ switch (_a.label) {
651
+ case 0:
652
+ wrappedValues = values.map(function (value) { return new bignumber_1.default(value); });
653
+ wrappedFee = new bignumber_1.default(fee);
654
+ transaction = {
655
+ ins: [],
656
+ outs: []
657
+ };
658
+ if (recipients.length !== wrappedValues.length) {
659
+ throw new errors_1.ConditionViolationError(coinlib_error_1.Domain.BITCOIN, 'recipients do not match values');
660
+ }
661
+ return [4 /*yield*/, index_1.default
662
+ .get("".concat(this.options.network.extras.indexerApi, "/api/v2/utxo/").concat(extendedPublicKey, "?confirmed=true"), {
663
+ responseType: 'json'
664
+ })
665
+ .catch(function (error) {
666
+ throw new errors_1.NetworkError(coinlib_error_1.Domain.BITCOIN, error);
667
+ })];
668
+ case 1:
669
+ utxos = (_a.sent()).data;
670
+ if (utxos.length <= 0) {
671
+ throw new errors_1.BalanceError(coinlib_error_1.Domain.BITCOIN, 'not enough balance'); // no transactions found on those addresses, probably won't find anything in the next ones
672
+ }
673
+ totalRequiredBalance = wrappedValues
674
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
675
+ .plus(wrappedFee);
676
+ valueAccumulator = new bignumber_1.default(0);
677
+ getPathIndexes = function (path) {
678
+ var result = path
679
+ .split('/')
680
+ .slice(-2)
681
+ .map(function (item) { return parseInt(item, 10); })
682
+ .filter(function (item) { return !isNaN(item); });
683
+ if (result.length !== 2) {
684
+ throw new errors_1.ConditionViolationError(coinlib_error_1.Domain.BITCOIN, 'Unexpected path format');
685
+ }
686
+ return [result[0], result[1]];
687
+ };
688
+ _i = 0, utxos_1 = utxos;
689
+ _a.label = 2;
690
+ case 2:
691
+ if (!(_i < utxos_1.length)) return [3 /*break*/, 5];
692
+ utxo = utxos_1[_i];
693
+ valueAccumulator = valueAccumulator.plus(utxo.value);
694
+ indexes = getPathIndexes(utxo.path);
695
+ return [4 /*yield*/, this.getAddressFromExtendedPublicKey(extendedPublicKey, indexes[0], indexes[1])];
696
+ case 3:
697
+ derivedAddress = _a.sent();
698
+ if (derivedAddress.address === utxo.address) {
699
+ transaction.ins.push({
700
+ txId: utxo.txid,
701
+ value: new bignumber_1.default(utxo.value).toString(10),
702
+ vout: utxo.vout,
703
+ address: utxo.address,
704
+ derivationPath: indexes.join('/')
705
+ });
706
+ }
707
+ else {
708
+ throw new errors_1.InvalidValueError(coinlib_error_1.Domain.BITCOIN, "Invalid address ".concat(JSON.stringify(utxo.address), " returned from API"));
709
+ }
710
+ if (valueAccumulator.isGreaterThanOrEqualTo(totalRequiredBalance)) {
711
+ return [3 /*break*/, 5];
712
+ }
713
+ _a.label = 4;
714
+ case 4:
715
+ _i++;
716
+ return [3 /*break*/, 2];
717
+ case 5:
718
+ if (valueAccumulator.isLessThan(totalRequiredBalance)) {
719
+ throw new errors_1.BalanceError(coinlib_error_1.Domain.BITCOIN, 'not enough balance');
720
+ }
721
+ for (i = 0; i < recipients.length; i++) {
722
+ transaction.outs.push({
723
+ recipient: recipients[i],
724
+ isChange: false,
725
+ value: wrappedValues[i].toString(10),
726
+ derivationPath: '' // TODO: Remove this as soon as our serializer supports optional properties
727
+ });
728
+ valueAccumulator = valueAccumulator.minus(wrappedValues[i]);
729
+ }
730
+ lastUsedInternalAddress = Math.max.apply(Math, __spreadArray([-1], utxos
731
+ .map(function (utxo) { return getPathIndexes(utxo.path); })
732
+ .filter(function (indexes) { return indexes[0] === 1; })
733
+ .map(function (indexes) { return indexes[1]; }), false));
734
+ changeValue = valueAccumulator.minus(wrappedFee);
735
+ if (!changeValue.isGreaterThan(new bignumber_1.default(DUST_AMOUNT))) return [3 /*break*/, 7];
736
+ changeAddressIndex = lastUsedInternalAddress + 1;
737
+ return [4 /*yield*/, this.getAddressFromExtendedPublicKey(extendedPublicKey, 1, changeAddressIndex)];
738
+ case 6:
739
+ derivedAddress = _a.sent();
740
+ transaction.outs.push({
741
+ recipient: derivedAddress.address,
742
+ isChange: true,
743
+ value: changeValue.toString(10),
744
+ derivationPath: changeAddressIndex.toString()
745
+ });
746
+ _a.label = 7;
747
+ case 7: return [2 /*return*/, transaction];
748
+ }
749
+ });
750
+ });
751
+ };
752
+ BitcoinProtocol.prototype.prepareTransactionFromPublicKey = function (publicKey, recipients, values, fee) {
753
+ return __awaiter(this, void 0, void 0, function () {
754
+ var wrappedValues, wrappedFee, transaction, address, utxos, totalRequiredBalance, valueAccumulator, _i, utxos_2, utxo, i, changeValue;
755
+ return __generator(this, function (_a) {
756
+ switch (_a.label) {
757
+ case 0:
758
+ wrappedValues = values.map(function (value) { return new bignumber_1.default(value); });
759
+ wrappedFee = new bignumber_1.default(fee);
760
+ transaction = {
761
+ ins: [],
762
+ outs: []
763
+ };
764
+ if (recipients.length !== wrappedValues.length) {
765
+ throw new errors_1.ConditionViolationError(coinlib_error_1.Domain.BITCOIN, 'Recipient and value length does not match.');
766
+ }
767
+ return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
768
+ case 1:
769
+ address = (_a.sent()).address;
770
+ return [4 /*yield*/, index_1.default.get("".concat(this.options.network.extras.indexerApi, "/api/v2/utxo/").concat(address), {
771
+ responseType: 'json'
772
+ })];
773
+ case 2:
774
+ utxos = (_a.sent()).data;
775
+ totalRequiredBalance = wrappedValues
776
+ .reduce(function (accumulator, currentValue) { return accumulator.plus(currentValue); })
777
+ .plus(wrappedFee);
778
+ valueAccumulator = new bignumber_1.default(0);
779
+ for (_i = 0, utxos_2 = utxos; _i < utxos_2.length; _i++) {
780
+ utxo = utxos_2[_i];
781
+ valueAccumulator = valueAccumulator.plus(new bignumber_1.default(utxo.value));
782
+ transaction.ins.push({
783
+ txId: utxo.txid,
784
+ value: new bignumber_1.default(utxo.value).toString(10),
785
+ vout: utxo.vout,
786
+ address: address
787
+ });
788
+ if (valueAccumulator.isGreaterThanOrEqualTo(totalRequiredBalance)) {
789
+ break;
790
+ }
791
+ }
792
+ if (valueAccumulator.isLessThan(totalRequiredBalance)) {
793
+ throw new errors_1.BalanceError(coinlib_error_1.Domain.BITCOIN, "not enough balance, having ".concat(valueAccumulator.toFixed(), " of ").concat(totalRequiredBalance.toFixed()));
794
+ }
795
+ // tx.addInput(utxo.txid, utxo.vout)
796
+ for (i = 0; i < recipients.length; i++) {
797
+ transaction.outs.push({
798
+ recipient: recipients[i],
799
+ isChange: false,
800
+ value: wrappedValues[i].toString(10)
801
+ });
802
+ valueAccumulator = valueAccumulator.minus(wrappedValues[i]);
803
+ // tx.addOutput(recipients[i], values[i])
804
+ }
805
+ changeValue = valueAccumulator.minus(wrappedFee);
806
+ if (changeValue.isGreaterThan(new bignumber_1.default(DUST_AMOUNT))) {
807
+ transaction.outs.push({
808
+ recipient: address,
809
+ isChange: true,
810
+ value: changeValue.toString(10)
811
+ });
812
+ }
813
+ return [2 /*return*/, transaction];
814
+ }
815
+ });
816
+ });
817
+ };
818
+ BitcoinProtocol.prototype.broadcastTransaction = function (rawTransaction) {
819
+ return __awaiter(this, void 0, void 0, function () {
820
+ var data;
821
+ return __generator(this, function (_a) {
822
+ switch (_a.label) {
823
+ case 0: return [4 /*yield*/, index_1.default.post(this.options.network.extras.indexerApi + '/api/v2/sendtx/', rawTransaction)];
824
+ case 1:
825
+ data = (_a.sent()).data;
826
+ return [2 /*return*/, data.result];
827
+ }
828
+ });
829
+ });
830
+ };
831
+ BitcoinProtocol.prototype.getTransactionsFromExtendedPublicKey = function (extendedPublicKey, limit, cursor, addressOffset) {
832
+ var _a;
833
+ if (addressOffset === void 0) { addressOffset = 0; }
834
+ return __awaiter(this, void 0, void 0, function () {
835
+ var page, data, ourAddresses, airGapTransactions, _i, _b, transaction, tempAirGapTransactionFrom, tempAirGapTransactionTo, tempAirGapTransactionIsInbound, amount, _c, _d, vin, _e, _f, vout, airGapTransaction;
836
+ return __generator(this, function (_g) {
837
+ switch (_g.label) {
838
+ case 0:
839
+ page = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.page) !== null && _a !== void 0 ? _a : 1;
840
+ return [4 /*yield*/, index_1.default.get(this.options.network.extras.indexerApi +
841
+ '/api/v2/xpub/' +
842
+ extendedPublicKey +
843
+ "?details=txs&tokens=used&pageSize=".concat(limit, "&page=").concat(page), {
844
+ responseType: 'json'
845
+ })];
846
+ case 1:
847
+ data = (_g.sent()).data;
848
+ ourAddresses = (data.tokens || []).filter(function (token) { return token.type === 'XPUBAddress'; }).map(function (token) { return token.name; });
849
+ airGapTransactions = [];
850
+ if (data.page == page) {
851
+ for (_i = 0, _b = data.transactions || []; _i < _b.length; _i++) {
852
+ transaction = _b[_i];
853
+ tempAirGapTransactionFrom = [];
854
+ tempAirGapTransactionTo = [];
855
+ tempAirGapTransactionIsInbound = true;
856
+ amount = new bignumber_1.default(0);
857
+ for (_c = 0, _d = transaction.vin; _c < _d.length; _c++) {
858
+ vin = _d[_c];
859
+ if (this.containsSome(vin.addresses, ourAddresses)) {
860
+ tempAirGapTransactionIsInbound = false;
861
+ }
862
+ tempAirGapTransactionFrom.push.apply(tempAirGapTransactionFrom, vin.addresses);
863
+ amount = amount.plus(vin.value);
864
+ }
865
+ for (_e = 0, _f = transaction.vout; _e < _f.length; _e++) {
866
+ vout = _f[_e];
867
+ if (vout.addresses) {
868
+ tempAirGapTransactionTo.push.apply(tempAirGapTransactionTo, vout.addresses);
869
+ // If receiving address is our address, and transaction is outbound => our change
870
+ if (this.containsSome(vout.addresses, ourAddresses) && !tempAirGapTransactionIsInbound) {
871
+ // remove only if related to this address
872
+ amount = amount.minus(vout.value);
873
+ }
874
+ // If receiving address is not ours, and transaction isbound => senders change
875
+ if (!this.containsSome(vout.addresses, ourAddresses) && tempAirGapTransactionIsInbound) {
876
+ amount = amount.minus(vout.value);
877
+ }
878
+ }
879
+ }
880
+ // deduct fee from amount
881
+ amount = amount.minus(transaction.fees);
882
+ airGapTransaction = {
883
+ hash: transaction.txid,
884
+ from: tempAirGapTransactionFrom,
885
+ to: tempAirGapTransactionTo,
886
+ isInbound: tempAirGapTransactionIsInbound,
887
+ amount: amount.toString(10),
888
+ fee: new bignumber_1.default(transaction.fees).toString(10),
889
+ blockHeight: transaction.blockHeight.toString(),
890
+ protocolIdentifier: this.identifier,
891
+ network: this.options.network,
892
+ timestamp: transaction.blockTime
893
+ };
894
+ airGapTransactions.push(airGapTransaction);
895
+ }
896
+ }
897
+ return [2 /*return*/, {
898
+ transactions: airGapTransactions,
899
+ cursor: {
900
+ page: cursor ? cursor.page + 1 : 2
901
+ }
902
+ }];
903
+ }
904
+ });
905
+ });
906
+ };
907
+ BitcoinProtocol.prototype.getTransactionsFromPublicKey = function (publicKey, limit, cursor) {
908
+ return __awaiter(this, void 0, void 0, function () {
909
+ var address;
910
+ return __generator(this, function (_a) {
911
+ switch (_a.label) {
912
+ case 0: return [4 /*yield*/, this.getAddressFromPublicKey(publicKey)];
913
+ case 1:
914
+ address = _a.sent();
915
+ return [2 /*return*/, this.getTransactionsFromAddresses([address.address], limit, cursor)];
916
+ }
917
+ });
918
+ });
919
+ };
920
+ BitcoinProtocol.prototype.getTransactionsFromAddresses = function (addresses, limit, cursor) {
921
+ var _a;
922
+ return __awaiter(this, void 0, void 0, function () {
923
+ var airGapTransactions, page, url, data, _i, _b, transaction, tempAirGapTransactionFrom, tempAirGapTransactionTo, tempAirGapTransactionIsInbound, amount, _c, _d, vin, _e, _f, vout, airGapTransaction;
924
+ return __generator(this, function (_g) {
925
+ switch (_g.label) {
926
+ case 0:
927
+ airGapTransactions = [];
928
+ page = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.page) !== null && _a !== void 0 ? _a : 1;
929
+ url = "".concat(this.options.network.extras.indexerApi, "/api/v2/address/").concat(addresses[0], "?page=").concat(page, "&pageSize=").concat(limit, "&details=txs");
930
+ return [4 /*yield*/, index_1.default.get(url, {
931
+ responseType: 'json'
932
+ })];
933
+ case 1:
934
+ data = (_g.sent()).data;
935
+ if (data.page == page) {
936
+ for (_i = 0, _b = data.transactions || []; _i < _b.length; _i++) {
937
+ transaction = _b[_i];
938
+ tempAirGapTransactionFrom = [];
939
+ tempAirGapTransactionTo = [];
940
+ tempAirGapTransactionIsInbound = true;
941
+ amount = new bignumber_1.default(0);
942
+ for (_c = 0, _d = transaction.vin; _c < _d.length; _c++) {
943
+ vin = _d[_c];
944
+ if (vin.addresses && this.containsSome(vin.addresses, addresses)) {
945
+ tempAirGapTransactionIsInbound = false;
946
+ }
947
+ tempAirGapTransactionFrom.push.apply(tempAirGapTransactionFrom, vin.addresses);
948
+ amount = vin.value ? amount.plus(vin.value) : amount;
949
+ }
950
+ for (_e = 0, _f = transaction.vout; _e < _f.length; _e++) {
951
+ vout = _f[_e];
952
+ if (vout.addresses) {
953
+ tempAirGapTransactionTo.push.apply(tempAirGapTransactionTo, vout.addresses);
954
+ // If receiving address is our address, and transaction is outbound => our change
955
+ if (this.containsSome(vout.addresses, addresses) && !tempAirGapTransactionIsInbound) {
956
+ // remove only if related to this address
957
+ amount = amount.minus(new bignumber_1.default(vout.value));
958
+ }
959
+ // If receiving address is not ours, and transaction isbound => senders change
960
+ if (!this.containsSome(vout.addresses, addresses) && tempAirGapTransactionIsInbound) {
961
+ amount = amount.minus(new bignumber_1.default(vout.value));
962
+ }
963
+ }
964
+ }
965
+ // deduct fee from amount
966
+ amount = amount.minus(new bignumber_1.default(transaction.fees));
967
+ airGapTransaction = {
968
+ hash: transaction.txid,
969
+ from: tempAirGapTransactionFrom,
970
+ to: tempAirGapTransactionTo,
971
+ isInbound: tempAirGapTransactionIsInbound,
972
+ amount: amount.toString(10),
973
+ fee: new bignumber_1.default(transaction.fees).toString(10),
974
+ blockHeight: transaction.blockHeight.toString(),
975
+ protocolIdentifier: this.identifier,
976
+ network: this.options.network,
977
+ timestamp: transaction.blockTime
978
+ };
979
+ airGapTransactions.push(airGapTransaction);
980
+ }
981
+ }
982
+ return [2 /*return*/, {
983
+ transactions: airGapTransactions,
984
+ cursor: {
985
+ page: cursor ? cursor.page + 1 : 2
986
+ }
987
+ }];
988
+ }
989
+ });
990
+ });
991
+ };
992
+ BitcoinProtocol.prototype.containsSome = function (needles, haystack) {
993
+ for (var _i = 0, needles_1 = needles; _i < needles_1.length; _i++) {
994
+ var needle = needles_1[_i];
995
+ if (haystack.indexOf(needle) > -1) {
996
+ return true;
997
+ }
998
+ }
999
+ return false;
1000
+ };
1001
+ BitcoinProtocol.prototype.signMessage = function (message, keypair) {
1002
+ return __awaiter(this, void 0, void 0, function () {
1003
+ return __generator(this, function (_a) {
1004
+ return [2 /*return*/, this.cryptoClient.signMessage(message, keypair)];
1005
+ });
1006
+ });
1007
+ };
1008
+ BitcoinProtocol.prototype.verifyMessage = function (message, signature, publicKey) {
1009
+ return __awaiter(this, void 0, void 0, function () {
1010
+ return __generator(this, function (_a) {
1011
+ return [2 /*return*/, this.cryptoClient.verifyMessage(message, signature, publicKey)];
1012
+ });
1013
+ });
1014
+ };
1015
+ BitcoinProtocol.prototype.encryptAsymmetric = function (message, publicKey) {
1016
+ return __awaiter(this, void 0, void 0, function () {
1017
+ var childPublicKey;
1018
+ return __generator(this, function (_a) {
1019
+ childPublicKey = this.options.config.bitcoinJSLib.HDNode.fromBase58(publicKey, this.options.network.extras.network)
1020
+ .derive(0)
1021
+ .derive(0)
1022
+ .getPublicKeyBuffer();
1023
+ return [2 /*return*/, this.cryptoClient.encryptAsymmetric(message, childPublicKey)];
1024
+ });
1025
+ });
1026
+ };
1027
+ BitcoinProtocol.prototype.decryptAsymmetric = function (message, keypair) {
1028
+ return __awaiter(this, void 0, void 0, function () {
1029
+ var childPrivateKey;
1030
+ return __generator(this, function (_a) {
1031
+ childPrivateKey = this.options.config.bitcoinJSLib.HDNode.fromBase58(keypair.privateKey, this.options.network.extras.network)
1032
+ .derive(0)
1033
+ .derive(0)
1034
+ .keyPair.d.toBuffer(32);
1035
+ return [2 /*return*/, this.cryptoClient.decryptAsymmetric(message, { publicKey: '', privateKey: childPrivateKey.toString('hex') })];
1036
+ });
1037
+ });
1038
+ };
1039
+ BitcoinProtocol.prototype.encryptAES = function (message, privateKey) {
1040
+ return __awaiter(this, void 0, void 0, function () {
1041
+ return __generator(this, function (_a) {
1042
+ return [2 /*return*/, this.cryptoClient.encryptAES(message, privateKey)];
1043
+ });
1044
+ });
1045
+ };
1046
+ BitcoinProtocol.prototype.decryptAES = function (message, privateKey) {
1047
+ return __awaiter(this, void 0, void 0, function () {
1048
+ return __generator(this, function (_a) {
1049
+ return [2 /*return*/, this.cryptoClient.decryptAES(message, privateKey)];
1050
+ });
1051
+ });
1052
+ };
1053
+ BitcoinProtocol.prototype.getTransactionStatuses = function (transactionHashes) {
1054
+ return __awaiter(this, void 0, void 0, function () {
1055
+ return __generator(this, function (_a) {
1056
+ return [2 /*return*/, Promise.reject('Transaction status not implemented')];
1057
+ });
1058
+ });
1059
+ };
1060
+ return BitcoinProtocol;
1061
+ }());
1062
+ exports.BitcoinProtocol = BitcoinProtocol;
1063
+ //# sourceMappingURL=BitcoinProtocol.js.map