Add fromBuffer and toBuffer to PrivateKey

This commit is contained in:
Esteban Ordano 2015-01-27 13:35:10 -03:00
parent 2c00c87198
commit 0bae82fdf4
2 changed files with 45 additions and 8 deletions

View File

@ -152,12 +152,8 @@ PrivateKey._transformBuffer = function(buf, network) {
var info = {};
if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] === 1) {
info.compressed = true;
} else if (buf.length === 1 + 32) {
info.compressed = false;
} else {
throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)');
if (buf.length === 32) {
return PrivateKey._transformBNBuffer(buf, network);
}
info.network = Networks.get(buf[0], 'privatekey');
@ -173,10 +169,33 @@ PrivateKey._transformBuffer = function(buf, network) {
throw new TypeError('Private key network mismatch');
}
if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] === 1) {
info.compressed = true;
} else if (buf.length === 1 + 32) {
info.compressed = false;
} else {
throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)');
}
info.bn = BN.fromBuffer(buf.slice(1, 32 + 1));
return info;
};
/**
* Internal function to transform a BN buffer into a private key
*
* @param {Buffer} buf
* @param {Network|string} [network] - a {@link Network} object, or a string with the network name
* @returns {object} an Object with keys: bn, network, and compressed
* @private
*/
PrivateKey._transformBNBuffer = function(buf, network) {
var info = {};
info.network = Networks.get(network) || Networks.defaultNetwork;
info.bn = BN.fromBuffer(buf);
info.compressed = false;
return info;
};
/**
@ -204,9 +223,20 @@ PrivateKey.fromJSON = function(json) {
return new PrivateKey(json);
};
/**
* Instantiate a PrivateKey from a Buffer with the DER or WIF representation
*
* @param {Buffer} arg
* @param {Network} network
* @return {PrivateKey}
*/
PrivateKey.fromBuffer = function(arg, network) {
return new PrivateKey(arg, network);
};
/**
* Internal function to transform a JSON string on plain object into a private key
* return this.
*
* @param {String} json - A JSON string or plain object
* @returns {Object} An object with keys: bn, network and compressed

View File

@ -268,11 +268,18 @@ describe('PrivateKey', function() {
});
describe('#toBuffer', function() {
it('should output known buffer', function() {
describe('buffer serialization', function() {
it('returns an expected value when creating a PrivateKey from a buffer', function() {
var privkey = new PrivateKey(BN.fromBuffer(buf), 'livenet');
privkey.toString().should.equal(buf.toString('hex'));
});
it('roundtrips correctly when using toBuffer/fromBuffer', function() {
var privkey = new PrivateKey(BN.fromBuffer(buf));
var toBuffer = new PrivateKey(privkey.toBuffer());
var fromBuffer = PrivateKey.fromBuffer(toBuffer.toBuffer());
fromBuffer.toString().should.equal(privkey.toString());
});
});
describe('#toBigNumber', function() {