-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
transaction.js
1458 lines (1305 loc) · 42.9 KB
/
transaction.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
var _ = require('lodash');
var $ = require('../util/preconditions');
var buffer = require('buffer');
var compare = Buffer.compare || require('buffer-compare');
var errors = require('../errors');
var BufferUtil = require('../util/buffer');
var JSUtil = require('../util/js');
var BufferReader = require('../encoding/bufferreader');
var BufferWriter = require('../encoding/bufferwriter');
var Hash = require('../crypto/hash');
var Signature = require('../crypto/signature');
var Sighash = require('./sighash');
var SighashWitness = require('./sighashwitness');
var Address = require('../address');
var UnspentOutput = require('./unspentoutput');
var Input = require('./input');
var PublicKeyHashInput = Input.PublicKeyHash;
var PublicKeyInput = Input.PublicKey;
var MultiSigScriptHashInput = Input.MultiSigScriptHash;
var MultiSigInput = Input.MultiSig;
var Output = require('./output');
var Script = require('../script');
var PrivateKey = require('../privatekey');
var BN = require('../crypto/bn');
var Interpreter = require('../script/interpreter');
/**
* Represents a transaction, a set of inputs and outputs to change ownership of tokens
*
* @param {*} serialized
* @constructor
*/
function Transaction(serialized, opts) {
if (!(this instanceof Transaction)) {
return new Transaction(serialized);
}
this.inputs = [];
this.outputs = [];
this._inputAmount = undefined;
this._outputAmount = undefined;
if (serialized) {
if (serialized instanceof Transaction) {
return Transaction.shallowCopy(serialized);
} else if (JSUtil.isHexa(serialized)) {
this.fromString(serialized);
} else if (BufferUtil.isBuffer(serialized)) {
this.fromBuffer(serialized);
} else if (_.isObject(serialized)) {
this.fromObject(serialized, opts);
} else {
throw new errors.InvalidArgument('Must provide an object or string to deserialize a transaction');
}
} else {
this._newTransaction();
}
}
var CURRENT_VERSION = 1;
var DEFAULT_NLOCKTIME = 0;
var MAX_BLOCK_SIZE = 1000000;
// Minimum amount for an output for it not to be considered a dust output
// https://github.com/dogecoin/dogecoin/blob/a758fa798217ea7c12e08224596dc0ae9c03b2a8/doc/fee-recommendation.md
Transaction.DUST_AMOUNT = 1000000; // 0.01 DOGE
// Margin of error to allow fees in the vecinity of the expected value but doesn't allow a big difference
Transaction.FEE_SECURITY_MARGIN = 15;
// max amount of satoshis in circulation
// Dogecoin has 100000000000 * 1e8 coins in satoshis //10000000
// This number can be found at (https://github.com/dogecoin/dogecoin/blob/0b46a40ed125d7bf4b5a485b91350bc8bdc48fc8/src/amount.h)
// This is the largest possible number that bn.js can accept; Anything larger will cause an assert error
Transaction.MAX_MONEY = 9007199254740991;
// nlocktime limit to be considered block height rather than a timestamp
Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT = 5e8;
// Max value for an unsigned 32 bit value
Transaction.NLOCKTIME_MAX_VALUE = 4294967295;
// Value used for fee estimation (satoshis per kilobyte)
// https://github.com/dogecoin/dogecoin/blob/0b46a40ed125d7bf4b5a485b91350bc8bdc48fc8/doc/man/dogecoin-qt.1
Transaction.FEE_PER_KB = 100000000; // default fees is 1 DOGE
// Safe upper bound for change address script size in bytes
Transaction.CHANGE_OUTPUT_MAX_SIZE = 20 + 4 + 34 + 4;
Transaction.MAXIMUM_EXTRA_SIZE = 4 + 9 + 9 + 4;
/* Constructors and Serialization */
/**
* Create a 'shallow' copy of the transaction, by serializing and deserializing
* it dropping any additional information that inputs and outputs may have hold
*
* @param {Transaction} transaction
* @return {Transaction}
*/
Transaction.shallowCopy = function(transaction) {
var copy = new Transaction(transaction.toBuffer());
return copy;
};
var hashProperty = {
configurable: false,
enumerable: true,
get: function() {
this._hash = new BufferReader(this._getHash()).readReverse().toString('hex');
return this._hash;
}
};
var witnessHashProperty = {
configurable: false,
enumerable: true,
get: function() {
return new BufferReader(this._getWitnessHash()).readReverse().toString('hex');
}
};
Object.defineProperty(Transaction.prototype, 'witnessHash', witnessHashProperty);
Object.defineProperty(Transaction.prototype, 'hash', hashProperty);
Object.defineProperty(Transaction.prototype, 'id', hashProperty);
var ioProperty = {
configurable: false,
enumerable: true,
get: function() {
return this._getInputAmount();
}
};
Object.defineProperty(Transaction.prototype, 'inputAmount', ioProperty);
ioProperty.get = function() {
return this._getOutputAmount();
};
Object.defineProperty(Transaction.prototype, 'outputAmount', ioProperty);
Object.defineProperty(Transaction.prototype, 'size', {
configurable: false,
enumerable: false,
get: function() {
return this._calculateSize();
}
});
Object.defineProperty(Transaction.prototype, 'vsize', {
configurable: false,
enumerable: false,
get: function() {
return this._calculateVSize();
}
});
Object.defineProperty(Transaction.prototype, 'weight', {
configurable: false,
enumerable: false,
get: function() {
return this._calculateWeight();
}
});
/**
* Retrieve the little endian hash of the transaction (used for serialization)
* @return {Buffer}
*/
Transaction.prototype._getHash = function() {
return Hash.sha256sha256(this.toBuffer(true));
};
/**
* Retrieve the little endian hash of the transaction including witness data
* @return {Buffer}
*/
Transaction.prototype._getWitnessHash = function() {
return Hash.sha256sha256(this.toBuffer(false));
};
/**
* Retrieve a hexa string that can be used with bitcoind's CLI interface
* (decoderawtransaction, sendrawtransaction)
*
* @param {Object|boolean=} unsafe if true, skip all tests. if it's an object,
* it's expected to contain a set of flags to skip certain tests:
* * `disableAll`: disable all checks
* * `disableSmallFees`: disable checking for fees that are too small
* * `disableLargeFees`: disable checking for fees that are too large
* * `disableIsFullySigned`: disable checking if all inputs are fully signed
* * `disableDustOutputs`: disable checking if there are no outputs that are dust amounts
* * `disableMoreOutputThanInput`: disable checking if the transaction spends more bitcoins than the sum of the input amounts
* @return {string}
*/
Transaction.prototype.serialize = function(unsafe) {
if (true === unsafe || unsafe && unsafe.disableAll) {
return this.uncheckedSerialize();
} else {
return this.checkedSerialize(unsafe);
}
};
Transaction.prototype.uncheckedSerialize = Transaction.prototype.toString = function() {
return this.toBuffer().toString('hex');
};
/**
* Retrieve a hexa string that can be used with bitcoind's CLI interface
* (decoderawtransaction, sendrawtransaction)
*
* @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
* @return {string}
*/
Transaction.prototype.checkedSerialize = function(opts) {
var serializationError = this.getSerializationError(opts);
if (serializationError) {
serializationError.message += ' - For more information please see: ' +
'https://bitcore.io/api/lib/transaction#serialization-checks';
throw serializationError;
}
return this.uncheckedSerialize();
};
Transaction.prototype.invalidSatoshis = function() {
var invalid = false;
for (var i = 0; i < this.outputs.length; i++) {
if (this.outputs[i].invalidSatoshis()) {
invalid = true;
}
}
return invalid;
};
/**
* Retrieve a possible error that could appear when trying to serialize and
* broadcast this transaction.
*
* @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
* @return {bitcore.Error}
*/
Transaction.prototype.getSerializationError = function(opts) {
opts = opts || {};
if (this.invalidSatoshis()) {
return new errors.Transaction.InvalidSatoshis();
}
var unspent = this._getUnspentValue();
var unspentError;
if (unspent < 0) {
if (!opts.disableMoreOutputThanInput) {
unspentError = new errors.Transaction.InvalidOutputAmountSum();
}
} else {
unspentError = this._hasFeeError(opts, unspent);
}
return unspentError ||
this._hasDustOutputs(opts) ||
this._isMissingSignatures(opts);
};
Transaction.prototype._hasFeeError = function(opts, unspent) {
if (this._fee != null && this._fee !== unspent) {
return new errors.Transaction.FeeError.Different(
'Unspent value is ' + unspent + ' but specified fee is ' + this._fee
);
}
if (!opts.disableLargeFees) {
var maximumFee = Math.floor(Transaction.FEE_SECURITY_MARGIN * this._estimateFee());
if (unspent > maximumFee) {
if (this._missingChange()) {
return new errors.Transaction.ChangeAddressMissing(
'Fee is too large and no change address was provided'
);
}
return new errors.Transaction.FeeError.TooLarge(
'expected less than ' + maximumFee + ' but got ' + unspent
);
}
}
if (!opts.disableSmallFees) {
var minimumFee = Math.ceil(this._estimateFee() / Transaction.FEE_SECURITY_MARGIN);
if (unspent < minimumFee) {
return new errors.Transaction.FeeError.TooSmall(
'expected more than ' + minimumFee + ' but got ' + unspent
);
}
}
};
Transaction.prototype._missingChange = function() {
return !this._changeScript;
};
Transaction.prototype._hasDustOutputs = function(opts) {
if (opts.disableDustOutputs) {
return;
}
var index, output;
for (index in this.outputs) {
output = this.outputs[index];
if (output.satoshis < Transaction.DUST_AMOUNT && !output.script.isDataOut()) {
return new errors.Transaction.DustOutputs();
}
}
};
Transaction.prototype._isMissingSignatures = function(opts) {
if (opts.disableIsFullySigned) {
return;
}
if (!this.isFullySigned()) {
return new errors.Transaction.MissingSignatures();
}
};
Transaction.prototype.inspect = function() {
return '<Transaction: ' + this.uncheckedSerialize() + '>';
};
Transaction.prototype.toBuffer = function(noWitness) {
var writer = new BufferWriter();
return this.toBufferWriter(writer, noWitness).toBuffer();
};
Transaction.prototype.hasWitnesses = function() {
for (var i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].hasWitnesses()) {
return true;
}
}
return false;
};
Transaction.prototype.toBufferWriter = function(writer, noWitness) {
writer.writeInt32LE(this.version);
const hasWitnesses = this.hasWitnesses();
if (hasWitnesses && !noWitness) {
writer.write(Buffer.from('0001', 'hex'));
}
writer.writeVarintNum(this.inputs ? this.inputs.length : 0);
for (const input of this.inputs || []) {
input.toBufferWriter(writer);
}
writer.writeVarintNum(this.outputs ? this.outputs.length : 0);
for (const output of this.outputs || []) {
output.toBufferWriter(writer);
}
if (hasWitnesses && !noWitness) {
for (const input of this.inputs) {
const witnesses = input.getWitnesses();
writer.writeVarintNum(witnesses.length);
for (let j = 0; j < witnesses.length; j++) {
writer.writeVarintNum(witnesses[j].length);
writer.write(witnesses[j]);
}
}
}
writer.writeUInt32LE(this.nLockTime);
return writer;
};
Transaction.prototype.fromBuffer = function(buffer) {
var reader = new BufferReader(buffer);
return this.fromBufferReader(reader);
};
Transaction.prototype.fromBufferReader = function(reader) {
$.checkArgument(!reader.finished(), 'No transaction data received');
this.version = reader.readInt32LE();
var sizeTxIns = reader.readVarintNum();
// check for segwit
var hasWitnesses = false;
if (sizeTxIns === 0 && reader.buf[reader.pos] !== 0) {
reader.pos += 1;
hasWitnesses = true;
sizeTxIns = reader.readVarintNum();
}
for (var i = 0; i < sizeTxIns; i++) {
var input = Input.fromBufferReader(reader);
this.inputs.push(input);
}
var sizeTxOuts = reader.readVarintNum();
for (var j = 0; j < sizeTxOuts; j++) {
this.outputs.push(Output.fromBufferReader(reader));
}
if (hasWitnesses) {
for (var k = 0; k < sizeTxIns; k++) {
var itemCount = reader.readVarintNum();
var witnesses = [];
for (var l = 0; l < itemCount; l++) {
var size = reader.readVarintNum();
var item = reader.read(size);
witnesses.push(item);
}
this.inputs[k].setWitnesses(witnesses);
}
}
this.nLockTime = reader.readUInt32LE();
return this;
};
Transaction.prototype.toObject = Transaction.prototype.toJSON = function toObject() {
var inputs = [];
this.inputs.forEach(function(input) {
inputs.push(input.toObject());
});
var outputs = [];
this.outputs.forEach(function(output) {
outputs.push(output.toObject());
});
var obj = {
hash: this.hash,
version: this.version,
inputs: inputs,
outputs: outputs,
nLockTime: this.nLockTime
};
if (this._changeScript) {
obj.changeScript = this._changeScript.toString();
}
if (this._changeIndex != null) {
obj.changeIndex = this._changeIndex;
}
if (this._fee != null) {
obj.fee = this._fee;
}
return obj;
};
Transaction.prototype.fromObject = function fromObject(arg, opts) {
/* jshint maxstatements: 20 */
$.checkArgument(_.isObject(arg) || arg instanceof Transaction);
var transaction;
if (arg instanceof Transaction) {
transaction = arg.toObject();
} else {
transaction = arg;
}
for (const input of transaction.inputs || []) {
if (!input.output || !input.output.script) {
this.uncheckedAddInput(new Input(input));
continue;
}
var script = new Script(input.output.script);
var txin;
if (script.isPublicKeyHashOut()) {
txin = new Input.PublicKeyHash(input);
} else if (script.isScriptHashOut() && input.publicKeys && input.threshold) {
txin = new Input.MultiSigScriptHash(
input, input.publicKeys, input.threshold, input.signatures
);
} else if (script.isPublicKeyOut()) {
txin = new Input.PublicKey(input);
} else {
throw new errors.Transaction.Input.UnsupportedScript(input.output.script);
}
this.addInput(txin);
}
for (const output of transaction.outputs || []) {
this.addOutput(new Output(output));
}
if (transaction.changeIndex) {
this._changeIndex = transaction.changeIndex;
}
if (transaction.changeScript) {
this._changeScript = new Script(transaction.changeScript);
}
if (transaction.fee) {
this._fee = transaction.fee;
}
this.nLockTime = transaction.nLockTime;
this.version = transaction.version;
this._checkConsistency(arg);
return this;
};
Transaction.prototype._checkConsistency = function(arg) {
if (this._changeIndex != null) {
$.checkState(this._changeScript, 'Change script is expected.');
$.checkState(this.outputs[this._changeIndex], 'Change index points to undefined output.');
$.checkState(this.outputs[this._changeIndex].script.toString() ===
this._changeScript.toString(), 'Change output has an unexpected script.');
}
if (arg && arg.hash) {
$.checkState(arg.hash === this.hash, 'Hash in object does not match transaction hash.');
}
};
/**
* Sets nLockTime so that transaction is not valid until the desired date(a
* timestamp in seconds since UNIX epoch is also accepted)
*
* @param {Date | Number} time
* @return {Transaction} this
*/
Transaction.prototype.lockUntilDate = function(time) {
$.checkArgument(time);
if (!isNaN(time) && time < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
throw new errors.Transaction.LockTimeTooEarly();
}
if (_.isDate(time)) {
time = time.getTime() / 1000;
}
for (var i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER){
this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
}
}
this.nLockTime = time;
return this;
};
/**
* Sets nLockTime so that transaction is not valid until the desired block
* height.
*
* @param {Number} height
* @return {Transaction} this
*/
Transaction.prototype.lockUntilBlockHeight = function(height) {
$.checkArgument(!isNaN(height));
if (height >= Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
throw new errors.Transaction.BlockHeightTooHigh();
}
if (height < 0) {
throw new errors.Transaction.NLockTimeOutOfRange();
}
for (var i = 0; i < this.inputs.length; i++) {
if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER){
this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
}
}
this.nLockTime = height;
return this;
};
/**
* Returns a semantic version of the transaction's nLockTime.
* @return {Number|Date}
* If nLockTime is 0, it returns null,
* if it is < 500000000, it returns a block height (number)
* else it returns a Date object.
*/
Transaction.prototype.getLockTime = function() {
if (!this.nLockTime) {
return null;
}
if (this.nLockTime < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
return this.nLockTime;
}
return new Date(1000 * this.nLockTime);
};
Transaction.prototype.fromString = function(string) {
this.fromBuffer(buffer.Buffer.from(string, 'hex'));
};
Transaction.prototype._newTransaction = function() {
this.version = CURRENT_VERSION;
this.nLockTime = DEFAULT_NLOCKTIME;
};
/* Transaction creation interface */
/**
* @typedef {Object} Transaction~fromObject
* @property {string} prevTxId
* @property {number} outputIndex
* @property {(Buffer|string|Script)} script
* @property {number} satoshis
*/
/**
* Add an input to this transaction. This is a high level interface
* to add an input, for more control, use @{link Transaction#addInput}.
*
* Can receive, as output information, the output of bitcoind's `listunspent` command,
* and a slightly fancier format recognized by bitcore:
*
* ```
* {
* address: 'mszYqVnqKoQx4jcTdJXxwKAissE3Jbrrc1',
* txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458',
* outputIndex: 0,
* script: Script.empty(),
* satoshis: 1020000
* }
* ```
* Where `address` can be either a string or a bitcore Address object. The
* same is true for `script`, which can be a string or a bitcore Script.
*
* Beware that this resets all the signatures for inputs (in further versions,
* SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
*
* @example
* ```javascript
* var transaction = new Transaction();
*
* // From a pay to public key hash output from bitcoind's listunspent
* transaction.from({'txid': '0000...', vout: 0, amount: 0.1, scriptPubKey: 'OP_DUP ...'});
*
* // From a pay to public key hash output
* transaction.from({'txId': '0000...', outputIndex: 0, satoshis: 1000, script: 'OP_DUP ...'});
*
* // From a multisig P2SH output
* transaction.from({'txId': '0000...', inputIndex: 0, satoshis: 1000, script: '... OP_HASH'},
* ['03000...', '02000...'], 2);
* ```
*
* @param {(Array.<Transaction~fromObject>|Transaction~fromObject)} utxo
* @param {Array=} pubkeys
* @param {number=} threshold
* @param {Object=} opts - Several options:
* - noSorting: defaults to false, if true and is multisig, don't
* sort the given public keys before creating the script
*/
Transaction.prototype.from = function(utxo, pubkeys, threshold, opts) {
if (Array.isArray(utxo)) {
for (const u of utxo) {
this.from(u, pubkeys, threshold, opts);
}
return this;
}
var exists = this.inputs.some(function(input) {
// TODO: Maybe prevTxId should be a string? Or defined as read only property?
return input.prevTxId.toString('hex') === utxo.txId && input.outputIndex === utxo.outputIndex;
});
if (exists) {
return this;
}
if (pubkeys && threshold) {
this._fromMultisigUtxo(utxo, pubkeys, threshold, opts);
} else {
this._fromNonP2SH(utxo);
}
return this;
};
/**
* associateInputs - Update inputs with utxos, allowing you to specify value, and pubkey.
* Populating these inputs allows for them to be signed with .sign(privKeys)
*
* @param {Array<Object>} utxos
* @param {Array<string | PublicKey>} pubkeys
* @param {number} threshold
* @param {Object} opts
* @returns {Array<number>}
*/
Transaction.prototype.associateInputs = function(utxos, pubkeys, threshold, opts) {
let indexes = [];
for(let utxo of utxos) {
const index = this.inputs.findIndex(i => i.prevTxId.toString('hex') === utxo.txId && i.outputIndex === utxo.outputIndex);
indexes.push(index);
if(index >= 0) {
this.inputs[index] = this._getInputFrom(utxo, pubkeys, threshold, opts);
}
}
return indexes;
}
Transaction.prototype._selectInputType = function(utxo, pubkeys, threshold) {
var clazz;
utxo = new UnspentOutput(utxo);
if(pubkeys && threshold) {
if (utxo.script.isMultisigOut()) {
clazz = MultiSigInput;
} else if (utxo.script.isScriptHashOut()) {
clazz = MultiSigScriptHashInput;
}
} else if (utxo.script.isPublicKeyHashOut()) {
clazz = PublicKeyHashInput;
} else if (utxo.script.isPublicKeyOut()) {
clazz = PublicKeyInput;
} else {
clazz = Input;
}
return clazz;
}
Transaction.prototype._getInputFrom = function(utxo, pubkeys, threshold, opts) {
utxo = new UnspentOutput(utxo);
const InputClass = this._selectInputType(utxo, pubkeys, threshold);
const input = {
output: new Output({
script: utxo.script,
satoshis: utxo.satoshis
}),
prevTxId: utxo.txId,
outputIndex: utxo.outputIndex,
sequenceNumber: utxo.sequenceNumber,
script: Script.empty()
};
let args = pubkeys && threshold ? [pubkeys, threshold, false, opts] : []
return new InputClass(input, ...args);
}
Transaction.prototype._fromNonP2SH = function(utxo) {
const input = this._getInputFrom(utxo);
this.addInput(input);
};
Transaction.prototype._fromMultisigUtxo = function(utxo, pubkeys, threshold, opts) {
$.checkArgument(threshold <= pubkeys.length,
'Number of required signatures must be greater than the number of public keys');
const input = this._getInputFrom(utxo, pubkeys, threshold, opts);
this.addInput(input);
};
/**
* Add an input to this transaction. The input must be an instance of the `Input` class.
* It should have information about the Output that it's spending, but if it's not already
* set, two additional parameters, `outputScript` and `satoshis` can be provided.
*
* @param {Input} input
* @param {String|Script} outputScript
* @param {number} satoshis
* @return Transaction this, for chaining
*/
Transaction.prototype.addInput = function(input, outputScript, satoshis) {
$.checkArgumentType(input, Input, 'input');
if (!input.output && (outputScript == null || satoshis == null)) {
throw new errors.Transaction.NeedMoreInfo('Need information about the UTXO script and satoshis');
}
if (!input.output && outputScript && satoshis != null) {
outputScript = outputScript instanceof Script ? outputScript : new Script(outputScript);
$.checkArgumentType(satoshis, 'number', 'satoshis');
input.output = new Output({
script: outputScript,
satoshis: satoshis
});
}
return this.uncheckedAddInput(input);
};
/**
* Add an input to this transaction, without checking that the input has information about
* the output that it's spending.
*
* @param {Input} input
* @return Transaction this, for chaining
*/
Transaction.prototype.uncheckedAddInput = function(input) {
$.checkArgumentType(input, Input, 'input');
this.inputs.push(input);
this._inputAmount = undefined;
this._updateChangeOutput();
return this;
};
/**
* Returns true if the transaction has enough info on all inputs to be correctly validated
*
* @return {boolean}
*/
Transaction.prototype.hasAllUtxoInfo = function() {
return this.inputs.every(function(input) {
return !!input.output;
});
};
/**
* Manually set the fee for this transaction. Beware that this resets all the signatures
* for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
* be reset).
*
* @param {number} amount satoshis to be sent
* @return {Transaction} this, for chaining
*/
Transaction.prototype.fee = function(amount) {
$.checkArgument(!isNaN(amount), 'amount must be a number');
this._fee = amount;
this._updateChangeOutput();
return this;
};
/**
* Manually set the fee per KB for this transaction. Beware that this resets all the signatures
* for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
* be reset).
*
* @param {number} amount satoshis per KB to be sent
* @return {Transaction} this, for chaining
*/
Transaction.prototype.feePerKb = function(amount) {
$.checkArgument(!isNaN(amount), 'amount must be a number');
this._feePerKb = amount;
this._updateChangeOutput();
return this;
};
/**
* Manually set the fee per Byte for this transaction. Beware that this resets all the signatures
* for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
* be reset).
* fee per Byte will be ignored if fee per KB is set
*
* @param {number} amount satoshis per Byte to be sent
* @return {Transaction} this, for chaining
*/
Transaction.prototype.feePerByte = function (amount) {
$.checkArgument(!isNaN(amount), 'amount must be a number');
this._feePerByte = amount;
this._updateChangeOutput();
return this;
};
/* Output management */
/**
* Set the change address for this transaction
*
* Beware that this resets all the signatures for inputs (in further versions,
* SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
*
* @param {Address} address An address for change to be sent to.
* @return {Transaction} this, for chaining
*/
Transaction.prototype.change = function(address) {
$.checkArgument(address, 'address is required');
this._changeScript = Script.fromAddress(address);
this._updateChangeOutput();
return this;
};
/**
* @return {Output} change output, if it exists
*/
Transaction.prototype.getChangeOutput = function() {
if (this._changeIndex != null) {
return this.outputs[this._changeIndex];
}
return null;
};
/**
* @typedef {Object} Transaction~toObject
* @property {(string|Address)} address
* @property {number} satoshis
*/
/**
* Add an output to the transaction.
*
* Beware that this resets all the signatures for inputs (in further versions,
* SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
*
* @param {(string|Address|Array.<Transaction~toObject>)} address
* @param {number} amount in satoshis
* @return {Transaction} this, for chaining
*/
Transaction.prototype.to = function(address, amount) {
if (Array.isArray(address)) {
for (const to of address) {
this.to(to.address, to.satoshis);
}
return this;
}
$.checkArgument(
JSUtil.isNaturalNumber(amount),
'Amount is expected to be a positive integer'
);
this.addOutput(new Output({
script: Script(new Address(address)),
satoshis: amount
}));
return this;
};
/**
* Add an OP_RETURN output to the transaction.
*
* Beware that this resets all the signatures for inputs (in further versions,
* SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
*
* @param {Buffer|string} value the data to be stored in the OP_RETURN output.
* In case of a string, the UTF-8 representation will be stored
* @return {Transaction} this, for chaining
*/
Transaction.prototype.addData = function(value) {
this.addOutput(new Output({
script: Script.buildDataOut(value),
satoshis: 0
}));
return this;
};
/**
* Add an output to the transaction.
*
* @param {Output} output the output to add.
* @return {Transaction} this, for chaining
*/
Transaction.prototype.addOutput = function(output) {
$.checkArgumentType(output, Output, 'output');
this._addOutput(output);
this._updateChangeOutput();
return this;
};
/**
* Remove all outputs from the transaction.
*
* @return {Transaction} this, for chaining
*/
Transaction.prototype.clearOutputs = function() {
this.outputs = [];
this._clearSignatures();
this._outputAmount = undefined;
this._changeIndex = undefined;
this._updateChangeOutput();
return this;
};
Transaction.prototype._addOutput = function(output) {
this.outputs.push(output);
this._outputAmount = undefined;
};
/**
* Calculates or gets the total output amount in satoshis
*
* @return {Number} the transaction total output amount
*/
Transaction.prototype._getOutputAmount = function() {
if (this._outputAmount == null) {
this._outputAmount = 0;
for (const output of this.outputs) {
this._outputAmount += output.satoshis;
}
}
return this._outputAmount;
};
/**
* Calculates or gets the total input amount in satoshis
*
* @return {Number} the transaction total input amount
*/
Transaction.prototype._getInputAmount = function() {
if (this._inputAmount == null) {
this._inputAmount = _.sumBy(this.inputs, function(input) {
if (input.output == null) {
throw new errors.Transaction.Input.MissingPreviousOutput();
}
return input.output.satoshis;
});
}
return this._inputAmount;
};
Transaction.prototype._updateChangeOutput = function() {
if (!this._changeScript) {
return;
}
this._clearSignatures();
if (this._changeIndex != null) {
this._removeOutput(this._changeIndex);
}
var available = this._getUnspentValue();
var fee = this.getFee();
var changeAmount = available - fee;
if (changeAmount >= Transaction.DUST_AMOUNT) {
this._changeIndex = this.outputs.length;
this._addOutput(new Output({
script: this._changeScript,
satoshis: changeAmount
}));
} else {