1 | 'use strict';
|
2 |
|
3 | var _ = require('lodash');
|
4 | var $ = require('../util/preconditions');
|
5 | var JSUtil = require('../util/js');
|
6 |
|
7 | var Script = require('../script');
|
8 | var Address = require('../address');
|
9 | var Unit = require('../unit');
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | function UnspentOutput(data) {
|
28 |
|
29 |
|
30 | if (!(this instanceof UnspentOutput)) {
|
31 | return new UnspentOutput(data);
|
32 | }
|
33 | $.checkArgument(_.isObject(data), 'Must provide an object from where to extract data');
|
34 | var address = data.address ? new Address(data.address) : undefined;
|
35 | var txId = data.txid ? data.txid : data.txId;
|
36 | if (!txId || !JSUtil.isHexaString(txId) || txId.length > 64) {
|
37 |
|
38 | throw new Error('Invalid TXID in object', data);
|
39 | }
|
40 | var outputIndex = _.isUndefined(data.vout) ? data.outputIndex : data.vout;
|
41 | if (!_.isNumber(outputIndex)) {
|
42 | throw new Error('Invalid outputIndex, received ' + outputIndex);
|
43 | }
|
44 | $.checkArgument(!_.isUndefined(data.scriptPubKey) || !_.isUndefined(data.script),
|
45 | 'Must provide the scriptPubKey for that output!');
|
46 | var script = new Script(data.scriptPubKey || data.script);
|
47 | $.checkArgument(!_.isUndefined(data.amount) || !_.isUndefined(data.satoshis),
|
48 | 'Must provide an amount for the output');
|
49 | var amount = !_.isUndefined(data.amount) ? new Unit.fromBTC(data.amount).toSatoshis() : data.satoshis;
|
50 | $.checkArgument(_.isNumber(amount), 'Amount must be a number');
|
51 | JSUtil.defineImmutable(this, {
|
52 | address: address,
|
53 | txId: txId,
|
54 | outputIndex: outputIndex,
|
55 | script: script,
|
56 | satoshis: amount
|
57 | });
|
58 | }
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 | UnspentOutput.prototype.inspect = function() {
|
65 | return '<UnspentOutput: ' + this.txId + ':' + this.outputIndex +
|
66 | ', satoshis: ' + this.satoshis + ', address: ' + this.address + '>';
|
67 | };
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 | UnspentOutput.prototype.toString = function() {
|
74 | return this.txId + ':' + this.outputIndex;
|
75 | };
|
76 |
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 | UnspentOutput.fromObject = function(data) {
|
83 | return new UnspentOutput(data);
|
84 | };
|
85 |
|
86 |
|
87 |
|
88 |
|
89 |
|
90 | UnspentOutput.prototype.toObject = UnspentOutput.prototype.toJSON = function toObject() {
|
91 | return {
|
92 | address: this.address ? this.address.toString() : undefined,
|
93 | txid: this.txId,
|
94 | vout: this.outputIndex,
|
95 | scriptPubKey: this.script.toBuffer().toString('hex'),
|
96 | amount: Unit.fromSatoshis(this.satoshis).toBTC()
|
97 | };
|
98 | };
|
99 |
|
100 | module.exports = UnspentOutput;
|