Add PrivateKey, Key classes. Update test to enc/dec private key test vectors.

This commit is contained in:
Jeff Garzik 2013-07-10 20:07:14 -04:00
parent c2f40f40ce
commit bf1e16b0da
3 changed files with 66 additions and 4 deletions

3
Key.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = require('bindings')('KeyModule');

23
PrivateKey.js Normal file
View File

@ -0,0 +1,23 @@
require('classtool');
function ClassSpec(b) {
var superclass = b.superclass || require('./util/VersionedData').class();
function PrivateKey() {
PrivateKey.super(this, arguments);
};
PrivateKey.superclass = superclass;
superclass.applyEncodingsTo(PrivateKey);
PrivateKey.prototype.validate = function() {
this.doAsBinary(function() {
PrivateKey.super(this, 'validate', arguments);
if (this.data.length < 32 || this.data.length > 33)
throw new Error('invalid data length');
});
};
return PrivateKey;
};
module.defineClass(ClassSpec);

View File

@ -2,12 +2,32 @@ var assert = require('assert');
var fs = require('fs');
var Address = require('../Address').class();
var PrivateKey = require('../PrivateKey').class();
var networks = require('../networks');
var KeyModule = require('../Key');
suite('basic');
function test_encode_priv(b58, payload, isTestnet)
function test_encode_priv(b58, payload, isTestnet, isCompressed)
{
var network = isTestnet ? networks.testnet : networks.livenet;
var version = network.keySecret;
var buf_pl = new Buffer(payload, 'hex');
var buf;
if (isCompressed) {
buf = new Buffer(buf_pl.length + 1);
buf_pl.copy(buf);
buf[buf_pl.length] = 1;
} else
buf = buf_pl;
var key = new KeyModule.Key();
key.private = buf;
key.compressed = isCompressed;
var privkey = new PrivateKey(version, buf);
assert.equal(privkey.toString(), b58);
}
function test_encode_pub(b58, payload, isTestnet, addrType)
@ -20,8 +40,23 @@ function test_encode_pub(b58, payload, isTestnet, addrType)
assert.equal(addr.toString(), b58);
}
function test_decode_priv(b58, payload, isTestnet)
function test_decode_priv(b58, payload, isTestnet, isCompressed)
{
var network = isTestnet ? networks.testnet : networks.livenet;
var version = network.keySecret;
var buf_pl = new Buffer(payload, 'hex');
var buf;
if (isCompressed) {
buf = new Buffer(buf_pl.length + 1);
buf_pl.copy(buf);
buf[buf_pl.length] = 1;
} else
buf = buf_pl;
var privkey = new PrivateKey(b58);
assert.equal(version, privkey.version());
assert.equal(buf.toString(), privkey.payload().toString());
}
function test_decode_pub(b58, payload, isTestnet, addrType)
@ -45,8 +80,9 @@ function is_valid(datum)
var isTestnet = obj['isTestnet'];
if (isPrivkey) {
test_encode_priv(b58, payload, isTestnet);
test_decode_priv(b58, payload, isTestnet);
var isCompressed = obj['isCompressed'];
test_encode_priv(b58, payload, isTestnet, isCompressed);
test_decode_priv(b58, payload, isTestnet, isCompressed);
} else {
var addrType = obj['addrType'];
test_encode_pub(b58, payload, isTestnet, addrType);