bitcore-lib-zcash/lib/SIN.js

85 lines
2.2 KiB
JavaScript
Raw Normal View History

2014-07-23 14:53:57 -07:00
'use strict';
2014-07-10 07:46:44 -07:00
var VersionedData = require('../util/VersionedData');
2014-07-10 11:55:32 -07:00
var EncodedData = require('../util/EncodedData');
var util = require('util');
2014-07-23 14:53:57 -07:00
var coinUtil = require('../util');
2013-08-16 19:22:50 -07:00
function SIN(type, payload) {
if (typeof type != 'number') {
SIN.super_.call(this, type, payload);
return;
}
2014-07-24 12:47:50 -07:00
if (!Buffer.isBuffer(payload) || payload.length != 20)
2014-07-23 21:40:13 -07:00
throw new Error('Payload must be 20 bytes');
this.data = new Buffer(1 + 1 + payload.length);
this.converters = this.encodings['binary'].converters;
this._encoding = this.encodings['binary']._encoding;
this.encoding('binary');
this.prefix(0x0F); // SIN magic number, in numberspace
this.type(type);
this.payload(payload);
};
2014-07-10 07:46:44 -07:00
2014-07-10 11:55:32 -07:00
util.inherits(SIN, VersionedData);
EncodedData.applyEncodingsTo(SIN);
SIN.SIN_PERSIST_MAINNET = 0x01; // associated with sacrifice TX
SIN.SIN_PERSIST_TESTNET = 0x11; // associated with sacrifice TX
SIN.SIN_EPHEM = 0x02; // generate off-net at any time
// get or set the prefix data (the first byte of the address)
SIN.prototype.prefix = function(num) {
if (num || (num === 0)) {
this.doAsBinary(function() {
this.data.writeUInt8(num, 0);
});
return num;
}
return this.as('binary').readUInt8(0);
};
2013-08-16 19:22:50 -07:00
// get or set the SIN-type data (the second byte of the address)
SIN.prototype.type = function(num) {
if (num || (num === 0)) {
this.doAsBinary(function() {
this.data.writeUInt8(num, 1);
});
return num;
}
return this.as('binary').readUInt8(1);
};
2013-08-16 19:22:50 -07:00
// get or set the payload data (as a Buffer object)
SIN.prototype.payload = function(data) {
if (data) {
this.doAsBinary(function() {
data.copy(this.data, 2);
});
return data;
}
return this.as('binary').slice(1);
};
2013-08-16 19:22:50 -07:00
SIN.prototype.validate = function() {
this.doAsBinary(function() {
2014-07-10 13:17:24 -07:00
SIN.super_.prototype.validate.call(this);
if (this.data.length != 22) throw new Error('invalid data length');
});
2013-08-16 19:22:50 -07:00
};
2014-07-23 14:53:57 -07:00
// create a SIN from a public key
SIN.fromPubKey = function(pubKey, type) {
if (!type)
type = SIN.SIN_EPHEM;
2014-07-23 15:49:42 -07:00
if (!Buffer.isBuffer(pubKey) || (pubKey.length !== 33 && pubKey.length != 65))
throw new Error('Invalid public key');
2014-07-23 14:53:57 -07:00
var hash = coinUtil.sha256ripe160(pubKey);
return new SIN(hash, type);
};
module.exports = SIN;