@onekeyfe/kaspa-core-lib 1.0.0-alpha.1

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 (53) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +59 -0
  3. package/index.d.ts +410 -0
  4. package/index.js +93 -0
  5. package/lib/address.js +792 -0
  6. package/lib/block/block.js +281 -0
  7. package/lib/block/blockheader.js +296 -0
  8. package/lib/block/index.js +4 -0
  9. package/lib/block/merkleblock.js +313 -0
  10. package/lib/crypto/bn.js +218 -0
  11. package/lib/crypto/ecdsa.js +296 -0
  12. package/lib/crypto/hash.js +85 -0
  13. package/lib/crypto/point.js +166 -0
  14. package/lib/crypto/random.js +57 -0
  15. package/lib/crypto/schnorr.js +287 -0
  16. package/lib/crypto/signature.js +441 -0
  17. package/lib/encoding/base58.js +70 -0
  18. package/lib/encoding/base58check.js +95 -0
  19. package/lib/encoding/bufferreader.js +202 -0
  20. package/lib/encoding/bufferwriter.js +155 -0
  21. package/lib/encoding/varint.js +72 -0
  22. package/lib/errors/index.js +61 -0
  23. package/lib/errors/spec.js +191 -0
  24. package/lib/hdprivatekey.js +646 -0
  25. package/lib/hdpublickey.js +496 -0
  26. package/lib/networks.js +277 -0
  27. package/lib/opcode.js +261 -0
  28. package/lib/privatekey.js +431 -0
  29. package/lib/publickey.js +375 -0
  30. package/lib/script/index.js +3 -0
  31. package/lib/script/interpreter.js +2107 -0
  32. package/lib/script/script.js +1163 -0
  33. package/lib/transaction/index.js +7 -0
  34. package/lib/transaction/input/index.js +6 -0
  35. package/lib/transaction/input/input.js +375 -0
  36. package/lib/transaction/input/multisig.js +221 -0
  37. package/lib/transaction/input/multisigscripthash.js +178 -0
  38. package/lib/transaction/input/publickey.js +91 -0
  39. package/lib/transaction/input/publickeyhash.js +100 -0
  40. package/lib/transaction/output.js +188 -0
  41. package/lib/transaction/sighash.js +534 -0
  42. package/lib/transaction/signature.js +89 -0
  43. package/lib/transaction/transaction.js +1384 -0
  44. package/lib/transaction/unspentoutput.js +109 -0
  45. package/lib/unit.js +238 -0
  46. package/lib/uri.js +223 -0
  47. package/lib/util/base32.js +63 -0
  48. package/lib/util/buffer.js +162 -0
  49. package/lib/util/convertBits.js +62 -0
  50. package/lib/util/js.js +110 -0
  51. package/lib/util/log.js +10 -0
  52. package/lib/util/preconditions.js +34 -0
  53. package/package.json +62 -0
@@ -0,0 +1,1384 @@
1
+ 'use strict';
2
+
3
+ var _ = require('lodash');
4
+ var $ = require('../util/preconditions');
5
+ var buffer = require('buffer');
6
+ var compare = Buffer.compare || require('buffer-compare');
7
+
8
+ var errors = require('../errors');
9
+ var BufferUtil = require('../util/buffer');
10
+ var JSUtil = require('../util/js');
11
+ const {LogBuffer} = JSUtil;
12
+ var BufferReader = require('../encoding/bufferreader');
13
+ var BufferWriter = require('../encoding/bufferwriter');
14
+ var Hash = require('../crypto/hash');
15
+ var Signature = require('../crypto/signature');
16
+ var Sighash = require('./sighash');
17
+
18
+ var Address = require('../address');
19
+ var UnspentOutput = require('./unspentoutput');
20
+ var Input = require('./input');
21
+ var PublicKeyHashInput = Input.PublicKeyHash;
22
+ var PublicKeyInput = Input.PublicKey;
23
+ var MultiSigScriptHashInput = Input.MultiSigScriptHash;
24
+ var MultiSigInput = Input.MultiSig;
25
+ var Output = require('./output');
26
+ var Script = require('../script');
27
+ var PrivateKey = require('../privatekey');
28
+ var BN = require('../crypto/bn');
29
+ var logLevels = require('../util/log').logLevels;
30
+
31
+
32
+ /*
33
+ [
34
+ "kaspa:precqv0krj3r6uyyfa36ga7s0u9jct0v4wg8ctsfde2gkrsgwgw8jgxfzfc98",
35
+ "kaspa:qqnash4vvcpx3s4qrf47p3rkcd4230sxz7506ejpt4gkpm2fh9xsumafqp07p",
36
+ "kaspa:qqwxqxwc0w54vsxlwyzt74enqq4e7d6mjp99l3te48r6ak4auehnqzae9a6uw",
37
+ "kaspa:qztdywdh8d9zjztdn8kdvckgch0e8p47gendyzks3lx2n8r70hktujwsy6ums",
38
+ "kaspa:qr0we0jumdfr25wpp9her3lk4nere24jmsfvew4z6gfwrj3dhhpny89xs7g6j",
39
+ "kaspa:qpdpduavrg6j39e8dn6rsr68yu4p6x6ju695up0p4r4gay0wymm4cged8p758"
40
+ ].map(addr=>{
41
+ let a = new Address(addr);
42
+ let s = Script(a)
43
+ console.log("address check:", s, s.classify(), a.isPayToScriptHash(), a.isPayToPublicKey(), a.type, a.toString());
44
+ })
45
+ */
46
+
47
+
48
+ /**
49
+ * Represents a transaction, a set of inputs and outputs to change ownership of tokens
50
+ *
51
+ * @param {*} serialized
52
+ * @constructor
53
+ */
54
+ function Transaction(serialized) {
55
+ if (!(this instanceof Transaction)) {
56
+ return new Transaction(serialized);
57
+ }
58
+ this.inputMap = new Map();
59
+ this.inputs = [];
60
+ this.outputs = [];
61
+ this._inputAmount = undefined;
62
+ this._outputAmount = undefined;
63
+
64
+ if (serialized) {
65
+ if (serialized instanceof Transaction) {
66
+ return Transaction.shallowCopy(serialized);
67
+ } else if (JSUtil.isHexa(serialized)) {
68
+ this.fromString(serialized);
69
+ } else if (BufferUtil.isBuffer(serialized)) {
70
+ this.fromBuffer(serialized);
71
+ } else if (_.isObject(serialized)) {
72
+ this.fromObject(serialized);
73
+ } else {
74
+ throw new errors.InvalidArgument('Must provide an object or string to deserialize a transaction');
75
+ }
76
+ } else {
77
+ this._newTransaction();
78
+ }
79
+ }
80
+
81
+ var CURRENT_VERSION = 2;
82
+ var DEFAULT_NLOCKTIME = 0;
83
+ var MAX_BLOCK_SIZE = 1000000;
84
+
85
+ Transaction.MassPerSigOp = 1000;
86
+ Transaction.MassPerTxByte = 1;
87
+ Transaction.MassPerScriptPubKeyByte = 10;
88
+ Transaction.EstimatedOutputMass = 27;
89
+ //mass of static info(version, input-length, output-length gas, payload etc. ) and 2 outputs
90
+ Transaction.EstimatedStandaloneMassWithoutInputs = 94 + (2 * Transaction.EstimatedOutputMass)
91
+
92
+ // Minimum amount for an output for it not to be considered a dust output
93
+ Transaction.DUST_AMOUNT = 546;
94
+
95
+ // Margin of error to allow fees in the vecinity of the expected value but doesn't allow a big difference
96
+ Transaction.FEE_SECURITY_MARGIN = 150;
97
+
98
+ // max amount of satoshis in circulation
99
+ Transaction.MAX_MONEY = 21000000 * 1e8;
100
+
101
+ // nlocktime limit to be considered block height rather than a timestamp
102
+ Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT = 5e8;
103
+
104
+ // Max value for an unsigned 32 bit value
105
+ Transaction.NLOCKTIME_MAX_VALUE = 4294967295;
106
+
107
+ // Value used for fee estimation (satoshis per kilobyte)
108
+ Transaction.FEE_PER_KB = 100000;
109
+
110
+
111
+ // Safe upper bound for change address script size in bytes
112
+ Transaction.CHANGE_OUTPUT_MAX_SIZE = 20 + 4 + 34 + 4;
113
+ Transaction.MAXIMUM_EXTRA_SIZE = 4 + 9 + 9 + 4;
114
+
115
+ /* Constructors and Serialization */
116
+
117
+ /**
118
+ * Create a 'shallow' copy of the transaction, by serializing and deserializing
119
+ * it dropping any additional information that inputs and outputs may have hold
120
+ *
121
+ * @param {Transaction} transaction
122
+ * @return {Transaction}
123
+ */
124
+ Transaction.shallowCopy = function(transaction) {
125
+ var copy = new Transaction(transaction.toBuffer());
126
+ return copy;
127
+ };
128
+
129
+ var hashProperty = {
130
+ configurable: false,
131
+ enumerable: true,
132
+ get: function() {
133
+ this._hash = new BufferReader(this._getHash()).readReverse().toString('hex');
134
+ return this._hash;
135
+ }
136
+ };
137
+ Object.defineProperty(Transaction.prototype, 'hash', hashProperty);
138
+ Object.defineProperty(Transaction.prototype, 'id', hashProperty);
139
+
140
+ var ioProperty = {
141
+ configurable: false,
142
+ enumerable: true,
143
+ get: function() {
144
+ return this._getInputAmount().toString();
145
+ }
146
+ };
147
+ Object.defineProperty(Transaction.prototype, 'inputAmount', ioProperty);
148
+ ioProperty.get = function() {
149
+ return this._getOutputAmount().toString();
150
+ };
151
+ Object.defineProperty(Transaction.prototype, 'outputAmount', ioProperty);
152
+
153
+ /**
154
+ * Retrieve the little endian hash of the transaction (used for serialization)
155
+ * @return {Buffer}
156
+ */
157
+ Transaction.prototype._getHash = function() {
158
+ return Hash.sha256sha256(this.toBuffer());
159
+ };
160
+
161
+ /**
162
+ * Retrieve a hexa string that can be used with bitcoind's CLI interface
163
+ * (decoderawtransaction, sendrawtransaction)
164
+ *
165
+ * @param {Object|boolean=} unsafe if true, skip all tests. if it's an object,
166
+ * it's expected to contain a set of flags to skip certain tests:
167
+ * * `disableAll`: disable all checks
168
+ * * `disableLargeFees`: disable checking for fees that are too large
169
+ * * `disableIsFullySigned`: disable checking if all inputs are fully signed
170
+ * * `disableDustOutputs`: disable checking if there are no outputs that are dust amounts
171
+ * * `disableMoreOutputThanInput`: disable checking if the transaction spends more bitcoins than the sum of the input amounts
172
+ * @return {string}
173
+ */
174
+ Transaction.prototype.serialize = function(unsafe) {
175
+ if (true === unsafe || unsafe && unsafe.disableAll) {
176
+ return this.uncheckedSerialize();
177
+ } else {
178
+ return this.checkedSerialize(unsafe);
179
+ }
180
+ };
181
+
182
+ Transaction.prototype.uncheckedSerialize = Transaction.prototype.toString = function() {
183
+ return this.toBuffer().toString('hex');
184
+ };
185
+
186
+ /**
187
+ * Retrieve a hexa string that can be used with bitcoind's CLI interface
188
+ * (decoderawtransaction, sendrawtransaction)
189
+ *
190
+ * @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
191
+ * @return {string}
192
+ */
193
+ Transaction.prototype.checkedSerialize = function(opts) {
194
+ var serializationError = this.getSerializationError(opts);
195
+ if (serializationError) {
196
+ serializationError.message += ' - For more information please see: ' +
197
+ 'https://kaspacore.io/api/lib/transaction#serialization-checks';
198
+ throw serializationError;
199
+ }
200
+ return this.uncheckedSerialize();
201
+ };
202
+
203
+ Transaction.prototype.invalidSatoshis = function() {
204
+ var invalid = false;
205
+ for (var i = 0; i < this.outputs.length; i++) {
206
+ if (this.outputs[i].invalidSatoshis()) {
207
+ invalid = true;
208
+ }
209
+ }
210
+ return invalid;
211
+ };
212
+
213
+ /**
214
+ * Retrieve a possible error that could appear when trying to serialize and
215
+ * broadcast this transaction.
216
+ *
217
+ * @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
218
+ * @return {kaspacore.Error}
219
+ */
220
+ Transaction.prototype.getSerializationError = function(opts) {
221
+ opts = opts || {};
222
+
223
+ if (this.invalidSatoshis()) {
224
+ return new errors.Transaction.InvalidSatoshis();
225
+ }
226
+
227
+ var unspent = this._getUnspentValue();
228
+ var unspentError;
229
+ if (unspent.lt(0)) {
230
+ if (!opts.disableMoreOutputThanInput) {
231
+ unspentError = new errors.Transaction.InvalidOutputAmountSum();
232
+ }
233
+ } else {
234
+ unspentError = this._hasFeeError(opts, unspent);
235
+ }
236
+
237
+ return unspentError ||
238
+ this._hasDustOutputs(opts) ||
239
+ this._isMissingSignatures(opts);
240
+ };
241
+
242
+ Transaction.prototype._hasFeeError = function(opts, unspent) {
243
+
244
+ if (!_.isUndefined(this._fee) && this._fee !== unspent) {
245
+ return new errors.Transaction.FeeError.Different(
246
+ 'Unspent value is ' + unspent + ' but specified fee is ' + this._fee
247
+ );
248
+ }
249
+
250
+ if (!opts.disableLargeFees) {
251
+ var maximumFee = Math.floor(Transaction.FEE_SECURITY_MARGIN * this._estimateFee());
252
+ if (unspent > maximumFee) {
253
+ if (this._missingChange()) {
254
+ return new errors.Transaction.ChangeAddressMissing(
255
+ 'Fee is too large and no change address was provided'
256
+ );
257
+ }
258
+ return new errors.Transaction.FeeError.TooLarge(
259
+ 'expected less than ' + maximumFee + ' but got ' + unspent
260
+ );
261
+ }
262
+ }
263
+ if (!opts.disableSmallFees) {
264
+ var minimumFee = Math.ceil(this._estimateFee() / Transaction.FEE_SECURITY_MARGIN);
265
+ if (unspent < minimumFee) {
266
+ return new errors.Transaction.FeeError.TooSmall(
267
+ 'expected more than ' + minimumFee + ' but got ' + unspent
268
+ );
269
+ }
270
+ }
271
+ };
272
+
273
+ Transaction.prototype._missingChange = function() {
274
+ return !this._changeScript;
275
+ };
276
+
277
+ Transaction.prototype._hasDustOutputs = function(opts) {
278
+ if (opts.disableDustOutputs) {
279
+ return;
280
+ }
281
+ var index, output;
282
+ for (index in this.outputs) {
283
+ output = this.outputs[index];
284
+ if (output.satoshis < Transaction.DUST_AMOUNT && !output.script.isDataOut()) {
285
+ return new errors.Transaction.DustOutputs();
286
+ }
287
+ }
288
+ };
289
+
290
+ Transaction.prototype._isMissingSignatures = function(opts) {
291
+ if (opts.disableIsFullySigned) {
292
+ return;
293
+ }
294
+ if (!this.isFullySigned()) {
295
+ return new errors.Transaction.MissingSignatures();
296
+ }
297
+ };
298
+
299
+ Transaction.prototype.inspect = function() {
300
+ return '<Transaction: ' + this.uncheckedSerialize() + '>';
301
+ };
302
+
303
+ Transaction.prototype.toBuffer = function(skipInputs=false) {
304
+ var writer = new BufferWriter();
305
+ return this.toBufferWriter(writer, {skipInputs}).toBuffer();
306
+ };
307
+
308
+ const __subnetworkId__ = Buffer.from("0000000000000000000000000000000000000000", "hex");
309
+ const __gas__ = Buffer.from("0000000000000000", "hex");
310
+ const __payload__ = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex");
311
+ const __unknown__ = Buffer.from("0000000000000000", "hex");
312
+
313
+ Transaction.prototype.toBufferWriter = function(writer, extra) {
314
+ writer.writeUInt16LE(this.version);
315
+ //!LogBuffer("$$$$ version: ", this.version, writer.bufs)
316
+ let bn = BN.fromNumber(this.inputs.length);
317
+ writer.writeUInt64LEBN(bn);
318
+ //!LogBuffer("$$$$ inputs.length: ", this.inputs.length, writer.bufs)
319
+ let {skipInputs=false} = extra||{}
320
+ if(skipInputs){
321
+ //let fakeInputs = Buffer.alloc(151 * this.inputs.length);
322
+ //writer.write(fakeInputs);
323
+ }else{
324
+ //@ts-ignore
325
+ _.each(this.inputs, function(input) {
326
+ //if(skipInputs){
327
+ // console.log('toBufferWriter:inputLength', input.toBufferWriter().toBuffer().length)
328
+ //}
329
+ input.lockUntilBlockHeight(0);
330
+ input.toBufferWriter(writer);
331
+ });
332
+ }
333
+ bn = BN.fromNumber(this.outputs.length);
334
+ writer.writeUInt64LEBN(bn);
335
+ //!LogBuffer("$$$$ outputs.length: ", this.outputs.length, writer.bufs)
336
+ //@ts-ignore
337
+ _.each(this.outputs, function(output) {
338
+ output.toBufferWriter(writer);
339
+ });
340
+ bn = BN.fromNumber(this.nLockTime);
341
+ writer.writeUInt64LEBN(bn);
342
+ //!LogBuffer("$$$$ nLockTime: ", this.nLockTime, writer.bufs)
343
+
344
+ //let subnetworkId = Buffer.from("0000000000000000000000000000000000000000", "hex");
345
+ writer.write(__subnetworkId__);
346
+ //!LogBuffer("$$$$ subnetworkId: ", subnetworkId.toString("hex"), writer.bufs)
347
+
348
+ //GAS
349
+ //let gas = Buffer.from("0000000000000000", "hex");
350
+ writer.write(__gas__);
351
+ //!LogBuffer("$$$$ gas: ", gas.toString("hex"), writer.bufs)
352
+ //PayloadHash
353
+ //let payload = Buffer.from("0000000000000000000000000000000000000000000000000000000000000000", "hex")
354
+ writer.write(__payload__)
355
+ //!LogBuffer("$$$$ payload: ", payload.toString("hex"), writer.bufs)
356
+
357
+ //let unknown = Buffer.from("0000000000000000", "hex");
358
+ writer.write(__unknown__);
359
+ //!LogBuffer("$$$$ unknown: ", unknown.toString("hex"), writer.bufs)
360
+
361
+ return writer;
362
+ };
363
+
364
+
365
+ Transaction.prototype.getStandaloneMass = function() {
366
+ let txSize = this.toBuffer(true).length;
367
+ txSize += 151 * this.inputs.length;
368
+
369
+ let scriptPubKeySize = 0;
370
+ this.outputs.forEach(output =>{
371
+ scriptPubKeySize += 2 //output.ScriptPublicKey.Version (uint16)
372
+ scriptPubKeySize += output._scriptBuffer.length;
373
+ //console.log("\n#### scriptPubKeySize:", scriptPubKeySize)
374
+ })
375
+
376
+ //console.log("\n#### txSize:", txSize)
377
+
378
+ return {
379
+ txSize,
380
+ mass:txSize * Transaction.MassPerTxByte + scriptPubKeySize * Transaction.MassPerScriptPubKeyByte
381
+ }
382
+ }
383
+ Transaction.prototype.getMassAndSize = function() {
384
+ let {txSize, mass:standaloneMass} = this.getStandaloneMass();
385
+ let sigOpsCount = 0;
386
+ this.inputs.forEach(input=>{
387
+ //console.log("input.script", input.output.script.toASM())
388
+ sigOpsCount += input.output.script.getSignatureOperationsCount()
389
+ });
390
+
391
+ //console.log("standaloneMass", standaloneMass)
392
+ //console.log("sigOpsCount", sigOpsCount)
393
+ //console.log("total MASS ", standaloneMass + sigOpsCount * Transaction.MassPerSigOp)
394
+ return {txSize, mass: standaloneMass + sigOpsCount * Transaction.MassPerSigOp};
395
+ }
396
+ Transaction.prototype.fromBuffer = function(buffer) {
397
+ var reader = new BufferReader(buffer);
398
+ return this.fromBufferReader(reader);
399
+ };
400
+
401
+ Transaction.prototype.fromBufferReader = function(reader) {
402
+ $.checkArgument(!reader.finished(), 'No transaction data received');
403
+ var i, sizeTxIns, sizeTxOuts;
404
+
405
+ this.version = reader.readUInt16LE();
406
+ sizeTxIns = reader.readUInt64LEBN().toNumber();
407
+ for (i = 0; i < sizeTxIns; i++) {
408
+ var input = Input.fromBufferReader(reader);
409
+ this.inputs.push(input);
410
+ }
411
+ sizeTxOuts = reader.readUInt64LEBN().toNumber();
412
+ for (i = 0; i < sizeTxOuts; i++) {
413
+ this.outputs.push(Output.fromBufferReader(reader));
414
+ }
415
+ this.nLockTime = reader.readUInt32LE();
416
+ return this;
417
+ };
418
+
419
+ Transaction.prototype.toObject = Transaction.prototype.toJSON = function toObject() {
420
+ var inputs = [];
421
+ this.inputs.forEach(function(input) {
422
+ inputs.push(input.toObject());
423
+ });
424
+ var outputs = [];
425
+ this.outputs.forEach(function(output) {
426
+ outputs.push(output.toObject());
427
+ });
428
+ var obj = {
429
+ hash: this.hash,
430
+ version: this.version,
431
+ inputs: inputs,
432
+ outputs: outputs,
433
+ nLockTime: this.nLockTime
434
+ };
435
+ if (this._changeScript) {
436
+ obj.changeScript = this._changeScript.toString();
437
+ }
438
+ if (!_.isUndefined(this._changeIndex)) {
439
+ obj.changeIndex = this._changeIndex;
440
+ }
441
+ if (!_.isUndefined(this._fee)) {
442
+ obj.fee = this._fee;
443
+ }
444
+ return obj;
445
+ };
446
+
447
+ Transaction.prototype.fromObject = function fromObject(arg) {
448
+ /* jshint maxstatements: 20 */
449
+ $.checkArgument(_.isObject(arg) || arg instanceof Transaction);
450
+ var self = this;
451
+ var transaction;
452
+ if (arg instanceof Transaction) {
453
+ transaction = transaction.toObject();
454
+ } else {
455
+ transaction = arg;
456
+ }
457
+ _.each(transaction.inputs, function(input) {
458
+ if (!input.output || !input.output.script) {
459
+ self.uncheckedAddInput(new Input(input));
460
+ return;
461
+ }
462
+ var script = new Script(input.output.script);
463
+ var txin;
464
+ if (script.isPublicKeyHashOut()) {
465
+ txin = new Input.PublicKeyHash(input);
466
+ } else if (script.isScriptHashOut() && input.publicKeys && input.threshold) {
467
+ txin = new Input.MultiSigScriptHash(
468
+ input, input.publicKeys, input.threshold, input.signatures
469
+ );
470
+ } else if (script.isPublicKeyOut()) {
471
+ txin = new Input.PublicKey(input);
472
+ } else {
473
+ throw new errors.Transaction.Input.UnsupportedScript(input.output.script);
474
+ }
475
+ self.addInput(txin);
476
+ });
477
+ _.each(transaction.outputs, function(output) {
478
+ self.addOutput(new Output(output));
479
+ });
480
+ if (transaction.changeIndex) {
481
+ this._changeIndex = transaction.changeIndex;
482
+ }
483
+ if (transaction.changeScript) {
484
+ this._changeScript = new Script(transaction.changeScript);
485
+ }
486
+ if (transaction.fee) {
487
+ this._fee = transaction.fee;
488
+ }
489
+ this.nLockTime = transaction.nLockTime;
490
+ this.version = transaction.version;
491
+ this._checkConsistency(arg);
492
+ return this;
493
+ };
494
+
495
+ Transaction.prototype._checkConsistency = function(arg) {
496
+ if (!_.isUndefined(this._changeIndex)) {
497
+ $.checkState(this._changeScript, 'Change script is expected.');
498
+ $.checkState(this.outputs[this._changeIndex], 'Change index points to undefined output.');
499
+ $.checkState(this.outputs[this._changeIndex].script.toString() ===
500
+ this._changeScript.toString(), 'Change output has an unexpected script.');
501
+ }
502
+ if (arg && arg.hash) {
503
+ $.checkState(arg.hash === this.hash, 'Hash in object does not match transaction hash.');
504
+ }
505
+ };
506
+
507
+ /**
508
+ * Sets nLockTime so that transaction is not valid until the desired date(a
509
+ * timestamp in seconds since UNIX epoch is also accepted)
510
+ *
511
+ * @param {Date | Number} time
512
+ * @return {Transaction} this
513
+ */
514
+ Transaction.prototype.lockUntilDate = function(time) {
515
+ $.checkArgument(time);
516
+ if (_.isNumber(time) && time < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
517
+ throw new errors.Transaction.LockTimeTooEarly();
518
+ }
519
+ if (_.isDate(time)) {
520
+ time = time.getTime() / 1000;
521
+ }
522
+
523
+ for (var i = 0; i < this.inputs.length; i++) {
524
+ if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER) {
525
+ this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
526
+ }
527
+ }
528
+
529
+ this.nLockTime = time;
530
+ return this;
531
+ };
532
+
533
+ /**
534
+ * Sets nLockTime so that transaction is not valid until the desired block
535
+ * height.
536
+ *
537
+ * @param {Number} height
538
+ * @return {Transaction} this
539
+ */
540
+ Transaction.prototype.lockUntilBlockHeight = function(height) {
541
+ $.checkArgument(_.isNumber(height));
542
+ if (height >= Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
543
+ throw new errors.Transaction.BlockHeightTooHigh();
544
+ }
545
+ if (height < 0) {
546
+ throw new errors.Transaction.NLockTimeOutOfRange();
547
+ }
548
+
549
+ for (var i = 0; i < this.inputs.length; i++) {
550
+ if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER) {
551
+ this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
552
+ }
553
+ }
554
+
555
+
556
+ this.nLockTime = height;
557
+ return this;
558
+ };
559
+
560
+ /**
561
+ * Returns a semantic version of the transaction's nLockTime.
562
+ * @return {Number|Date}
563
+ * If nLockTime is 0, it returns null,
564
+ * if it is < 500000000, it returns a block height (number)
565
+ * else it returns a Date object.
566
+ */
567
+ Transaction.prototype.getLockTime = function() {
568
+ if (!this.nLockTime) {
569
+ return null;
570
+ }
571
+ if (this.nLockTime < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
572
+ return this.nLockTime;
573
+ }
574
+ return new Date(1000 * this.nLockTime);
575
+ };
576
+
577
+ Transaction.prototype.fromString = function(string) {
578
+ this.fromBuffer(buffer.Buffer.from(string, 'hex'));
579
+ };
580
+
581
+ Transaction.prototype._newTransaction = function() {
582
+ this.version = CURRENT_VERSION;
583
+ this.nLockTime = DEFAULT_NLOCKTIME;
584
+ };
585
+
586
+ /* Transaction creation interface */
587
+
588
+ /**
589
+ * @typedef {Object} Transaction~fromObject
590
+ * @property {string} prevTxId
591
+ * @property {number} outputIndex
592
+ * @property {(Buffer|string|Script)} script
593
+ * @property {number} satoshis
594
+ */
595
+
596
+ /**
597
+ * Add an input to this transaction. This is a high level interface
598
+ * to add an input, for more control, use @{link Transaction#addInput}.
599
+ *
600
+ * Can receive, as output information, the output of bitcoind's `listunspent` command,
601
+ * and a slightly fancier format recognized by kaspacore:
602
+ *
603
+ * ```
604
+ * {
605
+ * address: 'mszYqVnqKoQx4jcTdJXxwKAissE3Jbrrc1',
606
+ * txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458',
607
+ * outputIndex: 0,
608
+ * script: Script.empty(),
609
+ * satoshis: 1020000
610
+ * }
611
+ * ```
612
+ * Where `address` can be either a string or a kaspacore Address object. The
613
+ * same is true for `script`, which can be a string or a kaspacore Script.
614
+ *
615
+ * Beware that this resets all the signatures for inputs (in further versions,
616
+ * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
617
+ *
618
+ * @example
619
+ * ```javascript
620
+ * var transaction = new Transaction();
621
+ *
622
+ * // From a pay to public key hash output from bitcoind's listunspent
623
+ * transaction.from({'txid': '0000...', vout: 0, amount: 0.1, scriptPubKey: 'OP_DUP ...'});
624
+ *
625
+ * // From a pay to public key hash output
626
+ * transaction.from({'txId': '0000...', outputIndex: 0, satoshis: 1000, script: 'OP_DUP ...'});
627
+ *
628
+ * // From a multisig P2SH output
629
+ * transaction.from({'txId': '0000...', inputIndex: 0, satoshis: 1000, script: '... OP_HASH'},
630
+ * ['03000...', '02000...'], 2);
631
+ * ```
632
+ *
633
+ * @param {(Array.<Transaction~fromObject>|Transaction~fromObject)} utxo
634
+ * @param {Array=} pubkeys
635
+ * @param {number=} threshold
636
+ * @param {Object=} opts - Several options:
637
+ * - noSorting: defaults to false, if true and is multisig, don't
638
+ * sort the given public keys before creating the script
639
+ */
640
+ Transaction.prototype.from = function(utxo, pubkeys, threshold, opts) {
641
+ if(JSUtil.debugLevel == logLevels.debug)
642
+ console.log("Transaction:from utxo:", utxo)
643
+ if (_.isArray(utxo)) {
644
+ var self = this;
645
+ _.each(utxo, function(utxo) {
646
+ self.from(utxo, pubkeys, threshold, opts);
647
+ });
648
+ return this;
649
+ }
650
+ var exists = _.some(this.inputs, function(input) {
651
+ // TODO: Maybe prevTxId should be a string? Or defined as read only property?
652
+ return input.prevTxId.toString('hex') === utxo.txId && input.outputIndex === utxo.outputIndex;
653
+ });
654
+ if (exists) {
655
+ return this;
656
+ }
657
+ if (pubkeys && threshold) {
658
+ this._fromMultisigUtxo(utxo, pubkeys, threshold, opts);
659
+ } else {
660
+ this._fromNonP2SH(utxo);
661
+ }
662
+ return this;
663
+ };
664
+
665
+ Transaction.prototype._fromNonP2SH = function(utxo) {
666
+ var clazz;
667
+ const {
668
+ scriptPublicKeyVersion
669
+ } = utxo;
670
+ utxo = new UnspentOutput(utxo);
671
+ if (utxo.script.isPublicKeyHashOut()) {
672
+ clazz = PublicKeyHashInput;
673
+ } else if (utxo.script.isPublicKeyOut()) {
674
+ clazz = PublicKeyInput;
675
+ } else {
676
+ clazz = Input;
677
+ }
678
+ this.addInput(new clazz({
679
+ output: new Output({
680
+ script: utxo.script,
681
+ satoshis: utxo.satoshis
682
+ }),
683
+ prevTxId: utxo.txId,
684
+ outputIndex: utxo.outputIndex,
685
+ script: Script.empty(),
686
+ version: scriptPublicKeyVersion
687
+ }));
688
+ };
689
+
690
+
691
+ Transaction.prototype._fromMultisigUtxo = function(utxo, pubkeys, threshold, opts) {
692
+ $.checkArgument(threshold <= pubkeys.length,
693
+ 'Number of required signatures must be greater than the number of public keys');
694
+ var clazz;
695
+ utxo = new UnspentOutput(utxo);
696
+ if (utxo.script.isMultisigOut()) {
697
+ clazz = MultiSigInput;
698
+ } else if (utxo.script.isScriptHashOut()) {
699
+ clazz = MultiSigScriptHashInput;
700
+ } else {
701
+ throw new Error("@TODO");
702
+ }
703
+ this.addInput(new clazz({
704
+ output: new Output({
705
+ script: utxo.script,
706
+ satoshis: utxo.satoshis
707
+ }),
708
+ prevTxId: utxo.txId,
709
+ outputIndex: utxo.outputIndex,
710
+ script: Script.empty()
711
+ }, pubkeys, threshold, undefined, opts));
712
+ };
713
+
714
+ /**
715
+ * Add an input to this transaction. The input must be an instance of the `Input` class.
716
+ * It should have information about the Output that it's spending, but if it's not already
717
+ * set, two additional parameters, `outputScript` and `satoshis` can be provided.
718
+ *
719
+ * @param {Input} input
720
+ * @param {String|Script} outputScript
721
+ * @param {number} satoshis
722
+ * @return Transaction this, for chaining
723
+ */
724
+ Transaction.prototype.addInput = function(input, outputScript, satoshis) {
725
+ $.checkArgumentType(input, Input, 'input');
726
+ if (!input.output && (_.isUndefined(outputScript) || _.isUndefined(satoshis))) {
727
+ throw new errors.Transaction.NeedMoreInfo('Need information about the UTXO script and satoshis');
728
+ }
729
+ if (!input.output && outputScript && !_.isUndefined(satoshis)) {
730
+ outputScript = outputScript instanceof Script ? outputScript : new Script(outputScript);
731
+ $.checkArgumentType(satoshis, 'number', 'satoshis');
732
+ input.output = new Output({
733
+ script: outputScript,
734
+ satoshis: satoshis
735
+ });
736
+ }
737
+ return this.uncheckedAddInput(input);
738
+ };
739
+
740
+ /**
741
+ * Add an input to this transaction, without checking that the input has information about
742
+ * the output that it's spending.
743
+ *
744
+ * @param {Input} input
745
+ * @return Transaction this, for chaining
746
+ */
747
+ Transaction.prototype.uncheckedAddInput = function(input) {
748
+ $.checkArgumentType(input, Input, 'input');
749
+ this.inputs.push(input);
750
+ this._inputAmount = undefined;
751
+ this._updateChangeOutput();
752
+ return this;
753
+ };
754
+
755
+ /**
756
+ * Returns true if the transaction has enough info on all inputs to be correctly validated
757
+ *
758
+ * @return {boolean}
759
+ */
760
+ Transaction.prototype.hasAllUtxoInfo = function() {
761
+ return _.every(this.inputs.map(function(input) {
762
+ return !!input.output;
763
+ }));
764
+ };
765
+
766
+ /**
767
+ * Manually set the fee for this transaction. Beware that this resets all the signatures
768
+ * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
769
+ * be reset).
770
+ *
771
+ * @param {number} amount satoshis to be sent
772
+ * @return {Transaction} this, for chaining
773
+ */
774
+ Transaction.prototype.fee = function(amount) {
775
+ $.checkArgument(_.isNumber(amount), 'amount must be a number');
776
+ this._fee = amount;
777
+ this._updateChangeOutput();
778
+ return this;
779
+ };
780
+
781
+ /**
782
+ * Manually set the fee per KB for this transaction. Beware that this resets all the signatures
783
+ * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
784
+ * be reset).
785
+ *
786
+ * @param {number} amount satoshis per KB to be sent
787
+ * @return {Transaction} this, for chaining
788
+ */
789
+ Transaction.prototype.feePerKb = function(amount) {
790
+ $.checkArgument(_.isNumber(amount), 'amount must be a number');
791
+ this._feePerKb = amount;
792
+ this._updateChangeOutput();
793
+ return this;
794
+ };
795
+
796
+ /**
797
+ * Manually set the fee per Byte for this transaction. Beware that this resets all the signatures
798
+ * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
799
+ * be reset).
800
+ * fee per Byte will be ignored if fee per KB is set
801
+ *
802
+ * @param {number} amount satoshis per Byte to be sent
803
+ * @return {Transaction} this, for chaining
804
+ */
805
+ Transaction.prototype.feePerByte = function(amount) {
806
+ $.checkArgument(_.isNumber(amount), 'amount must be a number');
807
+ this._feePerByte = amount;
808
+ this._updateChangeOutput();
809
+ return this;
810
+ };
811
+
812
+ /* Output management */
813
+
814
+ /**
815
+ * Set the change address for this transaction
816
+ *
817
+ * Beware that this resets all the signatures for inputs (in further versions,
818
+ * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
819
+ *
820
+ * @param {Address} address An address for change to be sent to.
821
+ * @return {Transaction} this, for chaining
822
+ */
823
+ Transaction.prototype.change = function(address) {
824
+ $.checkArgument(address, 'address is required');
825
+ this._changeScript = Script.fromAddress(address);
826
+ this._updateChangeOutput();
827
+ return this;
828
+ };
829
+
830
+
831
+ /**
832
+ * @return {Output} change output, if it exists
833
+ */
834
+ Transaction.prototype.getChangeOutput = function() {
835
+ if (!_.isUndefined(this._changeIndex)) {
836
+ return this.outputs[this._changeIndex];
837
+ }
838
+ return null;
839
+ };
840
+
841
+ /**
842
+ * @typedef {Object} Transaction~toObject
843
+ * @property {(string|Address)} address
844
+ * @property {number} satoshis
845
+ */
846
+
847
+ /**
848
+ * Add an output to the transaction.
849
+ *
850
+ * Beware that this resets all the signatures for inputs (in further versions,
851
+ * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
852
+ *
853
+ * @param {(string|Address|Array.<Transaction~toObject>)} address
854
+ * @param {number} amount in satoshis
855
+ * @return {Transaction} this, for chaining
856
+ */
857
+ Transaction.prototype.to = function(address, amount) {
858
+ if (_.isArray(address)) {
859
+ var self = this;
860
+ _.each(address, function(to) {
861
+ self.to(to.address, to.amount||to.satoshis);
862
+ });
863
+ return this;
864
+ }
865
+
866
+ $.checkArgument(
867
+ JSUtil.isNaturalNumber(amount),
868
+ 'Amount is expected to be a positive integer'
869
+ );
870
+ this.addOutput(new Output({
871
+ script: Script(new Address(address)),
872
+ satoshis: amount
873
+ }));
874
+ return this;
875
+ };
876
+
877
+ /**
878
+ * Add an OP_RETURN output to the transaction.
879
+ *
880
+ * Beware that this resets all the signatures for inputs (in further versions,
881
+ * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
882
+ *
883
+ * @param {Buffer|string} value the data to be stored in the OP_RETURN output.
884
+ * In case of a string, the UTF-8 representation will be stored
885
+ * @return {Transaction} this, for chaining
886
+ */
887
+ Transaction.prototype.addData = function(value) {
888
+ this.addOutput(new Output({
889
+ script: Script.buildDataOut(value),
890
+ satoshis: 0
891
+ }));
892
+ return this;
893
+ };
894
+
895
+
896
+ /**
897
+ * Add an output to the transaction.
898
+ *
899
+ * @param {Output} output the output to add.
900
+ * @return {Transaction} this, for chaining
901
+ */
902
+ Transaction.prototype.addOutput = function(output) {
903
+ $.checkArgumentType(output, Output, 'output');
904
+ this._addOutput(output);
905
+ this._updateChangeOutput();
906
+ return this;
907
+ };
908
+
909
+
910
+ /**
911
+ * Remove all outputs from the transaction.
912
+ *
913
+ * @return {Transaction} this, for chaining
914
+ */
915
+ Transaction.prototype.clearOutputs = function() {
916
+ this.outputs = [];
917
+ this._clearSignatures();
918
+ this._outputAmount = undefined;
919
+ this._changeIndex = undefined;
920
+ this._updateChangeOutput();
921
+ return this;
922
+ };
923
+
924
+
925
+ Transaction.prototype._addOutput = function(output) {
926
+ this.outputs.push(output);
927
+ this._outputAmount = undefined;
928
+ };
929
+
930
+
931
+ /**
932
+ * Calculates or gets the total output amount in satoshis
933
+ *
934
+ * @return {BN} the transaction total output amount
935
+ */
936
+ Transaction.prototype._getOutputAmount = function() {
937
+ if (_.isUndefined(this._outputAmount)) {
938
+ this._outputAmount = this.outputs.reduce((sum, output) => {
939
+ return sum.add(new BN(output.satoshis));
940
+ }, new BN(0));
941
+ }
942
+ return this._outputAmount;
943
+ };
944
+
945
+
946
+ /**
947
+ * Calculates or gets the total input amount in satoshis
948
+ *
949
+ * @return {BN} the transaction total input amount
950
+ */
951
+ Transaction.prototype._getInputAmount = function() {
952
+ if (_.isUndefined(this._inputAmount)) {
953
+ this._inputAmount = this.inputs.reduce((sum, input) => {
954
+ if (_.isUndefined(input.output)) {
955
+ throw new errors.Transaction.Input.MissingPreviousOutput();
956
+ }
957
+ return sum.add(new BN(input.output.satoshis));
958
+ }, new BN(0));
959
+ }
960
+ return this._inputAmount;
961
+ };
962
+
963
+ Transaction.prototype._updateChangeOutput = function() {
964
+ if (!this._changeScript) {
965
+ return;
966
+ }
967
+ this._clearSignatures();
968
+ if (!_.isUndefined(this._changeIndex)) {
969
+ this._removeOutput(this._changeIndex);
970
+ }
971
+ var available = this._getUnspentValue();
972
+ var fee = this.getFee();
973
+ var changeAmount = available.sub(fee);
974
+ if (changeAmount.gt(0)) {
975
+ this._changeIndex = this.outputs.length;
976
+ this._addOutput(new Output({
977
+ script: this._changeScript,
978
+ satoshis: changeAmount
979
+ }));
980
+ } else {
981
+ this._changeIndex = undefined;
982
+ }
983
+ };
984
+ /**
985
+ * Calculates the fee of the transaction.
986
+ *
987
+ * If there's a fixed fee set, return that.
988
+ *
989
+ * If there is no change output set, the fee is the
990
+ * total value of the outputs minus inputs. Note that
991
+ * a serialized transaction only specifies the value
992
+ * of its outputs. (The value of inputs are recorded
993
+ * in the previous transaction outputs being spent.)
994
+ * This method therefore raises a "MissingPreviousOutput"
995
+ * error when called on a serialized transaction.
996
+ *
997
+ * If there's no fee set and no change address,
998
+ * estimate the fee based on size.
999
+ *
1000
+ * @return {Number} fee of this transaction in satoshis
1001
+ */
1002
+ Transaction.prototype.getFee = function() {
1003
+ if (this.isCoinbase()) {
1004
+ return 0;
1005
+ }
1006
+ if (!_.isUndefined(this._fee)) {
1007
+ return this._fee;
1008
+ }
1009
+ // if no change output is set, fees should equal all the unspent amount
1010
+ if (!this._changeScript) {
1011
+ return this._getUnspentValue().toNumber();
1012
+ }
1013
+ return this._estimateFee();
1014
+ };
1015
+
1016
+ /**
1017
+ * Estimates fee from serialized transaction size in bytes.
1018
+ */
1019
+ Transaction.prototype._estimateFee = function() {
1020
+ var estimatedSize = this._estimateSize();
1021
+ var available = this._getUnspentValue();
1022
+ var feeRate = this._feePerByte || (this._feePerKb || Transaction.FEE_PER_KB) / 1000;
1023
+
1024
+ function getFee(size) {
1025
+ return size * feeRate;
1026
+ }
1027
+ var fee = Math.ceil(getFee(estimatedSize));
1028
+ var feeWithChange = Math.ceil(getFee(estimatedSize) + getFee(Transaction.CHANGE_OUTPUT_MAX_SIZE));
1029
+ if (!this._changeScript || available.lte(feeWithChange)) {
1030
+ return fee;
1031
+ }
1032
+ return feeWithChange;
1033
+ };
1034
+
1035
+ Transaction.prototype._getUnspentValue = function() {
1036
+ return this._getInputAmount().sub(this._getOutputAmount());
1037
+ };
1038
+
1039
+ Transaction.prototype._clearSignatures = function() {
1040
+ _.each(this.inputs, function(input) {
1041
+ input.clearSignatures();
1042
+ });
1043
+ };
1044
+
1045
+ Transaction.prototype._estimateSize = function() {
1046
+ var result = Transaction.MAXIMUM_EXTRA_SIZE;
1047
+ _.each(this.inputs, function(input) {
1048
+ result += input._estimateSize();
1049
+ });
1050
+ _.each(this.outputs, function(output) {
1051
+ result += output.script.toBuffer().length + 9;
1052
+ });
1053
+ return result;
1054
+ };
1055
+
1056
+ Transaction.prototype._removeOutput = function(index) {
1057
+ var output = this.outputs[index];
1058
+ this.outputs = _.without(this.outputs, output);
1059
+ this._outputAmount = undefined;
1060
+ };
1061
+
1062
+ Transaction.prototype.removeOutput = function(index) {
1063
+ this._removeOutput(index);
1064
+ this._updateChangeOutput();
1065
+ };
1066
+
1067
+ /**
1068
+ * Sort a transaction's inputs and outputs according to BIP69
1069
+ *
1070
+ * @see {https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki}
1071
+ * @return {Transaction} this
1072
+ */
1073
+ Transaction.prototype.sort = function() {
1074
+ this.sortInputs(function(inputs) {
1075
+ var copy = Array.prototype.concat.apply([], inputs);
1076
+ let i = 0;
1077
+ copy.forEach((x) => {
1078
+ x.i = i++
1079
+ });
1080
+ copy.sort(function(first, second) {
1081
+ return compare(first.prevTxId, second.prevTxId) || first.outputIndex - second.outputIndex || first.i - second.i; // to ensure stable sort
1082
+ });
1083
+ return copy;
1084
+ });
1085
+ this.sortOutputs(function(outputs) {
1086
+ var copy = Array.prototype.concat.apply([], outputs);
1087
+ let i = 0;
1088
+ copy.forEach((x) => {
1089
+ x.i = i++
1090
+ });
1091
+ copy.sort(function(first, second) {
1092
+ return first.satoshis - second.satoshis || compare(first.script.toBuffer(), second.script.toBuffer()) || first.i - second.i; // to ensure stable sort
1093
+ });
1094
+ return copy;
1095
+ });
1096
+ return this;
1097
+ };
1098
+
1099
+ /**
1100
+ * Randomize this transaction's outputs ordering. The shuffling algorithm is a
1101
+ * version of the Fisher-Yates shuffle, provided by lodash's _.shuffle().
1102
+ *
1103
+ * @return {Transaction} this
1104
+ */
1105
+ Transaction.prototype.shuffleOutputs = function() {
1106
+ return this.sortOutputs(_.shuffle);
1107
+ };
1108
+
1109
+ /**
1110
+ * Sort this transaction's outputs, according to a given sorting function that
1111
+ * takes an array as argument and returns a new array, with the same elements
1112
+ * but with a different order. The argument function MUST NOT modify the order
1113
+ * of the original array
1114
+ *
1115
+ * @param {Function} sortingFunction
1116
+ * @return {Transaction} this
1117
+ */
1118
+ Transaction.prototype.sortOutputs = function(sortingFunction) {
1119
+ var outs = sortingFunction(this.outputs);
1120
+ return this._newOutputOrder(outs);
1121
+ };
1122
+
1123
+ /**
1124
+ * Sort this transaction's inputs, according to a given sorting function that
1125
+ * takes an array as argument and returns a new array, with the same elements
1126
+ * but with a different order.
1127
+ *
1128
+ * @param {Function} sortingFunction
1129
+ * @return {Transaction} this
1130
+ */
1131
+ Transaction.prototype.sortInputs = function(sortingFunction) {
1132
+ this.inputs = sortingFunction(this.inputs);
1133
+ this._clearSignatures();
1134
+ return this;
1135
+ };
1136
+
1137
+ Transaction.prototype._newOutputOrder = function(newOutputs) {
1138
+ var isInvalidSorting = (this.outputs.length !== newOutputs.length ||
1139
+ _.difference(this.outputs, newOutputs).length !== 0);
1140
+ if (isInvalidSorting) {
1141
+ throw new errors.Transaction.InvalidSorting();
1142
+ }
1143
+
1144
+ if (!_.isUndefined(this._changeIndex)) {
1145
+ var changeOutput = this.outputs[this._changeIndex];
1146
+ this._changeIndex = _.findIndex(newOutputs, changeOutput);
1147
+ }
1148
+
1149
+ this.outputs = newOutputs;
1150
+ return this;
1151
+ };
1152
+
1153
+ Transaction.prototype.removeInput = function(txId, outputIndex) {
1154
+ var index;
1155
+ if (!outputIndex && _.isNumber(txId)) {
1156
+ index = txId;
1157
+ } else {
1158
+ index = _.findIndex(this.inputs, function(input) {
1159
+ return input.prevTxId.toString('hex') === txId && input.outputIndex === outputIndex;
1160
+ });
1161
+ }
1162
+ if (index < 0 || index >= this.inputs.length) {
1163
+ throw new errors.Transaction.InvalidIndex(index, this.inputs.length);
1164
+ }
1165
+ var input = this.inputs[index];
1166
+ this.inputs = _.without(this.inputs, input);
1167
+ this._inputAmount = undefined;
1168
+ this._updateChangeOutput();
1169
+ };
1170
+
1171
+ /* Signature handling */
1172
+
1173
+ /**
1174
+ * Sign the transaction using one or more private keys.
1175
+ *
1176
+ * It tries to sign each input, verifying that the signature will be valid
1177
+ * (matches a public key).
1178
+ *
1179
+ * @param {Array|String|PrivateKey} privateKey
1180
+ * @param {number} sigtype
1181
+ * @return {Transaction} this, for chaining
1182
+ */
1183
+ Transaction.prototype.sign = function(privateKey, sigtype, signingMethod) {
1184
+ this.inputMap = new Map();
1185
+ this.inputs.map((input, index)=>{
1186
+ let address = input.output.script.getPublicKey().toString("hex");
1187
+ //console.log("#####address", address)
1188
+ let list = this.inputMap.get(address)
1189
+ if(!list){
1190
+ list = [];
1191
+ this.inputMap.set(address, list);
1192
+ }
1193
+ list.push({input, index})
1194
+ })
1195
+
1196
+ this._sign(privateKey, sigtype, signingMethod);
1197
+ return this;
1198
+ }
1199
+ Transaction.prototype._sign = function(privateKey, sigtype, signingMethod) {
1200
+ signingMethod = signingMethod || "ecdsa"
1201
+
1202
+ $.checkState(this.hasAllUtxoInfo(), 'Not all utxo information is available to sign the transaction.');
1203
+ var self = this;
1204
+ if (_.isArray(privateKey)) {
1205
+ //let l1 = privateKey.length;
1206
+ privateKey = _.uniq(privateKey)
1207
+ //console.log("#####privateKey", l1, privateKey.length)
1208
+ _.each(privateKey, function(privateKey) {
1209
+ self._sign(privateKey, sigtype, signingMethod);
1210
+ });
1211
+ return this;
1212
+ }
1213
+ //let ts0 = Date.now();
1214
+ //console.log("Transaction: getSignatures started")
1215
+ let signatures = this.getSignatures(privateKey, sigtype, signingMethod)||[]
1216
+ //let ts1 = Date.now();
1217
+ //console.log("Transaction: getSignatures time", `${((ts1-ts0)/1000).toFixed(2)} sec`)
1218
+ signatures.map(signature=>{
1219
+ this.applySignature(signature, signingMethod);
1220
+ });
1221
+ //let ts2 = Date.now();
1222
+ //console.log("Transaction: applySignature time", `${((ts2-ts1)/1000).toFixed(2)} sec`)
1223
+
1224
+ return this;
1225
+ };
1226
+
1227
+ Transaction.prototype.getSignatures = function(privKey, sigtype, signingMethod) {
1228
+ privKey = new PrivateKey(privKey);
1229
+
1230
+ // By default, signs using ALL|FORKID
1231
+ sigtype = sigtype || (Signature.SIGHASH_ALL | Signature.SIGHASH_FORKID);
1232
+ let transaction = this;
1233
+ let results = [];
1234
+
1235
+ let hashData = privKey.publicKey.toBuffer();
1236
+ //if(1){
1237
+ let address = hashData.toString("hex");
1238
+ //console.log("hashData####", address)
1239
+ let sigs, list = this.inputMap.get(address)||[]
1240
+ list.map(({input, index})=>{
1241
+ sigs = input.getSignatures(transaction, privKey, index, sigtype, hashData, signingMethod)||[]
1242
+ results.push(...sigs)
1243
+ });
1244
+ /*}else{
1245
+ _.each(this.inputs, function forEachInput(input, index) {
1246
+ _.each(input.getSignatures(transaction, privKey, index, sigtype, hashData, signingMethod), function(signature) {
1247
+ results.push(signature);
1248
+ });
1249
+ });
1250
+ }*/
1251
+ return results;
1252
+ };
1253
+
1254
+ /**
1255
+ * Add a signature to the transaction
1256
+ *
1257
+ * @param {Object} signature
1258
+ * @param {number} signature.inputIndex
1259
+ * @param {number} signature.sigtype
1260
+ * @param {PublicKey} signature.publicKey
1261
+ * @param {Signature} signature.signature
1262
+ * @param {String} signingMethod "ecdsa" or "schnorr"
1263
+ * @return {Transaction} this, for chaining
1264
+ */
1265
+ Transaction.prototype.applySignature = function(signature, signingMethod) {
1266
+ this.inputs[signature.inputIndex].addSignature(this, signature, signingMethod);
1267
+ return this;
1268
+ };
1269
+
1270
+ Transaction.prototype.isFullySigned = function() {
1271
+ _.each(this.inputs, function(input) {
1272
+ if (input.isFullySigned === Input.prototype.isFullySigned) {
1273
+ throw new errors.Transaction.UnableToVerifySignature(
1274
+ 'Unrecognized script kind, or not enough information to execute script.' +
1275
+ 'This usually happens when creating a transaction from a serialized transaction'
1276
+ );
1277
+ }
1278
+ });
1279
+ return _.every(_.map(this.inputs, function(input) {
1280
+ return input.isFullySigned();
1281
+ }));
1282
+ };
1283
+
1284
+ Transaction.prototype.isValidSignature = function(signature) {
1285
+ var self = this;
1286
+ if (this.inputs[signature.inputIndex].isValidSignature === Input.prototype.isValidSignature) {
1287
+ throw new errors.Transaction.UnableToVerifySignature(
1288
+ 'Unrecognized script kind, or not enough information to execute script.' +
1289
+ 'This usually happens when creating a transaction from a serialized transaction'
1290
+ );
1291
+ }
1292
+ return this.inputs[signature.inputIndex].isValidSignature(self, signature);
1293
+ };
1294
+
1295
+ /**
1296
+ * @returns {bool} whether the signature is valid for this transaction input
1297
+ */
1298
+ Transaction.prototype.verifySignature = function(sig, pubkey, nin, subscript, satoshisBN, flags, signingMethod) {
1299
+ return Sighash.verify(this, sig, pubkey, nin, subscript, satoshisBN, flags, signingMethod);
1300
+ };
1301
+
1302
+ /**
1303
+ * Check that a transaction passes basic sanity tests. If not, return a string
1304
+ * describing the error. This function contains the same logic as
1305
+ * CheckTransaction in bitcoin core.
1306
+ */
1307
+ Transaction.prototype.verify = function() {
1308
+ // Basic checks that don't depend on any context
1309
+ if (this.inputs.length === 0) {
1310
+ return 'transaction txins empty';
1311
+ }
1312
+
1313
+ if (this.outputs.length === 0) {
1314
+ return 'transaction txouts empty';
1315
+ }
1316
+
1317
+ // Check for negative or overflow output values
1318
+ var valueoutbn = new BN(0);
1319
+ for (var i = 0; i < this.outputs.length; i++) {
1320
+ var txout = this.outputs[i];
1321
+
1322
+ if (txout.invalidSatoshis()) {
1323
+ return 'transaction txout ' + i + ' satoshis is invalid';
1324
+ }
1325
+ if (txout._satoshisBN.gt(new BN(Transaction.MAX_MONEY, 10))) {
1326
+ return 'transaction txout ' + i + ' greater than MAX_MONEY';
1327
+ }
1328
+ valueoutbn = valueoutbn.add(txout._satoshisBN);
1329
+ if (valueoutbn.gt(new BN(Transaction.MAX_MONEY))) {
1330
+ return 'transaction txout ' + i + ' total output greater than MAX_MONEY';
1331
+ }
1332
+ }
1333
+
1334
+ // Size limits
1335
+ if (this.toBuffer().length > MAX_BLOCK_SIZE) {
1336
+ return 'transaction over the maximum block size';
1337
+ }
1338
+
1339
+ // Check for duplicate inputs
1340
+ var txinmap = {};
1341
+ for (i = 0; i < this.inputs.length; i++) {
1342
+ var txin = this.inputs[i];
1343
+
1344
+ var inputid = txin.prevTxId + ':' + txin.outputIndex;
1345
+ if (!_.isUndefined(txinmap[inputid])) {
1346
+ return 'transaction input ' + i + ' duplicate input';
1347
+ }
1348
+ txinmap[inputid] = true;
1349
+ }
1350
+
1351
+ var isCoinbase = this.isCoinbase();
1352
+ if (isCoinbase) {
1353
+ var buf = this.inputs[0]._scriptBuffer;
1354
+ if (buf.length < 2 || buf.length > 100) {
1355
+ return 'coinbase transaction script size invalid';
1356
+ }
1357
+ } else {
1358
+ for (i = 0; i < this.inputs.length; i++) {
1359
+ if (this.inputs[i].isNull()) {
1360
+ return 'transaction input ' + i + ' has null input';
1361
+ }
1362
+ }
1363
+ }
1364
+ return true;
1365
+ };
1366
+
1367
+ /**
1368
+ * Analogous to bitcoind's IsCoinBase function in transaction.h
1369
+ */
1370
+ Transaction.prototype.isCoinbase = function() {
1371
+ return (this.inputs.length === 1 && this.inputs[0].isNull());
1372
+ };
1373
+
1374
+
1375
+ Transaction.prototype.setVersion = function(version) {
1376
+ $.checkArgument(
1377
+ JSUtil.isNaturalNumber(version) && version <= CURRENT_VERSION,
1378
+ 'Wrong version number');
1379
+ this.version = version;
1380
+ return this;
1381
+ };
1382
+
1383
+
1384
+ module.exports = Transaction;