bitcore-lib-zcash/lib/transaction/unspentoutput.js

73 lines
2.3 KiB
JavaScript
Raw Normal View History

2014-12-30 17:12:24 -08:00
'use strict';
var _ = require('lodash');
var $ = require('../util/preconditions');
var JSUtil = require('../util/js');
2014-12-30 17:12:24 -08:00
var Script = require('../script');
var Address = require('../address');
var Unit = require('../unit');
2014-12-30 17:12:24 -08:00
function UnspentOutput(data) {
2014-12-30 17:12:24 -08:00
/* jshint maxcomplexity: 20 */
/* jshint maxstatements: 20 */
if (!(this instanceof UnspentOutput)) {
return new UnspentOutput(data);
2014-12-30 17:12:24 -08:00
}
$.checkArgument(_.isObject(data), 'Must provide an object from where to extract data');
var address = data.address ? new Address(data.address) : undefined;
var txId = data.txid ? data.txid : data.txId;
if (!txId || !JSUtil.isHexaString(txId) || txId.length > 64) {
// TODO: Use the errors library
throw new Error('Invalid TXID in object', data);
}
var outputIndex = _.isUndefined(data.vout) ? data.outputIndex : data.vout;
if (!_.isNumber(outputIndex)) {
throw new Error('Invalid outputIndex, received ' + outputIndex);
}
$.checkArgument(data.scriptPubKey || data.script, 'Must provide the scriptPubKey for that output!');
var script = new Script(data.scriptPubKey || data.script);
$.checkArgument(data.amount || data.satoshis, 'Must provide the scriptPubKey for that output!');
var amount = data.amount ? new Unit.fromBTC(data.amount).toSatoshis() : data.satoshis;
$.checkArgument(_.isNumber(amount), 'Amount must be a number');
JSUtil.defineImmutable(this, {
address: address,
txId: txId,
outputIndex: outputIndex,
script: script,
satoshis: amount
});
}
UnspentOutput.prototype.inspect = function() {
return '<UnspentOutput: ' + this.txId + ':' + this.outputIndex +
2014-12-30 17:12:24 -08:00
', satoshis: ' + this.satoshis + ', address: ' + this.address + '>';
};
UnspentOutput.prototype.toString = function() {
2014-12-30 17:12:24 -08:00
return this.txId + ':' + this.outputIndex;
};
UnspentOutput.fromJSON = UnspentOutput.fromObject = function(data) {
2014-12-30 20:21:59 -08:00
if (JSUtil.isValidJSON(data)) {
2014-12-30 17:12:24 -08:00
data = JSON.parse(data);
}
return new UnspentOutput(data);
2014-12-30 17:12:24 -08:00
};
UnspentOutput.prototype.toJSON = function() {
2014-12-30 17:12:24 -08:00
return JSON.stringify(this.toObject());
};
UnspentOutput.prototype.toObject = function() {
2014-12-30 17:12:24 -08:00
return {
2014-12-30 20:21:59 -08:00
address: this.address.toString(),
2014-12-30 17:12:24 -08:00
txid: this.txId,
vout: this.outputIndex,
2014-12-30 20:21:59 -08:00
scriptPubKey: this.script.toBuffer().toString('hex'),
2014-12-30 17:12:24 -08:00
amount: Unit.fromSatoshis(this.satoshis).toBTC()
};
};
module.exports = UnspentOutput;