bitcore-lib-zcash/lib/key.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

2014-08-13 15:00:41 -07:00
var Address = require('../lib/address');
2014-08-07 21:31:36 -07:00
var Privkey = require('./privkey');
var Pubkey = require('./pubkey');
var Random = require('./random');
2014-08-13 12:23:06 -07:00
var Bn = require('./bn');
2014-08-07 21:31:36 -07:00
var point = require('./point');
var Key = function Key(privkey, pubkey) {
if (!(this instanceof Key))
return new Key(privkey, pubkey);
2014-08-09 17:43:24 -07:00
this.privkey = privkey;
this.pubkey = pubkey;
2014-08-07 21:31:36 -07:00
};
Key.prototype.fromRandom = function() {
do {
var privbuf = Random.getRandomBuffer(32);
2014-08-13 12:23:06 -07:00
this.privkey = new Privkey(Bn(privbuf));
var condition = this.privkey.bn.lt(point.getN());
2014-08-07 21:31:36 -07:00
} while (!condition);
2014-08-09 17:43:24 -07:00
this.privkey2pubkey();
return this;
2014-08-07 21:31:36 -07:00
};
Key.prototype.fromString = function(str) {
var obj = JSON.parse(str);
2014-08-13 12:23:06 -07:00
if (obj.privkey) {
2014-08-09 17:43:24 -07:00
this.privkey = new Privkey();
2014-08-13 12:23:06 -07:00
this.privkey.fromString(obj.privkey);
2014-08-07 21:31:36 -07:00
}
2014-08-13 12:23:06 -07:00
if (obj.pubkey) {
2014-08-09 17:43:24 -07:00
this.pubkey = new Pubkey();
2014-08-13 12:23:06 -07:00
this.pubkey.fromString(obj.pubkey);
2014-08-07 21:31:36 -07:00
}
};
2014-08-13 15:00:41 -07:00
Key.prototype.getAddress = function(network, compressed) {
return (new Address()).fromPubkey(this.pubkey, network, compressed);
};
2014-08-09 17:43:24 -07:00
Key.prototype.privkey2pubkey = function() {
2014-08-13 12:23:06 -07:00
this.pubkey = new Pubkey(point.getG().mul(this.privkey.bn));
2014-08-07 21:31:36 -07:00
};
Key.prototype.toString = function() {
var obj = {};
2014-08-09 17:43:24 -07:00
if (this.privkey)
2014-08-13 12:23:06 -07:00
obj.privkey = this.privkey.toString();
2014-08-09 17:43:24 -07:00
if (this.pubkey)
2014-08-13 12:23:06 -07:00
obj.pubkey = this.pubkey.toString();
2014-08-07 21:31:36 -07:00
return JSON.stringify(obj);
};
module.exports = Key;