@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,7 @@
1
+ module.exports = require('./transaction');
2
+
3
+ module.exports.Input = require('./input');
4
+ module.exports.Output = require('./output');
5
+ module.exports.UnspentOutput = require('./unspentoutput');
6
+ module.exports.Signature = require('./signature');
7
+ module.exports.Sighash = require('./sighash');
@@ -0,0 +1,6 @@
1
+ module.exports = require('./input');
2
+
3
+ module.exports.PublicKey = require('./publickey');
4
+ module.exports.PublicKeyHash = require('./publickeyhash');
5
+ module.exports.MultiSig = require('./multisig.js');
6
+ module.exports.MultiSigScriptHash = require('./multisigscripthash.js');
@@ -0,0 +1,375 @@
1
+ 'use strict';
2
+
3
+ var _ = require('lodash');
4
+ var $ = require('../../util/preconditions');
5
+ var errors = require('../../errors');
6
+ var BN = require('../../crypto/bn');
7
+ var BufferWriter = require('../../encoding/bufferwriter');
8
+ var BufferReader = require('../../encoding/bufferreader');
9
+ var buffer = require('buffer');
10
+ var BufferUtil = require('../../util/buffer');
11
+ var JSUtil = require('../../util/js');
12
+ const {LogBuffer} = JSUtil;
13
+ var Script = require('../../script');
14
+ var Sighash = require('../sighash');
15
+ var Output = require('../output');
16
+ var logLevels = require('../../util/log').logLevels;
17
+
18
+ var MAXINT = 0xffffffff; // Math.pow(2, 32) - 1;
19
+ var DEFAULT_RBF_SEQNUMBER = MAXINT - 2;
20
+ var DEFAULT_SEQNUMBER = MAXINT;
21
+ var DEFAULT_LOCKTIME_SEQNUMBER = MAXINT - 1;
22
+ const SEQUENCE_LOCKTIME_DISABLE_FLAG = Math.pow(2, 31); // (1 << 31);
23
+ const SEQUENCE_LOCKTIME_TYPE_FLAG = Math.pow(2, 22); // (1 << 22);
24
+ const SEQUENCE_LOCKTIME_MASK = 0xffff;
25
+ const SEQUENCE_LOCKTIME_GRANULARITY = 512; // 512 seconds
26
+ const SEQUENCE_BLOCKDIFF_LIMIT = Math.pow(2, 16) - 1; // 16 bits
27
+
28
+
29
+
30
+ function Input(params) {
31
+ if (!(this instanceof Input)) {
32
+ return new Input(params);
33
+ }
34
+ if (params) {
35
+ return this._fromObject(params);
36
+ }
37
+ }
38
+
39
+ Input.MAXINT = MAXINT;
40
+ Input.DEFAULT_SEQNUMBER = DEFAULT_SEQNUMBER;
41
+ Input.DEFAULT_LOCKTIME_SEQNUMBER = DEFAULT_LOCKTIME_SEQNUMBER;
42
+ Input.DEFAULT_RBF_SEQNUMBER = DEFAULT_RBF_SEQNUMBER;
43
+ Input.SEQUENCE_LOCKTIME_TYPE_FLAG = SEQUENCE_LOCKTIME_TYPE_FLAG;
44
+
45
+ Object.defineProperty(Input.prototype, 'script', {
46
+ configurable: false,
47
+ enumerable: true,
48
+ get: function() {
49
+ if (this.isNull()) {
50
+ return null;
51
+ }
52
+ if (!this._script) {
53
+ this._script = new Script(this._scriptBuffer);
54
+ this._script._isInput = true;
55
+ }
56
+ return this._script;
57
+ }
58
+ });
59
+
60
+ Input.fromObject = function(obj) {
61
+ $.checkArgument(_.isObject(obj));
62
+ var input = new Input();
63
+ return input._fromObject(obj);
64
+ };
65
+
66
+ Input.prototype.version = 0;
67
+ Input.prototype._fromObject = function(params) {
68
+ var prevTxId;
69
+ if (_.isString(params.prevTxId) && JSUtil.isHexa(params.prevTxId)) {
70
+ prevTxId = Buffer.from(params.prevTxId, 'hex');
71
+ } else {
72
+ prevTxId = params.prevTxId;
73
+ }
74
+ this.output = params.output ?
75
+ (params.output instanceof Output ? params.output : new Output(params.output)) : undefined;
76
+ this.prevTxId = prevTxId || params.txidbuf;
77
+ this.outputIndex = _.isUndefined(params.outputIndex) ? params.txoutnum : params.outputIndex;
78
+ this.sequenceNumber = _.isUndefined(params.sequenceNumber) ?
79
+ (_.isUndefined(params.seqnum) ? DEFAULT_SEQNUMBER : params.seqnum) : params.sequenceNumber;
80
+ if (_.isUndefined(params.script) && _.isUndefined(params.scriptBuffer)) {
81
+ throw new errors.Transaction.Input.MissingScript();
82
+ }
83
+ this.setScript(params.scriptBuffer || params.script);
84
+ if (params.version !== undefined)
85
+ this.version = params.version;
86
+ //console.log("input._fromObject: version, params", this.version, params)
87
+ return this;
88
+ };
89
+
90
+ Input.prototype.toObject = Input.prototype.toJSON = function toObject() {
91
+ var obj = {
92
+ prevTxId: this.prevTxId.toString('hex'),
93
+ outputIndex: this.outputIndex,
94
+ sequenceNumber: this.sequenceNumber,
95
+ script: this._scriptBuffer.toString('hex'),
96
+ version: this.version
97
+ };
98
+ // add human readable form if input contains valid script
99
+ if (this.script) {
100
+ obj.scriptString = this.script.toString();
101
+ }
102
+ if (this.output) {
103
+ obj.output = this.output.toObject();
104
+ }
105
+ return obj;
106
+ };
107
+
108
+ Input.fromBufferReader = function(br) {
109
+ var input = new Input();
110
+ input.prevTxId = br.read(32);
111
+ input.outputIndex = br.readUInt32LE();
112
+ let length = br.readUInt64LEBN().toNumber();
113
+ if(length){
114
+ length -= 2;
115
+ input.version = br.readUInt16LE();
116
+ }
117
+ input._scriptBuffer = br.read(length);
118
+ input.sequenceNumber = br.readUInt64LEBN().toNumber();
119
+ //TODO: return different classes according to which input it is
120
+ //e.g: CoinbaseInput, PublicKeyHashInput, MultiSigScriptHashInput, etc.
121
+ return input;
122
+ };
123
+ /*
124
+ Input.fromBufferReader_v2 = function(br) {
125
+ var input = {};
126
+ input.prevTxId = br.read(32);
127
+ input.outputIndex = br.readUInt32LE();
128
+ let length = br.readUInt64LEBN().toNumber();
129
+ if(length){
130
+ length -= 2;
131
+ input.version = br.readUInt16LE();
132
+ }
133
+ let scriptBuffer = br.read(length);
134
+ input.sequenceNumber = br.readUInt64LEBN().toNumber();
135
+ input.script = Script.fromBuffer(scriptBuffer)
136
+ let klass = Input;
137
+ console.log("#### isPublicKeyHashOut klass", scriptBuffer, input.script)
138
+ if(input.script.isScriptHashIn()){
139
+ console.log("#### isPublicKeyHashOut")
140
+ const PublicKeyHashInput = require('./publickeyhash');
141
+ klass = PublicKeyHashInput;
142
+ }
143
+ //TODO: return different classes according to which input it is
144
+ //e.g: CoinbaseInput, PublicKeyHashInput, MultiSigScriptHashInput, etc.
145
+ return new klass(input);
146
+ };
147
+ Input.prototype.toBufferWriter_org = function(writer) {
148
+ if (!writer) {
149
+ writer = new BufferWriter();
150
+ }
151
+
152
+ var script = this._scriptBuffer;
153
+
154
+ //@ts-ignore
155
+ let prevTxId = new BufferReader(this.prevTxId).readReverse()
156
+ writer.write(this.prevTxId);
157
+ //LogBuffer("$$$$ prevTxId1: ", this.prevTxId.toString("hex"), writer.bufs)
158
+ writer.writeUInt32LE(this.outputIndex);
159
+ //LogBuffer("$$$$ outputIndex: ", this.outputIndex, writer.bufs)
160
+ let scriptBuf = Buffer.from(script, "hex");
161
+ //if(JSUtil.LogBufferActive && JSUtil.debugLevel > logLevels.debug)
162
+ // console.log("$$$$ Input.version: ", this.version)
163
+ if (scriptBuf.length) {
164
+ let versionBuf = BN.fromNumber(this.version);
165
+ //@ts-ignore
166
+ scriptBuf = Buffer.concat([versionBuf.toBuffer({
167
+ endian: 'little',
168
+ size: 2
169
+ }), scriptBuf]);
170
+ }
171
+ let bn = BN.fromNumber(scriptBuf.length);
172
+ writer.writeUInt64LEBN(bn);
173
+ //LogBuffer("$$$$ script.length: ", scriptBuf.length, writer.bufs)
174
+ writer.write(scriptBuf);
175
+ //LogBuffer("$$$$ script: ", script.toString("hex"), writer.bufs)
176
+ bn = BN.fromNumber(this.sequenceNumber);
177
+ writer.writeUInt64LEBN(bn);
178
+ //LogBuffer("$$$$ sequenceNumber: ", this.sequenceNumber, writer.bufs)
179
+
180
+ return writer;
181
+ };
182
+ */
183
+ const BN_ZERO = BN.fromNumber(0);
184
+ const BN_ONE = BN.fromNumber(1);
185
+ const VERSION_BUFFERS = {
186
+ '0': BN_ZERO.toBuffer({endian: 'little', size: 2}),
187
+ '1': BN_ONE.toBuffer({endian: 'little', size: 2})
188
+ }
189
+
190
+ Input.prototype.toBufferWriter = function(writer) {
191
+ if (!writer) {
192
+ writer = new BufferWriter();
193
+ }
194
+
195
+ //var script = this._scriptBuffer;
196
+
197
+ //@ts-ignore
198
+ //let prevTxId = new BufferReader(this.prevTxId).readReverse()
199
+ writer.write(this.prevTxId);
200
+ //LogBuffer("$$$$ prevTxId1: ", this.prevTxId.toString("hex"), writer.bufs)
201
+ writer.writeUInt32LE(this.outputIndex);
202
+ //LogBuffer("$$$$ outputIndex: ", this.outputIndex, writer.bufs)
203
+
204
+ //if(JSUtil.LogBufferActive && JSUtil.debugLevel > logLevels.debug)
205
+ // console.log("$$$$ Input.version: ", this.version)
206
+ if (this._scriptBuffer.length) {
207
+ //let scriptBuf = Buffer.from(this._scriptBuffer, "hex");
208
+ //@ts-ignore
209
+ let scriptBuf = Buffer.concat([ VERSION_BUFFERS[this.version], this._scriptBuffer]);
210
+ writer.writeUInt64LEBN(BN.fromNumber(scriptBuf.length));
211
+ writer.write(scriptBuf);
212
+ }else{
213
+ writer.writeUInt64LEBN(BN_ZERO);
214
+ //LogBuffer("$$$$ script.length: ", scriptBuf.length, writer.bufs)
215
+ //writer.write(scriptBuf);
216
+ }
217
+
218
+ //LogBuffer("$$$$ script: ", script.toString("hex"), writer.bufs)
219
+ writer.writeUInt64LEBN(BN.fromNumber(this.sequenceNumber));
220
+ //LogBuffer("$$$$ sequenceNumber: ", this.sequenceNumber, writer.bufs)
221
+
222
+ return writer;
223
+ };
224
+
225
+ Input.prototype.setScript = function(script) {
226
+ this._script = null;
227
+ if (script instanceof Script) {
228
+ this._script = script;
229
+ this._script._isInput = true;
230
+ this._scriptBuffer = script.toBuffer();
231
+ } else if (script === null) {
232
+ this._script = Script.empty();
233
+ this._script._isInput = true;
234
+ this._scriptBuffer = this._script.toBuffer();
235
+ } else if (JSUtil.isHexa(script)) {
236
+ // hex string script
237
+ this._scriptBuffer = Buffer.from(script, 'hex');
238
+ } else if (_.isString(script)) {
239
+ // human readable string script
240
+ this._script = new Script(script);
241
+ this._script._isInput = true;
242
+ this._scriptBuffer = this._script.toBuffer();
243
+ } else if (BufferUtil.isBuffer(script)) {
244
+ // buffer script
245
+ this._scriptBuffer = Buffer.from(script);
246
+ } else {
247
+ throw new TypeError('Invalid argument type: script');
248
+ }
249
+ return this;
250
+ };
251
+
252
+ /**
253
+ * Retrieve signatures for the provided PrivateKey.
254
+ *
255
+ * @param {Transaction} transaction - the transaction to be signed
256
+ * @param {PrivateKey} privateKey - the private key to use when signing
257
+ * @param {number} inputIndex - the index of this input in the provided transaction
258
+ * @param {number} sigType - defaults to Signature.SIGHASH_ALL
259
+ * @param {Buffer} addressHash - if provided, don't calculate the hash of the
260
+ * public key associated with the private key provided
261
+ * @param {String} signingMethod "schnorr" or "ecdsa", default to "ecdsa" if not provided
262
+ * @abstract
263
+ */
264
+ Input.prototype.getSignatures = function() {
265
+ throw new errors.AbstractMethodInvoked(
266
+ 'Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported)' +
267
+ ' for input: ' + JSON.stringify(this)
268
+ );
269
+ };
270
+
271
+ Input.prototype.isFullySigned = function() {
272
+ throw new errors.AbstractMethodInvoked('Input#isFullySigned');
273
+ };
274
+
275
+ Input.prototype.isFinal = function() {
276
+ return this.sequenceNumber !== 4294967295;
277
+ };
278
+
279
+ Input.prototype.addSignature = function() {
280
+ throw new errors.AbstractMethodInvoked('Input#addSignature');
281
+ };
282
+
283
+ Input.prototype.clearSignatures = function() {
284
+ throw new errors.AbstractMethodInvoked('Input#clearSignatures');
285
+ };
286
+
287
+ Input.prototype.isValidSignature = function(transaction, signature, signingMethod) {
288
+ // FIXME: Refactor signature so this is not necessary
289
+ signature.signature.nhashtype = signature.sigtype;
290
+ return Sighash.verify(
291
+ transaction,
292
+ signature.signature,
293
+ signature.publicKey,
294
+ signature.inputIndex,
295
+ this.output.script,
296
+ this.output.satoshisBN,
297
+ undefined,
298
+ signingMethod
299
+ );
300
+ };
301
+
302
+ /**
303
+ * @returns true if this is a coinbase input (represents no input)
304
+ */
305
+ Input.prototype.isNull = function() {
306
+ return this.prevTxId.toString('hex') === '0000000000000000000000000000000000000000000000000000000000000000' &&
307
+ this.outputIndex === 0xffffffff;
308
+ };
309
+
310
+ Input.prototype._estimateSize = function() {
311
+ return this.toBufferWriter().toBuffer().length;
312
+ };
313
+
314
+
315
+ /**
316
+ * Sets sequence number so that transaction is not valid until the desired seconds
317
+ * since the transaction is mined
318
+ *
319
+ * @param {Number} time in seconds
320
+ * @return {Transaction} this
321
+ */
322
+ Input.prototype.lockForSeconds = function(seconds) {
323
+ $.checkArgument(_.isNumber(seconds));
324
+ if (seconds < 0 || seconds >= SEQUENCE_LOCKTIME_GRANULARITY * SEQUENCE_LOCKTIME_MASK) {
325
+ throw new errors.Transaction.Input.LockTimeRange();
326
+ }
327
+ seconds = parseInt(Math.floor(seconds / SEQUENCE_LOCKTIME_GRANULARITY));
328
+
329
+ // SEQUENCE_LOCKTIME_DISABLE_FLAG = 1
330
+ this.sequenceNumber = seconds | SEQUENCE_LOCKTIME_TYPE_FLAG;
331
+ return this;
332
+ };
333
+
334
+ /**
335
+ * Sets sequence number so that transaction is not valid until the desired block height differnece since the tx is mined
336
+ *
337
+ * @param {Number} height
338
+ * @return {Transaction} this
339
+ */
340
+ Input.prototype.lockUntilBlockHeight = function(heightDiff) {
341
+ $.checkArgument(_.isNumber(heightDiff));
342
+ if (heightDiff < 0 || heightDiff >= SEQUENCE_BLOCKDIFF_LIMIT) {
343
+ throw new errors.Transaction.Input.BlockHeightOutOfRange();
344
+ }
345
+ // SEQUENCE_LOCKTIME_TYPE_FLAG = 0
346
+ // SEQUENCE_LOCKTIME_DISABLE_FLAG = 0
347
+ this.sequenceNumber = heightDiff;
348
+ return this;
349
+ };
350
+
351
+
352
+ /**
353
+ * Returns a semantic version of the input's sequence nLockTime.
354
+ * @return {Number|Date}
355
+ * If sequence lock is disabled it returns null,
356
+ * if is set to block height lock, returns a block height (number)
357
+ * else it returns a Date object.
358
+ */
359
+ Input.prototype.getLockTime = function() {
360
+ if (this.sequenceNumber & SEQUENCE_LOCKTIME_DISABLE_FLAG) {
361
+ return null;
362
+ }
363
+
364
+ if (this.sequenceNumber & SEQUENCE_LOCKTIME_TYPE_FLAG) {
365
+ var seconds = SEQUENCE_LOCKTIME_GRANULARITY * (this.sequenceNumber & SEQUENCE_LOCKTIME_MASK);
366
+ return seconds;
367
+ } else {
368
+ var blockHeight = this.sequenceNumber & SEQUENCE_LOCKTIME_MASK;
369
+ return blockHeight;
370
+ }
371
+ };
372
+
373
+
374
+
375
+ module.exports = Input;
@@ -0,0 +1,221 @@
1
+ 'use strict';
2
+
3
+ var _ = require('lodash');
4
+ var inherits = require('inherits');
5
+ var Transaction = require('../transaction');
6
+ var Input = require('./input');
7
+ var Output = require('../output');
8
+ var $ = require('../../util/preconditions');
9
+
10
+ var Script = require('../../script');
11
+ var Signature = require('../../crypto/signature');
12
+ var Sighash = require('../sighash');
13
+ var PublicKey = require('../../publickey');
14
+ var BufferUtil = require('../../util/buffer');
15
+ var TransactionSignature = require('../signature');
16
+
17
+ /**
18
+ * @constructor
19
+ */
20
+ function MultiSigInput(input, pubkeys, threshold, signatures, opts) {
21
+ opts = opts || {};
22
+ Input.apply(this, arguments);
23
+ var self = this;
24
+ pubkeys = pubkeys || input.publicKeys;
25
+ threshold = threshold || input.threshold;
26
+ signatures = signatures || input.signatures;
27
+ if (opts.noSorting) {
28
+ this.publicKeys = pubkeys
29
+ } else {
30
+ this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); });
31
+ }
32
+ $.checkState(Script.buildMultisigOut(this.publicKeys, threshold).equals(this.output.script),
33
+ 'Provided public keys don\'t match to the provided output script');
34
+ this.publicKeyIndex = {};
35
+ _.each(this.publicKeys, function(publicKey, index) {
36
+ self.publicKeyIndex[publicKey.toString()] = index;
37
+ });
38
+ this.threshold = threshold;
39
+ // Empty array of signatures
40
+ this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length);
41
+ }
42
+ inherits(MultiSigInput, Input);
43
+
44
+ MultiSigInput.prototype.toObject = function() {
45
+ var obj = Input.prototype.toObject.apply(this, arguments);
46
+ obj.threshold = this.threshold;
47
+ obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); });
48
+ obj.signatures = this._serializeSignatures();
49
+ return obj;
50
+ };
51
+
52
+ MultiSigInput.prototype._deserializeSignatures = function(signatures) {
53
+ return _.map(signatures, function(signature) {
54
+ if (!signature) {
55
+ return undefined;
56
+ }
57
+ return new TransactionSignature(signature);
58
+ });
59
+ };
60
+
61
+ MultiSigInput.prototype._serializeSignatures = function() {
62
+ return _.map(this.signatures, function(signature) {
63
+ if (!signature) {
64
+ return undefined;
65
+ }
66
+ return signature.toObject();
67
+ });
68
+ };
69
+
70
+ MultiSigInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData, signingMethod) {
71
+ $.checkState(this.output instanceof Output);
72
+ sigtype = sigtype || (Signature.SIGHASH_ALL | Signature.SIGHASH_FORKID);
73
+
74
+ var self = this;
75
+ var results = [];
76
+ _.each(this.publicKeys, function(publicKey) {
77
+ if (publicKey.toString() === privateKey.publicKey.toString()) {
78
+ results.push(new TransactionSignature({
79
+ publicKey: privateKey.publicKey,
80
+ prevTxId: self.prevTxId,
81
+ outputIndex: self.outputIndex,
82
+ inputIndex: index,
83
+ signature: Sighash.sign(transaction, privateKey, sigtype, index, self.output.script, self.output.satoshisBN, undefined, signingMethod),
84
+ sigtype: sigtype
85
+ }));
86
+ }
87
+ });
88
+
89
+ return results;
90
+ };
91
+
92
+ MultiSigInput.prototype.addSignature = function(transaction, signature, signingMethod) {
93
+ $.checkState(!this.isFullySigned(), 'All needed signatures have already been added');
94
+ $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]),
95
+ 'Signature has no matching public key');
96
+ $.checkState(this.isValidSignature(transaction, signature, signingMethod));
97
+ this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature;
98
+ this._updateScript(signingMethod);
99
+ return this;
100
+ };
101
+
102
+ MultiSigInput.prototype._updateScript = function(signingMethod) {
103
+ this.setScript(Script.buildMultisigIn(
104
+ this.publicKeys,
105
+ this.threshold,
106
+ this._createSignatures(signingMethod)
107
+ ));
108
+ return this;
109
+ };
110
+
111
+ MultiSigInput.prototype._createSignatures = function(signingMethod) {
112
+ return _.map(
113
+ _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }),
114
+ function(signature) {
115
+ return BufferUtil.concat([
116
+ signature.signature.toDER(signingMethod),
117
+ BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
118
+ ]);
119
+ }
120
+ );
121
+ };
122
+
123
+ MultiSigInput.prototype.clearSignatures = function() {
124
+ this.signatures = new Array(this.publicKeys.length);
125
+ this._updateScript();
126
+ };
127
+
128
+ MultiSigInput.prototype.isFullySigned = function() {
129
+ return this.countSignatures() === this.threshold;
130
+ };
131
+
132
+ MultiSigInput.prototype.countMissingSignatures = function() {
133
+ return this.threshold - this.countSignatures();
134
+ };
135
+
136
+ MultiSigInput.prototype.countSignatures = function() {
137
+ return _.reduce(this.signatures, function(sum, signature) {
138
+ return sum + (!!signature);
139
+ }, 0);
140
+ };
141
+
142
+ MultiSigInput.prototype.publicKeysWithoutSignature = function() {
143
+ var self = this;
144
+ return _.filter(this.publicKeys, function(publicKey) {
145
+ return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]);
146
+ });
147
+ };
148
+
149
+ MultiSigInput.prototype.isValidSignature = function(transaction, signature, signingMethod) {
150
+ // FIXME: Refactor signature so this is not necessary
151
+ signature.signature.nhashtype = signature.sigtype;
152
+ return Sighash.verify(
153
+ transaction,
154
+ signature.signature,
155
+ signature.publicKey,
156
+ signature.inputIndex,
157
+ this.output.script,
158
+ this.output.satoshisBN,
159
+ undefined,
160
+ signingMethod
161
+ );
162
+ };
163
+
164
+ /**
165
+ *
166
+ * @param {Buffer[]} signatures
167
+ * @param {PublicKey[]} publicKeys
168
+ * @param {Transaction} transaction
169
+ * @param {Integer} inputIndex
170
+ * @param {Input} input
171
+ * @returns {TransactionSignature[]}
172
+ */
173
+ MultiSigInput.normalizeSignatures = function(transaction, input, inputIndex, signatures, publicKeys, signingMethod) {
174
+ return publicKeys.map(function (pubKey) {
175
+ var signatureMatch = null;
176
+ signatures = signatures.filter(function (signatureBuffer) {
177
+ if (signatureMatch) {
178
+ return true;
179
+ }
180
+
181
+ var signature = new TransactionSignature({
182
+ signature: Signature.fromTxFormat(signatureBuffer),
183
+ publicKey: pubKey,
184
+ prevTxId: input.prevTxId,
185
+ outputIndex: input.outputIndex,
186
+ inputIndex: inputIndex,
187
+ sigtype: Signature.SIGHASH_ALL
188
+ });
189
+
190
+ signature.signature.nhashtype = signature.sigtype;
191
+ var isMatch = Sighash.verify(
192
+ transaction,
193
+ signature.signature,
194
+ signature.publicKey,
195
+ signature.inputIndex,
196
+ input.output.script,
197
+ undefined,
198
+ signingMethod
199
+ );
200
+
201
+ if (isMatch) {
202
+ signatureMatch = signature;
203
+ return false;
204
+ }
205
+
206
+ return true;
207
+ });
208
+
209
+ return signatureMatch ? signatureMatch : null;
210
+ });
211
+ };
212
+
213
+ MultiSigInput.OPCODES_SIZE = 1; // 0
214
+ MultiSigInput.SIGNATURE_SIZE = 73; // size (1) + DER (<=72)
215
+
216
+ MultiSigInput.prototype._estimateSize = function() {
217
+ return MultiSigInput.OPCODES_SIZE +
218
+ this.threshold * MultiSigInput.SIGNATURE_SIZE;
219
+ };
220
+
221
+ module.exports = MultiSigInput;