Refactoring

This commit is contained in:
Kagami Hiiragi 2015-01-12 20:50:21 +03:00
parent 3aea60e875
commit e723993d1c
2 changed files with 16 additions and 38 deletions

View File

@ -14,13 +14,14 @@ var EC = require("elliptic").ec;
var ec = new EC("secp256k1");
exports.getPublic = function(privateKey) {
// `elliptic` doesn't have such checkings so we do it by ourself. We
// should always ensure that library user doesn't try to do something
// dumb.
if (privateKey.length !== 32) {
throw new Error("Bad private key");
function assert(condition, message) {
if (!condition) {
throw new Error(message || "Assertion failed");
}
}
exports.getPublic = function(privateKey) {
assert(privateKey.length === 32, "Bad private key");
// XXX(Kagami): `elliptic.utils.encode` returns array for every
// encoding except `hex`.
return new Buffer(ec.keyPair(privateKey).getPublic("arr"));
@ -28,20 +29,14 @@ exports.getPublic = function(privateKey) {
exports.sign = function(privateKey, msg) {
var key = ec.keyPair(privateKey);
var sig;
try {
sig = new Buffer(key.sign(msg).toDER());
return Promise.resolve(sig);
} catch(e) {
return Promise.reject();
}
return new Promise(function(resolve) {
resolve(new Buffer(key.sign(msg).toDER()));
});
};
exports.verify = function(key, msg, sig) {
key = ec.keyPair(key);
if (key.verify(msg, sig)) {
return Promise.resolve();
} else {
return Promise.reject();
}
return new Promise(function(resolve, reject) {
return key.verify(msg, sig) ? resolve() : reject();
});
};

View File

@ -25,20 +25,9 @@ var getPublic = exports.getPublic = secp256k1.createPublicKey;
* @return {Promise.<Buffer>} A promise that resolves with the
* signature and rejects on bad key or message.
*/
// FIXME(Kagami): What to do in case of invalid nonce?
exports.sign = function(privateKey, msg) {
return new promise(function(resolve, reject) {
try {
secp256k1.sign(privateKey, msg, function(code, sig) {
if (code === 1) {
resolve(sig);
} else {
reject();
}
});
} catch(e) {
reject();
}
return new promise(function(resolve) {
resolve(secp256k1.sign(privateKey, msg));
});
};
@ -53,12 +42,6 @@ exports.sign = function(privateKey, msg) {
exports.verify = function(key, msg, sig) {
var publicKey = key.length === 32 ? getPublic(key) : key;
return new promise(function(resolve, reject) {
secp256k1.verify(publicKey, msg, sig, function(code) {
if (code === 1) {
resolve();
} else {
reject();
}
});
return secp256k1.verify(publicKey, msg, sig) === 1 ? resolve() : reject();
});
};