@teleportdao/bitcoin 1.4.3 → 1.4.4

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 (44) hide show
  1. package/dist/bitcoin-base.d.ts +17 -16
  2. package/dist/bitcoin-base.d.ts.map +1 -1
  3. package/dist/bitcoin-base.js +12 -7
  4. package/dist/bitcoin-base.js.map +1 -1
  5. package/dist/bitcoin-utils.d.ts +1 -1
  6. package/dist/bitcoin-utils.d.ts.map +1 -1
  7. package/dist/bitcoin-utils.js +3 -0
  8. package/dist/bitcoin-utils.js.map +1 -1
  9. package/dist/bundle.js +4 -0
  10. package/dist/index.d.ts +5 -5
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +14 -12
  13. package/dist/index.js.map +1 -1
  14. package/dist/sign/sign-transaction.d.ts +9 -5
  15. package/dist/sign/sign-transaction.d.ts.map +1 -1
  16. package/dist/sign/sign-transaction.js +14 -11
  17. package/dist/sign/sign-transaction.js.map +1 -1
  18. package/dist/teleport-dao-payments.d.ts +17 -6
  19. package/dist/teleport-dao-payments.d.ts.map +1 -1
  20. package/dist/teleport-dao-payments.js +4 -3
  21. package/dist/teleport-dao-payments.js.map +1 -1
  22. package/dist/transaction-builder/bitcoin-transaction-builder.d.ts +26 -11
  23. package/dist/transaction-builder/bitcoin-transaction-builder.d.ts.map +1 -1
  24. package/dist/transaction-builder/bitcoin-transaction-builder.js +36 -8
  25. package/dist/transaction-builder/bitcoin-transaction-builder.js.map +1 -1
  26. package/dist/transaction-builder/transaction-builder.d.ts +148 -9
  27. package/dist/transaction-builder/transaction-builder.d.ts.map +1 -1
  28. package/dist/transaction-builder/transaction-builder.js +230 -30
  29. package/dist/transaction-builder/transaction-builder.js.map +1 -1
  30. package/package.json +7 -5
  31. package/src/bitcoin-base.js +220 -219
  32. package/src/bitcoin-interface.js +350 -350
  33. package/src/bitcoin-utils.js +487 -483
  34. package/src/helper/teleport-request-helper.js +179 -179
  35. package/src/index.ts +8 -0
  36. package/src/sign/sign-transaction.ts +96 -0
  37. package/src/teleport-dao-payments.js +280 -280
  38. package/src/transaction-builder/bitcoin-transaction-builder.ts +57 -0
  39. package/src/transaction-builder/transaction-builder.ts +490 -0
  40. package/src/index.js +0 -15
  41. package/src/sign/sign-transaction.js +0 -36
  42. package/src/transaction-builder/bitcoin-transaction-builder.js +0 -37
  43. package/src/transaction-builder/transaction-builder-common.js +0 -236
  44. package/src/transaction-builder/transaction-builder.js +0 -159
@@ -1,483 +1,487 @@
1
- const bip39 = require("bip39")
2
- const bip32 = require("bip32")
3
- let varUnit = require("varuint-bitcoin")
4
- const fastRoot = require("merkle-lib/fastRoot")
5
- const merkle = require("merkle-lib")
6
- const merkleProof = require("merkle-lib/proof")
7
- const bitcoin = require("bitcoinjs-lib")
8
- const networks = require("./utils/networks")
9
-
10
- function generateMnemonic() {
11
- const mnemonic = bip39.generateMnemonic(256)
12
- return mnemonic
13
- }
14
-
15
- function parseRawTransaction(rawTransaction) {
16
- const size = {
17
- version: 4,
18
- flag: 2,
19
- tx: 32,
20
- index: 4,
21
- sequence: 4,
22
- amount: 8,
23
- }
24
-
25
- let offset = 0
26
- let version = rawTransaction.slice(offset, size.version * 2)
27
- offset += size.version * 2
28
- let flag = rawTransaction.slice(offset, offset + size.flag * 2)
29
- offset = flag === "0001" ? offset + size.flag * 2 : offset // * 0x0001 is flag in segwit transactions
30
-
31
- let inputsStartIndex = offset
32
-
33
- let numberOfInputs = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
34
- let noiSize = varUnit.encodingLength(numberOfInputs)
35
- offset += noiSize * 2
36
-
37
- for (let i = 0; i < numberOfInputs; i += 1) {
38
- offset += size.tx * 2
39
- offset += size.index * 2
40
- let sigLength = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
41
- let sigLengthSize = varUnit.encodingLength(sigLength)
42
- offset += sigLengthSize * 2
43
- offset += sigLength * 2
44
- offset += size.sequence * 2
45
- }
46
- let inputLastIndex = offset
47
- let outputStartIndex = offset
48
-
49
- let numberOfOutputs = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
50
- let nooSize = varUnit.encodingLength(numberOfOutputs)
51
- offset += nooSize * 2
52
-
53
- for (let i = 0; i < numberOfOutputs; i += 1) {
54
- offset += size.amount * 2
55
- let unlockSigLength = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
56
- let unlockSigLengthSize = varUnit.encodingLength(unlockSigLength)
57
- offset += unlockSigLengthSize * 2
58
- offset += unlockSigLength * 2
59
- }
60
- let outputLastIndex = offset
61
-
62
- version = `0x${version}`
63
- flag = `0x${flag}`
64
- const vin = `0x${rawTransaction.slice(inputsStartIndex, inputLastIndex)}`
65
- const vout = `0x${rawTransaction.slice(outputStartIndex, outputLastIndex)}`
66
- let witness = `0x${rawTransaction.slice(outputLastIndex, rawTransaction.length - 8)}`
67
- let locktime = `0x${rawTransaction.slice(rawTransaction.length - 8, rawTransaction.length)}`
68
- return { version, flag, vin, vout, witness, locktime }
69
- }
70
-
71
- function reverseBytes(hexInput) {
72
- return Buffer.from(hexInput, "hex").reverse().toString("hex")
73
- }
74
-
75
- function getAddressType(address, network = bitcoin.networks.bitcoin) {
76
- if (address.startsWith(network.bech32)) {
77
- // todo : check length - it could be p2wsh
78
- return "p2wpkh"
79
- }
80
- let base58Data = bitcoin.address.fromBase58Check(address)
81
- if (base58Data.version === Number(network.scriptHash)) {
82
- return "p2sh"
83
- }
84
- if (base58Data.version === Number(network.pubKeyHash)) {
85
- return "p2pkh"
86
- }
87
-
88
- throw new Error("invalid address")
89
- }
90
-
91
- function createAddressObjectByHash({ addressType, hash }, network = bitcoin.networks.bitcoin) {
92
- let addressObject
93
- switch (addressType) {
94
- case "p2pkh":
95
- addressObject = bitcoin.payments.p2pkh({
96
- hash,
97
- network,
98
- })
99
- break
100
- case "p2wpkh":
101
- addressObject = bitcoin.payments.p2wpkh({
102
- hash,
103
- network,
104
- })
105
- break
106
- case "p2sh":
107
- addressObject = bitcoin.payments.p2sh({
108
- hash,
109
- network,
110
- })
111
- break
112
- default:
113
- throw new Error("address type is incorrect")
114
- }
115
- return addressObject
116
- }
117
-
118
- function createAddressObjectByScript({ addressType, script }, network = bitcoin.networks.bitcoin) {
119
- let addressObject
120
- switch (addressType) {
121
- case "p2pkh":
122
- addressObject = bitcoin.payments.p2pkh({
123
- output: script,
124
- network,
125
- })
126
- break
127
- case "p2wpkh":
128
- addressObject = bitcoin.payments.p2wpkh({
129
- output: script,
130
- network,
131
- })
132
- break
133
- case "p2sh":
134
- addressObject = bitcoin.payments.p2sh({
135
- output: script,
136
- network,
137
- })
138
- break
139
- default:
140
- throw new Error("address type is incorrect")
141
- }
142
- return addressObject
143
- }
144
-
145
- function createAddressObjectByPublicKey(
146
- { addressType, publicKey },
147
- network = bitcoin.networks.bitcoin,
148
- ) {
149
- let addressObject
150
-
151
- switch (addressType) {
152
- case "p2pkh":
153
- addressObject = bitcoin.payments.p2pkh({
154
- pubkey: publicKey,
155
- network,
156
- })
157
- break
158
- case "p2wpkh":
159
- addressObject = bitcoin.payments.p2wpkh({
160
- pubkey: publicKey,
161
- network,
162
- })
163
- break
164
- case "p2sh-p2wpkh":
165
- addressObject = bitcoin.payments.p2sh({
166
- redeem: bitcoin.payments.p2wpkh({
167
- pubkey: publicKey,
168
- network,
169
- }),
170
- })
171
- break
172
- default:
173
- throw new Error("address type is incorrect")
174
- }
175
- return addressObject
176
- }
177
-
178
- function createAddressObjectByAddress(address, network = bitcoin.networks.bitcoin) {
179
- let addressType = getAddressType(address, network)
180
- let addressObject
181
- switch (addressType) {
182
- case "p2pkh":
183
- addressObject = bitcoin.payments.p2pkh({
184
- address,
185
- network,
186
- })
187
- break
188
- case "p2wpkh":
189
- addressObject = bitcoin.payments.p2wpkh({
190
- address,
191
- network,
192
- })
193
- break
194
- case "p2sh":
195
- addressObject = bitcoin.payments.p2sh({
196
- address,
197
- network,
198
- })
199
- break
200
- default:
201
- throw new Error("address type is incorrect")
202
- }
203
- return { addressObject, addressType }
204
- }
205
-
206
- function getPublicKeyHexByXpubAndIndex(
207
- xpub,
208
- index = 0,
209
- isChange = false,
210
- network = networks.bitcoin,
211
- ) {
212
- const node = bip32.fromBase58(xpub, network)
213
- return node
214
- .derive(isChange ? 1 : 0)
215
- .derive(index)
216
- .publicKey.toString("hex")
217
- }
218
-
219
- function getPubKeyFromPrivateKeyWIF(privateKeyWIF, network = bitcoin.networks.bitcoin) {
220
- let key = bitcoin.ECPair.fromWIF(privateKeyWIF, network)
221
- return key.publicKey
222
- }
223
-
224
- function getPubKeyFromPrivateKeyHex(privateKeyHex, network = bitcoin.networks.bitcoin) {
225
- let key = bitcoin.ECPair.fromPrivateKey(Buffer.from(privateKeyHex, "hex"), network)
226
- return key.publicKey
227
- }
228
-
229
- function getPrivateKeyHexFromWIF(privateKeyWIF, network = bitcoin.networks.bitcoin) {
230
- let key = bitcoin.ECPair.fromWIF(privateKeyWIF, network)
231
- return key.privateKey.toString("hex")
232
- }
233
-
234
- function calculateMerkleProof(blockTransactions, txId, blockMerkleRoot = undefined) {
235
- let transactionIndex = blockTransactions.findIndex((tx) => tx === txId)
236
- if (transactionIndex < 0) throw new Error("txId is not in this tree")
237
- let data = blockTransactions.map((a) => Buffer.from(a, "hex").reverse())
238
-
239
- if (
240
- blockMerkleRoot &&
241
- blockMerkleRoot !== fastRoot(data, bitcoin.crypto.hash256).toString("hex")
242
- ) {
243
- throw new Error("calculated anf block merkleRoot not matched")
244
- }
245
-
246
- let tree = merkle(data, bitcoin.crypto.hash256)
247
- let proof = merkleProof(tree, data[transactionIndex])
248
-
249
- let intermediateNodesArray = proof
250
- .map((_id) => _id && _id.toString("hex"))
251
- .filter((_id) => _id != null)
252
- let intermediateNodes = intermediateNodesArray.reduce(
253
- (a, value, index) =>
254
- index !== transactionIndex % 2 && index < intermediateNodesArray.length - 1 ? a + value : a,
255
- "0x",
256
- )
257
- return {
258
- intermediateNodes,
259
- transactionIndex,
260
- }
261
- }
262
-
263
- function parseBlockHeader(headerHex) {
264
- const size = {
265
- version: 4,
266
- previousBlockHash: 32,
267
- merkleRoot: 32,
268
- timestamp: 4,
269
- difficulty: 4,
270
- nonce: 4,
271
- }
272
- let offset = 0
273
- let result = {}
274
- for (let key in size) {
275
- result[key] = headerHex.slice(offset, offset + size[key] * 2)
276
- offset += size[key] * 2
277
- }
278
- return result
279
- }
280
-
281
- function convertBitcoinScriptToAddress(script, network = bitcoin.networks.bitcoin) {
282
- try {
283
- return bitcoin.address?.fromOutputScript(script, network)
284
- } catch (error) {
285
- return null
286
- }
287
- }
288
-
289
- function parseRawBlock(rawBlockHex, blockNumber = undefined, network = bitcoin.networks.network) {
290
- let block = bitcoin.Block.fromBuffer(Buffer.from(rawBlockHex, "hex"))
291
- let blockHash = block.getHash().toString("hex")
292
- let merkleRoot = block.merkleRoot.toString("hex")
293
- let prvBlockHash = block.prevHash.toString("hex")
294
- return {
295
- blockNumber,
296
- merkleRoot,
297
- prvBlockHash,
298
- transactions: block.transactions.map((tx) => ({
299
- txId: tx.getId(),
300
- version: tx.version,
301
- locktime: tx.locktime,
302
- blockNumber,
303
- blockHash,
304
- vout: tx.outs.map((vo, index) => ({
305
- address: convertBitcoinScriptToAddress(vo.script, network),
306
- script: vo.script.toString("hex"),
307
- value: vo.value,
308
- index,
309
- })),
310
- vin: tx.ins.map((vi) => ({
311
- txId: Buffer.from(vi.hash).reverse().toString("hex"),
312
- index: vi.index,
313
- })),
314
- })),
315
- }
316
- }
317
-
318
- function extractTransactionsAndBlockInfoFromRawBlock(
319
- rawBlockHex,
320
- blockNumber,
321
- addresses = [],
322
- /**
323
- * inputTxIds = {
324
- * txId : string
325
- * index: number
326
- * }[]
327
- */
328
- inputTxIds = [],
329
- network = bitcoin.networks.bitcoin,
330
- ) {
331
- let block = bitcoin.Block.fromBuffer(Buffer.from(rawBlockHex, "hex"))
332
- let blockHash = block.getHash().reverse().toString("hex")
333
- let merkleRoot = block.merkleRoot.toString("hex")
334
- let prvBlockHash = block.prevHash.toString("hex")
335
-
336
- let blockInfo = {
337
- blockNumber,
338
- blockHash,
339
- merkleRoot,
340
- prvBlockHash,
341
- }
342
-
343
- let addressScript = addresses.map((address) =>
344
- createAddressObjectByAddress(address, network).addressObject.output.toString("hex"),
345
- )
346
-
347
- let blockTxIds = block.transactions.map((tx) => tx.getId())
348
-
349
- let withdrawTxs = []
350
- let depositTxs = []
351
- block.transactions.forEach((tx) => {
352
- let txId = tx.getId()
353
-
354
- let inputTxAddress
355
- let isWithdraw = tx.ins.find((vi) => {
356
- let viTxId = Buffer.from(vi.hash).reverse().toString("hex")
357
- let viInput = inputTxIds.find((vin) => vin.txId === viTxId && vin.index === vi.index)
358
- inputTxAddress = viInput?.address
359
- return !!inputTxAddress
360
- })
361
- if (isWithdraw && inputTxAddress) {
362
- let txMerkleProof = calculateMerkleProof(blockTxIds, txId, merkleRoot)
363
-
364
- withdrawTxs.push({
365
- txId: tx.getId(),
366
- version: tx.version,
367
- locktime: tx.locktime,
368
- blockNumber,
369
- blockHash,
370
- merkleProof: txMerkleProof,
371
- vout: tx.outs.map((vo) => ({
372
- address: convertBitcoinScriptToAddress(vo.script, network),
373
- script: vo.script.toString("hex"),
374
- value: vo.value,
375
- })),
376
- vin: tx.ins.map((vi) => {
377
- let viTxId = Buffer.from(vi.hash).reverse().toString("hex")
378
- let viInput = inputTxIds.find((vin) => vin.txId === viTxId && vin.index === vi.index)
379
- return {
380
- txId: Buffer.from(vi.hash).reverse().toString("hex"),
381
- index: vi.index,
382
- address: viInput.address || null,
383
- script: viInput.script || null,
384
- value: viInput.value || null,
385
- }
386
- }),
387
- address: inputTxAddress,
388
- addressScript: createAddressObjectByAddress(
389
- inputTxAddress,
390
- network,
391
- ).addressObject.output.toString("hex"),
392
- })
393
- }
394
-
395
- let addressIndex
396
- let isDeposit = tx.outs.find((blockTxVo) => {
397
- let sIndex = addressScript.findIndex(
398
- (addScript) => addScript === blockTxVo.script.toString("hex"),
399
- )
400
- if (sIndex >= 0) {
401
- addressIndex = sIndex
402
- return true
403
- }
404
- return false
405
- })
406
-
407
- if (isDeposit && addressIndex >= 0) {
408
- // todo we can optimize this calculation (in following function, merkle tree calculate each times but we can do this once for block)
409
- let txMerkleProof = calculateMerkleProof(blockTxIds, txId, merkleRoot)
410
- depositTxs.push({
411
- txId: tx.getId(),
412
- version: tx.version,
413
- locktime: tx.locktime,
414
- blockNumber,
415
- blockHash,
416
- merkleProof: txMerkleProof,
417
- vout: tx.outs.map((vo) => ({
418
- address: convertBitcoinScriptToAddress(vo.script, network),
419
- script: vo.script.toString("hex"),
420
- value: vo.value,
421
- })),
422
- vin: tx.ins.map((vi) => ({
423
- txId: Buffer.from(vi.hash).reverse().toString("hex"),
424
- index: vi.index,
425
- })),
426
- addressScript: addressScript[addressIndex],
427
- address: addresses[addressIndex],
428
- })
429
- }
430
- })
431
- return {
432
- blockInfo,
433
- withdrawTxs,
434
- depositTxs,
435
- }
436
- }
437
-
438
- function validateAddress(address, network = bitcoin.networks.bitcoin) {
439
- try {
440
- let isValid = false
441
- let isAddressSegwit = address.startsWith(network.bech32)
442
- if (isAddressSegwit) {
443
- bitcoin.address.fromBech32(address)
444
- isValid = true
445
- } else {
446
- let base58Data = bitcoin.address.fromBase58Check(address)
447
- isValid =
448
- base58Data.version === Number(network.scriptHash) ||
449
- base58Data.version === Number(network.pubKeyHash)
450
- }
451
- return isValid
452
- } catch (error) {
453
- return false
454
- }
455
- }
456
-
457
- module.exports = {
458
- parseRawTransaction,
459
- calculateMerkleProof,
460
- createAddressObjectByHash,
461
- createAddressObjectByPublicKey,
462
- createAddressObjectByAddress,
463
- createAddressObjectByScript,
464
-
465
- // ------------------------
466
- getAddressType,
467
- getPubKeyFromPrivateKeyWIF,
468
- getPubKeyFromPrivateKeyHex,
469
- getPublicKeyHexByXpubAndIndex,
470
- getPrivateKeyHexFromWIF,
471
- reverseBytes,
472
-
473
- parseBlockHeader,
474
- generateMnemonic,
475
-
476
- // ---------------------------
477
- parseRawBlock,
478
- extractTransactionsAndBlockInfoFromRawBlock,
479
- // -----------------------------
480
- validateAddress,
481
-
482
- networks,
483
- }
1
+ const bip39 = require("bip39")
2
+ const bip32 = require("bip32")
3
+ let varUnit = require("varuint-bitcoin")
4
+ const fastRoot = require("merkle-lib/fastRoot")
5
+ const merkle = require("merkle-lib")
6
+ const merkleProof = require("merkle-lib/proof")
7
+ const bitcoin = require("bitcoinjs-lib")
8
+ const networks = require("./utils/networks")
9
+
10
+ function generateMnemonic() {
11
+ const mnemonic = bip39.generateMnemonic(256)
12
+ return mnemonic
13
+ }
14
+
15
+ function parseRawTransaction(rawTransaction) {
16
+ const size = {
17
+ version: 4,
18
+ flag: 2,
19
+ tx: 32,
20
+ index: 4,
21
+ sequence: 4,
22
+ amount: 8,
23
+ }
24
+
25
+ let offset = 0
26
+ let version = rawTransaction.slice(offset, size.version * 2)
27
+ offset += size.version * 2
28
+ let flag = rawTransaction.slice(offset, offset + size.flag * 2)
29
+ offset = flag === "0001" ? offset + size.flag * 2 : offset // * 0x0001 is flag in segwit transactions
30
+
31
+ let inputsStartIndex = offset
32
+
33
+ let numberOfInputs = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
34
+ let noiSize = varUnit.encodingLength(numberOfInputs)
35
+ offset += noiSize * 2
36
+
37
+ for (let i = 0; i < numberOfInputs; i += 1) {
38
+ offset += size.tx * 2
39
+ offset += size.index * 2
40
+ let sigLength = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
41
+ let sigLengthSize = varUnit.encodingLength(sigLength)
42
+ offset += sigLengthSize * 2
43
+ offset += sigLength * 2
44
+ offset += size.sequence * 2
45
+ }
46
+ let inputLastIndex = offset
47
+ let outputStartIndex = offset
48
+
49
+ let numberOfOutputs = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
50
+ let nooSize = varUnit.encodingLength(numberOfOutputs)
51
+ offset += nooSize * 2
52
+
53
+ for (let i = 0; i < numberOfOutputs; i += 1) {
54
+ offset += size.amount * 2
55
+ let unlockSigLength = varUnit.decode(Buffer.from(rawTransaction.slice(offset), "hex"))
56
+ let unlockSigLengthSize = varUnit.encodingLength(unlockSigLength)
57
+ offset += unlockSigLengthSize * 2
58
+ offset += unlockSigLength * 2
59
+ }
60
+ let outputLastIndex = offset
61
+
62
+ version = `0x${version}`
63
+ flag = `0x${flag}`
64
+ const vin = `0x${rawTransaction.slice(inputsStartIndex, inputLastIndex)}`
65
+ const vout = `0x${rawTransaction.slice(outputStartIndex, outputLastIndex)}`
66
+ let witness = `0x${rawTransaction.slice(outputLastIndex, rawTransaction.length - 8)}`
67
+ let locktime = `0x${rawTransaction.slice(rawTransaction.length - 8, rawTransaction.length)}`
68
+ return { version, flag, vin, vout, witness, locktime }
69
+ }
70
+
71
+ function reverseBytes(hexInput) {
72
+ return Buffer.from(hexInput, "hex").reverse().toString("hex")
73
+ }
74
+
75
+ function getAddressType(address, network = bitcoin.networks.bitcoin) {
76
+ if (address.startsWith(`${network.bech32}1p`)) {
77
+ // todo : check length - it could be p2wsh
78
+ return "p2tr"
79
+ }
80
+ if (address.startsWith(network.bech32)) {
81
+ // todo : check length - it could be p2wsh
82
+ return "p2wpkh"
83
+ }
84
+ let base58Data = bitcoin.address.fromBase58Check(address)
85
+ if (base58Data.version === Number(network.scriptHash)) {
86
+ return "p2sh"
87
+ }
88
+ if (base58Data.version === Number(network.pubKeyHash)) {
89
+ return "p2pkh"
90
+ }
91
+
92
+ throw new Error("invalid address")
93
+ }
94
+
95
+ function createAddressObjectByHash({ addressType, hash }, network = bitcoin.networks.bitcoin) {
96
+ let addressObject
97
+ switch (addressType) {
98
+ case "p2pkh":
99
+ addressObject = bitcoin.payments.p2pkh({
100
+ hash,
101
+ network,
102
+ })
103
+ break
104
+ case "p2wpkh":
105
+ addressObject = bitcoin.payments.p2wpkh({
106
+ hash,
107
+ network,
108
+ })
109
+ break
110
+ case "p2sh":
111
+ addressObject = bitcoin.payments.p2sh({
112
+ hash,
113
+ network,
114
+ })
115
+ break
116
+ default:
117
+ throw new Error("address type is incorrect")
118
+ }
119
+ return addressObject
120
+ }
121
+
122
+ function createAddressObjectByScript({ addressType, script }, network = bitcoin.networks.bitcoin) {
123
+ let addressObject
124
+ switch (addressType) {
125
+ case "p2pkh":
126
+ addressObject = bitcoin.payments.p2pkh({
127
+ output: script,
128
+ network,
129
+ })
130
+ break
131
+ case "p2wpkh":
132
+ addressObject = bitcoin.payments.p2wpkh({
133
+ output: script,
134
+ network,
135
+ })
136
+ break
137
+ case "p2sh":
138
+ addressObject = bitcoin.payments.p2sh({
139
+ output: script,
140
+ network,
141
+ })
142
+ break
143
+ default:
144
+ throw new Error("address type is incorrect")
145
+ }
146
+ return addressObject
147
+ }
148
+
149
+ function createAddressObjectByPublicKey(
150
+ { addressType, publicKey },
151
+ network = bitcoin.networks.bitcoin,
152
+ ) {
153
+ let addressObject
154
+
155
+ switch (addressType) {
156
+ case "p2pkh":
157
+ addressObject = bitcoin.payments.p2pkh({
158
+ pubkey: publicKey,
159
+ network,
160
+ })
161
+ break
162
+ case "p2wpkh":
163
+ addressObject = bitcoin.payments.p2wpkh({
164
+ pubkey: publicKey,
165
+ network,
166
+ })
167
+ break
168
+ case "p2sh-p2wpkh":
169
+ addressObject = bitcoin.payments.p2sh({
170
+ redeem: bitcoin.payments.p2wpkh({
171
+ pubkey: publicKey,
172
+ network,
173
+ }),
174
+ })
175
+ break
176
+ default:
177
+ throw new Error("address type is incorrect")
178
+ }
179
+ return addressObject
180
+ }
181
+
182
+ function createAddressObjectByAddress(address, network = bitcoin.networks.bitcoin) {
183
+ let addressType = getAddressType(address, network)
184
+ let addressObject
185
+ switch (addressType) {
186
+ case "p2pkh":
187
+ addressObject = bitcoin.payments.p2pkh({
188
+ address,
189
+ network,
190
+ })
191
+ break
192
+ case "p2wpkh":
193
+ addressObject = bitcoin.payments.p2wpkh({
194
+ address,
195
+ network,
196
+ })
197
+ break
198
+ case "p2sh":
199
+ addressObject = bitcoin.payments.p2sh({
200
+ address,
201
+ network,
202
+ })
203
+ break
204
+ default:
205
+ throw new Error("address type is incorrect")
206
+ }
207
+ return { addressObject, addressType }
208
+ }
209
+
210
+ function getPublicKeyHexByXpubAndIndex(
211
+ xpub,
212
+ index = 0,
213
+ isChange = false,
214
+ network = networks.bitcoin,
215
+ ) {
216
+ const node = bip32.fromBase58(xpub, network)
217
+ return node
218
+ .derive(isChange ? 1 : 0)
219
+ .derive(index)
220
+ .publicKey.toString("hex")
221
+ }
222
+
223
+ function getPubKeyFromPrivateKeyWIF(privateKeyWIF, network = bitcoin.networks.bitcoin) {
224
+ let key = bitcoin.ECPair.fromWIF(privateKeyWIF, network)
225
+ return key.publicKey
226
+ }
227
+
228
+ function getPubKeyFromPrivateKeyHex(privateKeyHex, network = bitcoin.networks.bitcoin) {
229
+ let key = bitcoin.ECPair.fromPrivateKey(Buffer.from(privateKeyHex, "hex"), network)
230
+ return key.publicKey
231
+ }
232
+
233
+ function getPrivateKeyHexFromWIF(privateKeyWIF, network = bitcoin.networks.bitcoin) {
234
+ let key = bitcoin.ECPair.fromWIF(privateKeyWIF, network)
235
+ return key.privateKey.toString("hex")
236
+ }
237
+
238
+ function calculateMerkleProof(blockTransactions, txId, blockMerkleRoot = undefined) {
239
+ let transactionIndex = blockTransactions.findIndex((tx) => tx === txId)
240
+ if (transactionIndex < 0) throw new Error("txId is not in this tree")
241
+ let data = blockTransactions.map((a) => Buffer.from(a, "hex").reverse())
242
+
243
+ if (
244
+ blockMerkleRoot &&
245
+ blockMerkleRoot !== fastRoot(data, bitcoin.crypto.hash256).toString("hex")
246
+ ) {
247
+ throw new Error("calculated anf block merkleRoot not matched")
248
+ }
249
+
250
+ let tree = merkle(data, bitcoin.crypto.hash256)
251
+ let proof = merkleProof(tree, data[transactionIndex])
252
+
253
+ let intermediateNodesArray = proof
254
+ .map((_id) => _id && _id.toString("hex"))
255
+ .filter((_id) => _id != null)
256
+ let intermediateNodes = intermediateNodesArray.reduce(
257
+ (a, value, index) =>
258
+ index !== transactionIndex % 2 && index < intermediateNodesArray.length - 1 ? a + value : a,
259
+ "0x",
260
+ )
261
+ return {
262
+ intermediateNodes,
263
+ transactionIndex,
264
+ }
265
+ }
266
+
267
+ function parseBlockHeader(headerHex) {
268
+ const size = {
269
+ version: 4,
270
+ previousBlockHash: 32,
271
+ merkleRoot: 32,
272
+ timestamp: 4,
273
+ difficulty: 4,
274
+ nonce: 4,
275
+ }
276
+ let offset = 0
277
+ let result = {}
278
+ for (let key in size) {
279
+ result[key] = headerHex.slice(offset, offset + size[key] * 2)
280
+ offset += size[key] * 2
281
+ }
282
+ return result
283
+ }
284
+
285
+ function convertBitcoinScriptToAddress(script, network = bitcoin.networks.bitcoin) {
286
+ try {
287
+ return bitcoin.address?.fromOutputScript(script, network)
288
+ } catch (error) {
289
+ return null
290
+ }
291
+ }
292
+
293
+ function parseRawBlock(rawBlockHex, blockNumber = undefined, network = bitcoin.networks.network) {
294
+ let block = bitcoin.Block.fromBuffer(Buffer.from(rawBlockHex, "hex"))
295
+ let blockHash = block.getHash().toString("hex")
296
+ let merkleRoot = block.merkleRoot.toString("hex")
297
+ let prvBlockHash = block.prevHash.toString("hex")
298
+ return {
299
+ blockNumber,
300
+ merkleRoot,
301
+ prvBlockHash,
302
+ transactions: block.transactions.map((tx) => ({
303
+ txId: tx.getId(),
304
+ version: tx.version,
305
+ locktime: tx.locktime,
306
+ blockNumber,
307
+ blockHash,
308
+ vout: tx.outs.map((vo, index) => ({
309
+ address: convertBitcoinScriptToAddress(vo.script, network),
310
+ script: vo.script.toString("hex"),
311
+ value: vo.value,
312
+ index,
313
+ })),
314
+ vin: tx.ins.map((vi) => ({
315
+ txId: Buffer.from(vi.hash).reverse().toString("hex"),
316
+ index: vi.index,
317
+ })),
318
+ })),
319
+ }
320
+ }
321
+
322
+ function extractTransactionsAndBlockInfoFromRawBlock(
323
+ rawBlockHex,
324
+ blockNumber,
325
+ addresses = [],
326
+ /**
327
+ * inputTxIds = {
328
+ * txId : string
329
+ * index: number
330
+ * }[]
331
+ */
332
+ inputTxIds = [],
333
+ network = bitcoin.networks.bitcoin,
334
+ ) {
335
+ let block = bitcoin.Block.fromBuffer(Buffer.from(rawBlockHex, "hex"))
336
+ let blockHash = block.getHash().reverse().toString("hex")
337
+ let merkleRoot = block.merkleRoot.toString("hex")
338
+ let prvBlockHash = block.prevHash.toString("hex")
339
+
340
+ let blockInfo = {
341
+ blockNumber,
342
+ blockHash,
343
+ merkleRoot,
344
+ prvBlockHash,
345
+ }
346
+
347
+ let addressScript = addresses.map((address) =>
348
+ createAddressObjectByAddress(address, network).addressObject.output.toString("hex"),
349
+ )
350
+
351
+ let blockTxIds = block.transactions.map((tx) => tx.getId())
352
+
353
+ let withdrawTxs = []
354
+ let depositTxs = []
355
+ block.transactions.forEach((tx) => {
356
+ let txId = tx.getId()
357
+
358
+ let inputTxAddress
359
+ let isWithdraw = tx.ins.find((vi) => {
360
+ let viTxId = Buffer.from(vi.hash).reverse().toString("hex")
361
+ let viInput = inputTxIds.find((vin) => vin.txId === viTxId && vin.index === vi.index)
362
+ inputTxAddress = viInput?.address
363
+ return !!inputTxAddress
364
+ })
365
+ if (isWithdraw && inputTxAddress) {
366
+ let txMerkleProof = calculateMerkleProof(blockTxIds, txId, merkleRoot)
367
+
368
+ withdrawTxs.push({
369
+ txId: tx.getId(),
370
+ version: tx.version,
371
+ locktime: tx.locktime,
372
+ blockNumber,
373
+ blockHash,
374
+ merkleProof: txMerkleProof,
375
+ vout: tx.outs.map((vo) => ({
376
+ address: convertBitcoinScriptToAddress(vo.script, network),
377
+ script: vo.script.toString("hex"),
378
+ value: vo.value,
379
+ })),
380
+ vin: tx.ins.map((vi) => {
381
+ let viTxId = Buffer.from(vi.hash).reverse().toString("hex")
382
+ let viInput = inputTxIds.find((vin) => vin.txId === viTxId && vin.index === vi.index)
383
+ return {
384
+ txId: Buffer.from(vi.hash).reverse().toString("hex"),
385
+ index: vi.index,
386
+ address: viInput.address || null,
387
+ script: viInput.script || null,
388
+ value: viInput.value || null,
389
+ }
390
+ }),
391
+ address: inputTxAddress,
392
+ addressScript: createAddressObjectByAddress(
393
+ inputTxAddress,
394
+ network,
395
+ ).addressObject.output.toString("hex"),
396
+ })
397
+ }
398
+
399
+ let addressIndex
400
+ let isDeposit = tx.outs.find((blockTxVo) => {
401
+ let sIndex = addressScript.findIndex(
402
+ (addScript) => addScript === blockTxVo.script.toString("hex"),
403
+ )
404
+ if (sIndex >= 0) {
405
+ addressIndex = sIndex
406
+ return true
407
+ }
408
+ return false
409
+ })
410
+
411
+ if (isDeposit && addressIndex >= 0) {
412
+ // todo we can optimize this calculation (in following function, merkle tree calculate each times but we can do this once for block)
413
+ let txMerkleProof = calculateMerkleProof(blockTxIds, txId, merkleRoot)
414
+ depositTxs.push({
415
+ txId: tx.getId(),
416
+ version: tx.version,
417
+ locktime: tx.locktime,
418
+ blockNumber,
419
+ blockHash,
420
+ merkleProof: txMerkleProof,
421
+ vout: tx.outs.map((vo) => ({
422
+ address: convertBitcoinScriptToAddress(vo.script, network),
423
+ script: vo.script.toString("hex"),
424
+ value: vo.value,
425
+ })),
426
+ vin: tx.ins.map((vi) => ({
427
+ txId: Buffer.from(vi.hash).reverse().toString("hex"),
428
+ index: vi.index,
429
+ })),
430
+ addressScript: addressScript[addressIndex],
431
+ address: addresses[addressIndex],
432
+ })
433
+ }
434
+ })
435
+ return {
436
+ blockInfo,
437
+ withdrawTxs,
438
+ depositTxs,
439
+ }
440
+ }
441
+
442
+ function validateAddress(address, network = bitcoin.networks.bitcoin) {
443
+ try {
444
+ let isValid = false
445
+ let isAddressSegwit = address.startsWith(network.bech32)
446
+ if (isAddressSegwit) {
447
+ bitcoin.address.fromBech32(address)
448
+ isValid = true
449
+ } else {
450
+ let base58Data = bitcoin.address.fromBase58Check(address)
451
+ isValid =
452
+ base58Data.version === Number(network.scriptHash) ||
453
+ base58Data.version === Number(network.pubKeyHash)
454
+ }
455
+ return isValid
456
+ } catch (error) {
457
+ return false
458
+ }
459
+ }
460
+
461
+ module.exports = {
462
+ parseRawTransaction,
463
+ calculateMerkleProof,
464
+ createAddressObjectByHash,
465
+ createAddressObjectByPublicKey,
466
+ createAddressObjectByAddress,
467
+ createAddressObjectByScript,
468
+
469
+ // ------------------------
470
+ getAddressType,
471
+ getPubKeyFromPrivateKeyWIF,
472
+ getPubKeyFromPrivateKeyHex,
473
+ getPublicKeyHexByXpubAndIndex,
474
+ getPrivateKeyHexFromWIF,
475
+ reverseBytes,
476
+
477
+ parseBlockHeader,
478
+ generateMnemonic,
479
+
480
+ // ---------------------------
481
+ parseRawBlock,
482
+ extractTransactionsAndBlockInfoFromRawBlock,
483
+ // -----------------------------
484
+ validateAddress,
485
+
486
+ networks,
487
+ }