You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.3 KiB

var Address = require('../lib/address');
11 years ago
var Privkey = require('./privkey');
var Pubkey = require('./pubkey');
var Random = require('./random');
var Bn = require('./bn');
11 years ago
var point = require('./point');
var Key = function Key(privkey, pubkey) {
if (!(this instanceof Key))
return new Key(privkey, pubkey);
11 years ago
this.privkey = privkey;
this.pubkey = pubkey;
11 years ago
};
Key.prototype.fromRandom = function() {
do {
var privbuf = Random.getRandomBuffer(32);
this.privkey = new Privkey(Bn(privbuf));
var condition = this.privkey.bn.lt(point.getN());
11 years ago
} while (!condition);
11 years ago
this.privkey2pubkey();
return this;
11 years ago
};
Key.prototype.fromString = function(str) {
var obj = JSON.parse(str);
if (obj.privkey) {
11 years ago
this.privkey = new Privkey();
this.privkey.fromString(obj.privkey);
11 years ago
}
if (obj.pubkey) {
11 years ago
this.pubkey = new Pubkey();
this.pubkey.fromString(obj.pubkey);
11 years ago
}
};
Key.prototype.getAddress = function(network) {
return Address().fromPubkey(this.pubkey, network);
};
11 years ago
Key.prototype.privkey2pubkey = function() {
this.pubkey = new Pubkey(point.getG().mul(this.privkey.bn), this.privkey.compressed);
11 years ago
};
Key.prototype.toString = function() {
var obj = {};
11 years ago
if (this.privkey)
obj.privkey = this.privkey.toString();
11 years ago
if (this.pubkey)
obj.pubkey = this.pubkey.toString();
11 years ago
return JSON.stringify(obj);
};
module.exports = Key;