bsv2 2.0.24 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/{.babelrc.test → .babel.test} +1 -1
  2. package/.husky/pre-commit +1 -1
  3. package/.mocharc.yml +1 -1
  4. package/.travis.yml +1 -1
  5. package/babel.config.cjs +44 -0
  6. package/benchmark.js +10 -18
  7. package/bin/bsv.js +1 -1
  8. package/bin/network.js +2 -1
  9. package/dist/bsv2.mjs +36061 -4
  10. package/dist/bsv2.umd.js +28 -0
  11. package/doc/assets/anchor.js +350 -0
  12. package/doc/assets/bass-addons.css +12 -0
  13. package/doc/assets/bass.css +544 -0
  14. package/doc/assets/fonts/EOT/SourceCodePro-Bold.eot +0 -0
  15. package/doc/assets/fonts/EOT/SourceCodePro-Regular.eot +0 -0
  16. package/doc/assets/fonts/LICENSE.txt +93 -0
  17. package/doc/assets/fonts/OTF/SourceCodePro-Bold.otf +0 -0
  18. package/doc/assets/fonts/OTF/SourceCodePro-Regular.otf +0 -0
  19. package/doc/assets/fonts/TTF/SourceCodePro-Bold.ttf +0 -0
  20. package/doc/assets/fonts/TTF/SourceCodePro-Regular.ttf +0 -0
  21. package/doc/assets/fonts/WOFF/OTF/SourceCodePro-Bold.otf.woff +0 -0
  22. package/doc/assets/fonts/WOFF/OTF/SourceCodePro-Regular.otf.woff +0 -0
  23. package/doc/assets/fonts/WOFF/TTF/SourceCodePro-Bold.ttf.woff +0 -0
  24. package/doc/assets/fonts/WOFF/TTF/SourceCodePro-Regular.ttf.woff +0 -0
  25. package/doc/assets/fonts/WOFF2/OTF/SourceCodePro-Bold.otf.woff2 +0 -0
  26. package/doc/assets/fonts/WOFF2/OTF/SourceCodePro-Regular.otf.woff2 +0 -0
  27. package/doc/assets/fonts/WOFF2/TTF/SourceCodePro-Bold.ttf.woff2 +0 -0
  28. package/doc/assets/fonts/WOFF2/TTF/SourceCodePro-Regular.ttf.woff2 +0 -0
  29. package/doc/assets/fonts/source-code-pro.css +23 -0
  30. package/doc/assets/github.css +123 -0
  31. package/doc/assets/site.js +168 -0
  32. package/doc/assets/split.css +15 -0
  33. package/doc/assets/split.js +782 -0
  34. package/doc/assets/style.css +147 -0
  35. package/doc/index.html +9461 -0
  36. package/entry.js +2 -3
  37. package/eslint.config.mjs +8 -0
  38. package/index.js +1 -5
  39. package/{karma.conf.js → karma.conf.ts} +2 -3
  40. package/lib/ach.js +5 -5
  41. package/lib/address.js +11 -9
  42. package/lib/aescbc.js +3 -3
  43. package/lib/bip-39.js +12 -11
  44. package/lib/block.js +2 -2
  45. package/lib/bn.js +12 -17
  46. package/lib/bsm.js +1 -1
  47. package/lib/config.js +1 -1
  48. package/lib/constants.js +1 -1
  49. package/lib/ecdsa.js +24 -23
  50. package/lib/interp.js +18 -14
  51. package/lib/merkle.js +1 -1
  52. package/lib/op-code.js +137 -135
  53. package/lib/priv-key.js +1 -1
  54. package/lib/script.js +44 -42
  55. package/lib/sig.js +12 -12
  56. package/lib/struct.js +9 -6
  57. package/lib/tx.js +6 -6
  58. package/load-babel.js +3 -1
  59. package/mtest/test.html +6 -4
  60. package/mtest/test.js +1 -1
  61. package/out/Sig.html +541 -0
  62. package/out/bip-32.js.html +523 -0
  63. package/out/bip-39.js.html +336 -0
  64. package/out/block.js.html +183 -0
  65. package/out/bn.js.html +512 -0
  66. package/out/ecdsa.js.html +546 -0
  67. package/out/fonts/OpenSans-Bold-webfont.eot +0 -0
  68. package/out/fonts/OpenSans-Bold-webfont.svg +1830 -0
  69. package/out/fonts/OpenSans-Bold-webfont.woff +0 -0
  70. package/out/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  71. package/out/fonts/OpenSans-BoldItalic-webfont.svg +1830 -0
  72. package/out/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  73. package/out/fonts/OpenSans-Italic-webfont.eot +0 -0
  74. package/out/fonts/OpenSans-Italic-webfont.svg +1830 -0
  75. package/out/fonts/OpenSans-Italic-webfont.woff +0 -0
  76. package/out/fonts/OpenSans-Light-webfont.eot +0 -0
  77. package/out/fonts/OpenSans-Light-webfont.svg +1831 -0
  78. package/out/fonts/OpenSans-Light-webfont.woff +0 -0
  79. package/out/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  80. package/out/fonts/OpenSans-LightItalic-webfont.svg +1835 -0
  81. package/out/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  82. package/out/fonts/OpenSans-Regular-webfont.eot +0 -0
  83. package/out/fonts/OpenSans-Regular-webfont.svg +1831 -0
  84. package/out/fonts/OpenSans-Regular-webfont.woff +0 -0
  85. package/out/global.html +220 -0
  86. package/out/index.html +128 -0
  87. package/out/interp.js.html +2064 -0
  88. package/out/merkle.js.html +143 -0
  89. package/out/msg.js.html +235 -0
  90. package/out/priv-key.js.html +208 -0
  91. package/out/pub-key.js.html +281 -0
  92. package/out/script.js.html +876 -0
  93. package/out/scripts/linenumber.js +25 -0
  94. package/out/scripts/prettify/Apache-License-2.0.txt +202 -0
  95. package/out/scripts/prettify/lang-css.js +2 -0
  96. package/out/scripts/prettify/prettify.js +28 -0
  97. package/out/sig-operations.js.html +171 -0
  98. package/out/sig.js.html +450 -0
  99. package/out/struct.js.html +440 -0
  100. package/out/styles/jsdoc-default.css +358 -0
  101. package/out/styles/prettify-jsdoc.css +111 -0
  102. package/out/styles/prettify-tomorrow.css +132 -0
  103. package/out/tx-builder.js.html +644 -0
  104. package/out/tx-in.js.html +223 -0
  105. package/out/tx-verifier.js.html +260 -0
  106. package/out/tx.js.html +481 -0
  107. package/package.json +34 -39
  108. package/vite.config.js +36 -0
  109. package/dist/bsv2.bundle.js +0 -8
  110. package/dist/bsv2.cjs.js +0 -2
  111. package/dist/bsv2.cjs.js.LICENSE.txt +0 -1
  112. package/dist/bsv2.module.js +0 -2
  113. /package/{webpack.config.js → mtest/webpack.config.js} +0 -0
@@ -0,0 +1,644 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>JSDoc: Source: tx-builder.js</title>
6
+
7
+ <script src="scripts/prettify/prettify.js"> </script>
8
+ <script src="scripts/prettify/lang-css.js"> </script>
9
+ <!--[if lt IE 9]>
10
+ <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
11
+ <![endif]-->
12
+ <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
13
+ <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
14
+ </head>
15
+
16
+ <body>
17
+
18
+ <div id="main">
19
+
20
+ <h1 class="page-title">Source: tx-builder.js</h1>
21
+
22
+
23
+
24
+
25
+
26
+
27
+ <section>
28
+ <article>
29
+ <pre class="prettyprint source linenums"><code>/**
30
+ * Transaction Builder
31
+ * ===================
32
+ */
33
+ 'use strict'
34
+
35
+ import { Address } from './address'
36
+ import { Constants as Cst } from './constants'
37
+ import { Bn } from './bn'
38
+ import { HashCache } from './hash-cache'
39
+ import { Script } from './script'
40
+ import { SigOperations } from './sig-operations'
41
+ import { Sig } from './sig'
42
+ import { Struct } from './struct'
43
+ import { Tx } from './tx'
44
+ import { TxIn } from './tx-in'
45
+ import { TxOut } from './tx-out'
46
+ import { TxOutMap } from './tx-out-map'
47
+ import { VarInt } from './var-int'
48
+
49
+ const Constants = Cst.Default.TxBuilder
50
+
51
+ class TxBuilder extends Struct {
52
+ constructor (
53
+ tx = new Tx(),
54
+ txIns = [],
55
+ txOuts = [],
56
+ uTxOutMap = new TxOutMap(),
57
+ sigOperations = new SigOperations(),
58
+ changeScript,
59
+ changeAmountBn,
60
+ feeAmountBn,
61
+ feePerKbNum = Constants.feePerKbNum,
62
+ nLockTime = 0,
63
+ versionBytesNum = 1,
64
+ sigsPerInput = 1,
65
+ dust = Constants.dust,
66
+ dustChangeToFees = false,
67
+ hashCache = new HashCache()
68
+ ) {
69
+ super({
70
+ tx,
71
+ txIns,
72
+ txOuts,
73
+ uTxOutMap,
74
+ sigOperations,
75
+ changeScript,
76
+ changeAmountBn,
77
+ feeAmountBn,
78
+ feePerKbNum,
79
+ nLockTime,
80
+ versionBytesNum,
81
+ sigsPerInput,
82
+ dust,
83
+ dustChangeToFees,
84
+ hashCache
85
+ })
86
+ }
87
+
88
+ toJSON () {
89
+ const json = {}
90
+ json.tx = this.tx.toHex()
91
+ json.txIns = this.txIns.map(txIn => txIn.toHex())
92
+ json.txOuts = this.txOuts.map(txOut => txOut.toHex())
93
+ json.uTxOutMap = this.uTxOutMap.toJSON()
94
+ json.sigOperations = this.sigOperations.toJSON()
95
+ json.changeScript = this.changeScript ? this.changeScript.toHex() : undefined
96
+ json.changeAmountBn = this.changeAmountBn ? this.changeAmountBn.toNumber() : undefined
97
+ json.feeAmountBn = this.feeAmountBn ? this.feeAmountBn.toNumber() : undefined
98
+ json.feePerKbNum = this.feePerKbNum
99
+ json.sigsPerInput = this.sigsPerInput
100
+ json.dust = this.dust
101
+ json.dustChangeToFees = this.dustChangeToFees
102
+ json.hashCache = this.hashCache.toJSON()
103
+ return json
104
+ }
105
+
106
+ fromJSON (json) {
107
+ this.tx = new Tx().fromHex(json.tx)
108
+ this.txIns = json.txIns.map(txIn => TxIn.fromHex(txIn))
109
+ this.txOuts = json.txOuts.map(txOut => TxOut.fromHex(txOut))
110
+ this.uTxOutMap = new TxOutMap().fromJSON(json.uTxOutMap)
111
+ this.sigOperations = new SigOperations().fromJSON(json.sigOperations)
112
+ this.changeScript = json.changeScript ? new Script().fromHex(json.changeScript) : undefined
113
+ this.changeAmountBn = json.changeAmountBn ? new Bn(json.changeAmountBn) : undefined
114
+ this.feeAmountBn = json.feeAmountBn ? new Bn(json.feeAmountBn) : undefined
115
+ this.feePerKbNum = json.feePerKbNum || this.feePerKbNum
116
+ this.sigsPerInput = json.sigsPerInput || this.sigsPerInput
117
+ this.dust = json.dust || this.dust
118
+ this.dustChangeToFees =
119
+ json.dustChangeToFees || this.dustChangeToFees
120
+ this.hashCache = HashCache.fromJSON(json.hashCache)
121
+ return this
122
+ }
123
+
124
+ setFeePerKbNum (feePerKbNum) {
125
+ if (typeof feePerKbNum !== 'number' || feePerKbNum &lt; 0) {
126
+ throw new Error('cannot set a fee of zero or less')
127
+ }
128
+ this.feePerKbNum = feePerKbNum
129
+ return this
130
+ }
131
+
132
+ setChangeAddress (changeAddress) {
133
+ this.changeScript = changeAddress.toTxOutScript()
134
+ return this
135
+ }
136
+
137
+ setChangeScript (changeScript) {
138
+ this.changeScript = changeScript
139
+ return this
140
+ }
141
+
142
+ /**
143
+ * nLockTime is an unsigned integer.
144
+ */
145
+ setNLocktime (nLockTime) {
146
+ this.nLockTime = nLockTime
147
+ return this
148
+ }
149
+
150
+ setVersion (versionBytesNum) {
151
+ this.versionBytesNum = versionBytesNum
152
+ return this
153
+ }
154
+
155
+ /**
156
+ * Sometimes one of your outputs or the change output will be less than
157
+ * dust. Values less than dust cannot be broadcast. If you are OK with
158
+ * sending dust amounts to fees, then set this value to true.
159
+ */
160
+ setDust (dust = Constants.dust) {
161
+ this.dust = dust
162
+ return this
163
+ }
164
+
165
+ /**
166
+ * Sometimes one of your outputs or the change output will be less than
167
+ * dust. Values less than dust cannot be broadcast. If you are OK with
168
+ * sending dust amounts to fees, then set this value to true. We
169
+ * preferentially send all dust to the change if possible. However, that
170
+ * might not be possible if the change itself is less than dust, in which
171
+ * case all dust goes to fees.
172
+ */
173
+ sendDustChangeToFees (dustChangeToFees = false) {
174
+ this.dustChangeToFees = dustChangeToFees
175
+ return this
176
+ }
177
+
178
+ /**
179
+ * Import a transaction partially signed by someone else. The only thing you
180
+ * can do after this is sign one or more inputs. Usually used for multisig
181
+ * transactions. uTxOutMap is optional. It is not necessary so long as you
182
+ * pass in the txOut when you sign. You need to know the output when signing
183
+ * an input, including the script in the output, which is why this is
184
+ * necessary when signing an input.
185
+ */
186
+ importPartiallySignedTx (tx, uTxOutMap = this.uTxOutMap, sigOperations = this.sigOperations) {
187
+ this.tx = tx
188
+ this.uTxOutMap = uTxOutMap
189
+ this.sigOperations = sigOperations
190
+ return this
191
+ }
192
+
193
+ /**
194
+ * Pay "from" a script - in other words, add an input to the transaction.
195
+ */
196
+ inputFromScript (txHashBuf, txOutNum, txOut, script, nSequence) {
197
+ if (
198
+ !Buffer.isBuffer(txHashBuf) ||
199
+ !(typeof txOutNum === 'number') ||
200
+ !(txOut instanceof TxOut) ||
201
+ !(script instanceof Script)
202
+ ) {
203
+ throw new Error('invalid one of: txHashBuf, txOutNum, txOut, script')
204
+ }
205
+ this.txIns.push(
206
+ TxIn.fromProperties(txHashBuf, txOutNum, script, nSequence)
207
+ )
208
+ this.uTxOutMap.set(txHashBuf, txOutNum, txOut)
209
+ return this
210
+ }
211
+
212
+ addSigOperation (txHashBuf, txOutNum, nScriptChunk, type, addressStr, nHashType) {
213
+ this.sigOperations.addOne(txHashBuf, txOutNum, nScriptChunk, type, addressStr, nHashType)
214
+ return this
215
+ }
216
+
217
+ /**
218
+ * Pay "from" a pubKeyHash output - in other words, add an input to the
219
+ * transaction.
220
+ */
221
+ inputFromPubKeyHash (txHashBuf, txOutNum, txOut, pubKey, nSequence, nHashType) {
222
+ if (
223
+ !Buffer.isBuffer(txHashBuf) ||
224
+ typeof txOutNum !== 'number' ||
225
+ !(txOut instanceof TxOut)
226
+ ) {
227
+ throw new Error('invalid one of: txHashBuf, txOutNum, txOut')
228
+ }
229
+ this.txIns.push(
230
+ new TxIn()
231
+ .fromObject({ nSequence })
232
+ .fromPubKeyHashTxOut(txHashBuf, txOutNum, txOut, pubKey)
233
+ )
234
+ this.uTxOutMap.set(txHashBuf, txOutNum, txOut)
235
+ const addressStr = Address.fromTxOutScript(txOut.script).toString()
236
+ this.addSigOperation(txHashBuf, txOutNum, 0, 'sig', addressStr, nHashType)
237
+ this.addSigOperation(txHashBuf, txOutNum, 1, 'pubKey', addressStr)
238
+ return this
239
+ }
240
+
241
+ /**
242
+ * An address to send funds to, along with the amount. The amount should be
243
+ * denominated in satoshis, not bitcoins.
244
+ */
245
+ outputToAddress (valueBn, addr) {
246
+ if (!(addr instanceof Address) || !(valueBn instanceof Bn)) {
247
+ throw new Error('addr must be an Address, and valueBn must be a Bn')
248
+ }
249
+ const script = new Script().fromPubKeyHash(addr.hashBuf)
250
+ this.outputToScript(valueBn, script)
251
+ return this
252
+ }
253
+
254
+ /**
255
+ * A script to send funds to, along with the amount. The amount should be
256
+ * denominated in satoshis, not bitcoins.
257
+ */
258
+ outputToScript (valueBn, script) {
259
+ if (!(script instanceof Script) || !(valueBn instanceof Bn)) {
260
+ throw new Error('script must be a Script, and valueBn must be a Bn')
261
+ }
262
+ const txOut = TxOut.fromProperties(valueBn, script)
263
+ this.txOuts.push(txOut)
264
+ return this
265
+ }
266
+
267
+ buildOutputs () {
268
+ let outAmountBn = new Bn(0)
269
+ this.txOuts.forEach(txOut => {
270
+ if (txOut.valueBn.lt(this.dust) &amp;&amp; !txOut.script.isNonSpendable()) {
271
+ throw new Error('cannot create output lesser than dust')
272
+ }
273
+ outAmountBn = outAmountBn.add(txOut.valueBn)
274
+ this.tx.addTxOut(txOut)
275
+ })
276
+ return outAmountBn
277
+ }
278
+
279
+ buildInputs (outAmountBn, extraInputsNum = 0) {
280
+ let inAmountBn = new Bn(0)
281
+ for (const txIn of this.txIns) {
282
+ const txOut = this.uTxOutMap.get(txIn.txHashBuf, txIn.txOutNum)
283
+ inAmountBn = inAmountBn.add(txOut.valueBn)
284
+ this.tx.addTxIn(txIn)
285
+ if (inAmountBn.geq(outAmountBn)) {
286
+ if (extraInputsNum &lt;= 0) {
287
+ break
288
+ }
289
+ extraInputsNum--
290
+ }
291
+ }
292
+ if (inAmountBn.lt(outAmountBn)) {
293
+ throw new Error(
294
+ 'not enough funds for outputs: inAmountBn ' +
295
+ inAmountBn.toNumber() +
296
+ ' outAmountBn ' +
297
+ outAmountBn.toNumber()
298
+ )
299
+ }
300
+ return inAmountBn
301
+ }
302
+
303
+ // Thanks to SigOperations, if those are accurately used, then we can
304
+ // accurately estimate what the size of the transaction is going to be once
305
+ // all the signatures and public keys are inserted.
306
+ estimateSize () {
307
+ // largest possible sig size. final 1 is for pushdata at start. second to
308
+ // final is sighash byte. the rest are DER encoding.
309
+ const sigSize = 1 + 1 + 1 + 1 + 32 + 1 + 1 + 32 + 1 + 1
310
+ // length of script, y odd, x value - assumes compressed public key
311
+ const pubKeySize = 1 + 1 + 33
312
+
313
+ let size = this.tx.toBuffer().length
314
+
315
+ this.tx.txIns.forEach((txIn) => {
316
+ const { txHashBuf, txOutNum } = txIn
317
+ const sigOperations = this.sigOperations.get(txHashBuf, txOutNum)
318
+ sigOperations.forEach((obj) => {
319
+ const { nScriptChunk, type } = obj
320
+ const script = new Script([txIn.script.chunks[nScriptChunk]])
321
+ const scriptSize = script.toBuffer().length
322
+ size -= scriptSize
323
+ if (type === 'sig') {
324
+ size += sigSize
325
+ } else if (obj.type === 'pubKey') {
326
+ size += pubKeySize
327
+ } else {
328
+ throw new Error('unsupported sig operations type')
329
+ }
330
+ })
331
+ })
332
+
333
+ // size = size + sigSize * this.tx.txIns.length
334
+ size = size + 1 // assume txInsVi increases by 1 byte
335
+ return Math.round(size)
336
+ }
337
+
338
+ estimateFee (extraFeeAmount = new Bn(0)) {
339
+ // old style rounding up per kb - pays too high fees:
340
+ // const fee = Math.ceil(this.estimateSize() / 1000) * this.feePerKbNum
341
+
342
+ // new style pays lower fees - rounds up to satoshi, not per kb:
343
+ const fee = Math.ceil(this.estimateSize() / 1000 * this.feePerKbNum)
344
+
345
+ return new Bn(fee).add(extraFeeAmount)
346
+ }
347
+
348
+ /**
349
+ * Builds the transaction and adds the appropriate fee by subtracting from
350
+ * the change output. Note that by default the TxBuilder will use as many
351
+ * inputs as necessary to pay the output amounts and the required fee. The
352
+ * TxBuilder will not necessarily us all the inputs. To force the TxBuilder
353
+ * to use all the inputs (such as if you wish to spend the entire balance
354
+ * of a wallet), set the argument useAllInputs = true.
355
+ */
356
+ build (opts = { useAllInputs: false }) {
357
+ let minFeeAmountBn
358
+ if (this.txIns.length &lt;= 0) {
359
+ throw Error('tx-builder number of inputs must be greater than 0')
360
+ }
361
+ if (!this.changeScript) {
362
+ throw new Error('must specify change script to use build method')
363
+ }
364
+ for (
365
+ let extraInputsNum = opts.useAllInputs ? this.txIns.length - 1 : 0;
366
+ extraInputsNum &lt; this.txIns.length;
367
+ extraInputsNum++
368
+ ) {
369
+ this.tx = new Tx()
370
+ const outAmountBn = this.buildOutputs()
371
+ const changeTxOut = TxOut.fromProperties(new Bn(0), this.changeScript)
372
+ this.tx.addTxOut(changeTxOut)
373
+
374
+ let inAmountBn
375
+ try {
376
+ inAmountBn = this.buildInputs(outAmountBn, extraInputsNum)
377
+ } catch (err) {
378
+ if (err.message.includes('not enough funds for outputs')) {
379
+ throw new Error('unable to gather enough inputs for outputs and fee')
380
+ } else {
381
+ throw err
382
+ }
383
+ }
384
+
385
+ // Set change amount from inAmountBn - outAmountBn
386
+ this.changeAmountBn = inAmountBn.sub(outAmountBn)
387
+ changeTxOut.valueBn = this.changeAmountBn
388
+
389
+ minFeeAmountBn = this.estimateFee()
390
+ if (
391
+ this.changeAmountBn.geq(minFeeAmountBn) &amp;&amp;
392
+ this.changeAmountBn.sub(minFeeAmountBn).gt(this.dust)
393
+ ) {
394
+ break
395
+ }
396
+ }
397
+ if (this.changeAmountBn.geq(minFeeAmountBn)) {
398
+ // Subtract fee from change
399
+ this.feeAmountBn = minFeeAmountBn
400
+ this.changeAmountBn = this.changeAmountBn.sub(this.feeAmountBn)
401
+ this.tx.txOuts[this.tx.txOuts.length - 1].valueBn = this.changeAmountBn
402
+
403
+ if (this.changeAmountBn.lt(this.dust)) {
404
+ if (this.dustChangeToFees) {
405
+ // Remove the change amount since it is less than dust and the
406
+ // builder has requested dust be sent to fees.
407
+ this.tx.txOuts.pop()
408
+ this.tx.txOutsVi = VarInt.fromNumber(this.tx.txOutsVi.toNumber() - 1)
409
+ this.feeAmountBn = this.feeAmountBn.add(this.changeAmountBn)
410
+ this.changeAmountBn = new Bn(0)
411
+ } else {
412
+ throw new Error('unable to create change amount greater than dust')
413
+ }
414
+ }
415
+
416
+ this.tx.nLockTime = this.nLockTime
417
+ this.tx.versionBytesNum = this.versionBytesNum
418
+ if (this.tx.txOuts.length === 0) {
419
+ throw new Error(
420
+ 'outputs length is zero - unable to create any outputs greater than dust'
421
+ )
422
+ }
423
+ return this
424
+ } else {
425
+ throw new Error('unable to gather enough inputs for outputs and fee')
426
+ }
427
+ }
428
+
429
+ // BIP 69 sorting. call after build() but before sign()
430
+ sort () {
431
+ this.tx.sort()
432
+ return this
433
+ }
434
+
435
+ /**
436
+ * Check if all signatures are present in a multisig input script.
437
+ */
438
+ static allSigsPresent (m, script) {
439
+ // The first element is a Famous MultiSig Bug OP_0, and last element is the
440
+ // redeemScript. The rest are signatures.
441
+ let present = 0
442
+ for (let i = 1; i &lt; script.chunks.length - 1; i++) {
443
+ if (script.chunks[i].buf) {
444
+ present++
445
+ }
446
+ }
447
+ return present === m
448
+ }
449
+
450
+ /**
451
+ * Remove blank signatures in a multisig input script.
452
+ */
453
+ static removeBlankSigs (script) {
454
+ // The first element is a Famous MultiSig Bug OP_0, and last element is the
455
+ // redeemScript. The rest are signatures.
456
+ script = new Script(script.chunks.slice()) // copy the script
457
+ for (let i = 1; i &lt; script.chunks.length - 1; i++) {
458
+ if (!script.chunks[i].buf) {
459
+ script.chunks.splice(i, 1) // remove ith element
460
+ }
461
+ }
462
+ return script
463
+ }
464
+
465
+ fillSig (nIn, nScriptChunk, sig) {
466
+ const txIn = this.tx.txIns[nIn]
467
+ txIn.script.chunks[nScriptChunk] = new Script().writeBuffer(
468
+ sig.toTxFormat()
469
+ ).chunks[0]
470
+ txIn.scriptVi = VarInt.fromNumber(txIn.script.toBuffer().length)
471
+ return this
472
+ }
473
+
474
+ /**
475
+ * Sign an input, but do not fill the signature into the transaction. Return
476
+ * the signature.
477
+ *
478
+ * For a normal transaction, subScript is usually the scriptPubKey. If
479
+ * you're not normal because you're using OP_CODESEPARATORs, you know what
480
+ * to do.
481
+ */
482
+ getSig (keyPair, nHashType = Sig.SIGHASH_ALL | Sig.SIGHASH_FORKID, nIn, subScript, flags = Tx.SCRIPT_ENABLE_SIGHASH_FORKID) {
483
+ let valueBn
484
+ if (
485
+ nHashType &amp; Sig.SIGHASH_FORKID &amp;&amp;
486
+ flags &amp; Tx.SCRIPT_ENABLE_SIGHASH_FORKID
487
+ ) {
488
+ const txHashBuf = this.tx.txIns[nIn].txHashBuf
489
+ const txOutNum = this.tx.txIns[nIn].txOutNum
490
+ const txOut = this.uTxOutMap.get(txHashBuf, txOutNum)
491
+ if (!txOut) {
492
+ throw new Error('for SIGHASH_FORKID must provide UTXOs')
493
+ }
494
+ valueBn = txOut.valueBn
495
+ }
496
+ return this.tx.sign(keyPair, nHashType, nIn, subScript, valueBn, flags, this.hashCache)
497
+ }
498
+
499
+ /**
500
+ * Asynchronously sign an input in a worker, but do not fill the signature
501
+ * into the transaction. Return the signature.
502
+ */
503
+ asyncGetSig (keyPair, nHashType = Sig.SIGHASH_ALL | Sig.SIGHASH_FORKID, nIn, subScript, flags = Tx.SCRIPT_ENABLE_SIGHASH_FORKID) {
504
+ let valueBn
505
+ if (
506
+ nHashType &amp; Sig.SIGHASH_FORKID &amp;&amp;
507
+ flags &amp; Tx.SCRIPT_ENABLE_SIGHASH_FORKID
508
+ ) {
509
+ const txHashBuf = this.tx.txIns[nIn].txHashBuf
510
+ const txOutNum = this.tx.txIns[nIn].txOutNum
511
+ const txOut = this.uTxOutMap.get(txHashBuf, txOutNum)
512
+ if (!txOut) {
513
+ throw new Error('for SIGHASH_FORKID must provide UTXOs')
514
+ }
515
+ valueBn = txOut.valueBn
516
+ }
517
+ return this.tx.asyncSign(
518
+ keyPair,
519
+ nHashType,
520
+ nIn,
521
+ subScript,
522
+ valueBn,
523
+ flags,
524
+ this.hashCache
525
+ )
526
+ }
527
+
528
+ /**
529
+ * Sign ith input with keyPair and insert the signature into the transaction.
530
+ * This method only works for some standard transaction types. For
531
+ * non-standard transaction types, use getSig.
532
+ */
533
+ signTxIn (nIn, keyPair, txOut, nScriptChunk, nHashType = Sig.SIGHASH_ALL | Sig.SIGHASH_FORKID, flags = Tx.SCRIPT_ENABLE_SIGHASH_FORKID) {
534
+ const txIn = this.tx.txIns[nIn]
535
+ const script = txIn.script
536
+ if (nScriptChunk === undefined &amp;&amp; script.isPubKeyHashIn()) {
537
+ nScriptChunk = 0
538
+ }
539
+ if (nScriptChunk === undefined) {
540
+ throw new Error('cannot sign unknown script type for input ' + nIn)
541
+ }
542
+ const txHashBuf = txIn.txHashBuf
543
+ const txOutNum = txIn.txOutNum
544
+ if (!txOut) {
545
+ txOut = this.uTxOutMap.get(txHashBuf, txOutNum)
546
+ }
547
+ const outScript = txOut.script
548
+ const subScript = outScript // true for standard script types
549
+ const sig = this.getSig(keyPair, nHashType, nIn, subScript, flags, this.hashCache)
550
+ this.fillSig(nIn, nScriptChunk, sig)
551
+ return this
552
+ }
553
+
554
+ /**
555
+ * Asynchronously sign ith input with keyPair in a worker and insert the
556
+ * signature into the transaction. This method only works for some standard
557
+ * transaction types. For non-standard transaction types, use asyncGetSig.
558
+ */
559
+ async asyncSignTxIn (nIn, keyPair, txOut, nScriptChunk, nHashType = Sig.SIGHASH_ALL | Sig.SIGHASH_FORKID, flags = Tx.SCRIPT_ENABLE_SIGHASH_FORKID) {
560
+ const txIn = this.tx.txIns[nIn]
561
+ const script = txIn.script
562
+ if (nScriptChunk === undefined &amp;&amp; script.isPubKeyHashIn()) {
563
+ nScriptChunk = 0
564
+ }
565
+ if (nScriptChunk === undefined) {
566
+ throw new Error('cannot sign unknown script type for input ' + nIn)
567
+ }
568
+ const txHashBuf = txIn.txHashBuf
569
+ const txOutNum = txIn.txOutNum
570
+ if (!txOut) {
571
+ txOut = this.uTxOutMap.get(txHashBuf, txOutNum)
572
+ }
573
+ const outScript = txOut.script
574
+ const subScript = outScript // true for standard script types
575
+ const sig = await this.asyncGetSig(keyPair, nHashType, nIn, subScript, flags, this.hashCache)
576
+ this.fillSig(nIn, nScriptChunk, sig)
577
+ return this
578
+ }
579
+
580
+ signWithKeyPairs (keyPairs) {
581
+ // produce map of addresses to private keys
582
+ const addressStrMap = {}
583
+ for (const keyPair of keyPairs) {
584
+ const addressStr = Address.fromPubKey(keyPair.pubKey).toString()
585
+ addressStrMap[addressStr] = keyPair
586
+ }
587
+ // loop through all inputs
588
+ for (const nIn in this.tx.txIns) {
589
+ const txIn = this.tx.txIns[nIn]
590
+ // for each input, use sigOperations to get list of signatures and pubkeys
591
+ // to be produced and inserted
592
+ const arr = this.sigOperations.get(txIn.txHashBuf, txIn.txOutNum)
593
+ for (const obj of arr) {
594
+ // for each pubkey, get the privkey from the privkey map and sign the input
595
+ const { nScriptChunk, type, addressStr, nHashType } = obj
596
+ const keyPair = addressStrMap[addressStr]
597
+ if (!keyPair) {
598
+ obj.log = `cannot find keyPair for addressStr ${addressStr}`
599
+ continue
600
+ }
601
+ const txOut = this.uTxOutMap.get(txIn.txHashBuf, txIn.txOutNum)
602
+ if (type === 'sig') {
603
+ this.signTxIn(nIn, keyPair, txOut, nScriptChunk, nHashType)
604
+ obj.log = 'successfully inserted signature'
605
+ } else if (type === 'pubKey') {
606
+ txIn.script.chunks[nScriptChunk] = new Script().writeBuffer(
607
+ keyPair.pubKey.toBuffer()
608
+ ).chunks[0]
609
+ txIn.setScript(txIn.script)
610
+ obj.log = 'successfully inserted public key'
611
+ } else {
612
+ obj.log = `cannot perform operation of type ${type}`
613
+ continue
614
+ }
615
+ }
616
+ }
617
+ return this
618
+ }
619
+ }
620
+
621
+ export { TxBuilder }
622
+ </code></pre>
623
+ </article>
624
+ </section>
625
+
626
+
627
+
628
+
629
+ </div>
630
+
631
+ <nav>
632
+ <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="Sig.html">Sig</a></li></ul><h3>Global</h3><ul><li><a href="global.html#decorate">decorate</a></li></ul>
633
+ </nav>
634
+
635
+ <br class="clear">
636
+
637
+ <footer>
638
+ Documentation generated by <a href="https://github.com/jsdoc/jsdoc">JSDoc 4.0.4</a> on Fri Feb 28 2025 03:51:24 GMT+0100 (hora estándar de Europa central)
639
+ </footer>
640
+
641
+ <script> prettyPrint(); </script>
642
+ <script src="scripts/linenumber.js"> </script>
643
+ </body>
644
+ </html>