bitcore/lib/keypair.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2014-11-20 07:52:32 -08:00
'use strict';
2014-08-07 21:31:36 -07:00
var Privkey = require('./privkey');
var Pubkey = require('./pubkey');
2014-10-02 12:08:44 -07:00
var Keypair = function Keypair(obj) {
if (!(this instanceof Keypair))
return new Keypair(obj);
2014-10-06 14:54:20 -07:00
// breaks some tests
// TODO: allow keys to be created with simply `new Keypair()` (random gen.)
/*if (!obj) {
2014-10-02 12:08:44 -07:00
var privkey = Privkey().fromRandom();
var obj = this.fromPrivkey( privkey );
2014-10-06 14:54:20 -07:00
}*/
2014-10-02 12:08:44 -07:00
2014-08-28 16:18:36 -07:00
if (obj)
this.set(obj);
};
Keypair.prototype.set = function(obj) {
2014-08-28 16:18:36 -07:00
this.privkey = obj.privkey || this.privkey || undefined;
2014-10-02 12:08:44 -07:00
this.pubkey = obj.pubkey || this.pubkey || undefined;
2014-08-28 16:18:36 -07:00
return this;
2014-08-07 21:31:36 -07:00
};
Keypair.prototype.fromJSON = function(json) {
if (json.privkey)
this.set({privkey: Privkey().fromJSON(json.privkey)});
if (json.pubkey)
this.set({pubkey: Pubkey().fromJSON(json.pubkey)});
return this;
};
Keypair.prototype.toJSON = function() {
var json = {};
if (this.privkey)
json.privkey = this.privkey.toJSON();
if (this.pubkey)
json.pubkey = this.pubkey.toJSON();
return json;
};
Keypair.prototype.fromPrivkey = function(privkey) {
2014-08-29 12:43:55 -07:00
this.privkey = privkey;
this.privkey2pubkey();
return this;
};
Keypair.prototype.fromRandom = function() {
2014-08-28 19:27:22 -07:00
this.privkey = Privkey().fromRandom();
2014-08-09 17:43:24 -07:00
this.privkey2pubkey();
return this;
2014-08-07 21:31:36 -07:00
};
Keypair.prototype.fromString = function(str) {
2014-08-07 21:31:36 -07:00
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
}
};
Keypair.prototype.privkey2pubkey = function() {
2014-08-28 20:19:30 -07:00
this.pubkey = Pubkey().fromPrivkey(this.privkey);
2014-08-07 21:31:36 -07:00
};
Keypair.prototype.toString = function() {
2014-08-07 21:31:36 -07:00
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 = Keypair;