bitcore/lib/privkey.js

71 lines
2.1 KiB
JavaScript
Raw Normal View History

2014-08-13 12:23:06 -07:00
var Bn = require('./bn');
2014-08-06 22:47:10 -07:00
var point = require('./point');
var constants = require('./constants');
var base58check = require('./base58check');
var Privkey = function Privkey(bn, network, compressed) {
if (!(this instanceof Privkey))
return new Privkey(bn, network, compressed);
2014-08-13 12:23:06 -07:00
this.bn = bn;
2014-08-06 22:47:10 -07:00
this.network = network;
2014-08-09 19:58:48 -07:00
this.compressed = compressed;
2014-08-06 22:47:10 -07:00
};
2014-08-09 19:58:48 -07:00
Privkey.prototype.validate = function() {
2014-08-13 12:23:06 -07:00
if (!this.bn.lt(point.getN()))
throw new Error('Number must be less than N');
2014-08-09 19:58:48 -07:00
if (typeof constants[this.network] === undefined)
throw new Error('Must specify the network ("mainnet" or "testnet")');
2014-08-09 19:58:48 -07:00
if (typeof this.compressed !== 'boolean')
throw new Error('Must specify whether the corresponding public key is compressed or not (true or false)');
2014-08-06 22:47:10 -07:00
};
Privkey.prototype.toWIF = function() {
var network = this.network;
var compressed = this.compressed;
2014-08-07 21:31:36 -07:00
if (typeof this.network === 'undefined')
network = 'mainnet';
if (typeof this.compressed === 'undefined')
compressed = true;
2014-08-13 12:23:06 -07:00
var privbuf = this.bn.toBuffer({size: 32});
2014-08-06 22:47:10 -07:00
var buf;
if (compressed)
2014-08-13 12:23:06 -07:00
buf = Buffer.concat([new Buffer([constants[network].privkey]), this.bn.toBuffer({size: 32}), new Buffer([0x01])]);
2014-08-06 22:47:10 -07:00
else
2014-08-13 12:23:06 -07:00
buf = Buffer.concat([new Buffer([constants[network].privkey]), this.bn.toBuffer({size: 32})]);
2014-08-06 22:47:10 -07:00
return base58check.encode(buf);
};
Privkey.prototype.fromWIF = function(str) {
var buf = base58check.decode(str);
if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] == 1)
this.compressed = true;
else if (buf.length === 1 + 32)
this.compressed = false;
else
throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)');
2014-08-06 22:47:10 -07:00
if (buf[0] === constants.mainnet.privkey)
this.network = 'mainnet';
else if (buf[0] === constants.testnet.privkey)
this.network = 'testnet';
else
throw new Error('Invalid network');
2014-08-06 22:47:10 -07:00
2014-08-13 12:23:06 -07:00
this.bn = Bn.fromBuffer(buf.slice(1, 32 + 1));
2014-08-06 22:47:10 -07:00
};
Privkey.prototype.toString = function() {
return this.toWIF();
};
Privkey.prototype.fromString = function(str) {
this.fromWIF(str);
};
module.exports = Privkey;