Merge pull request #103 from dcousens/ecdsatests

ECDSA Tests and Public key recovery
This commit is contained in:
Wei Lu 2014-03-29 19:21:29 +08:00
commit fab8921f16
3 changed files with 32 additions and 15 deletions

View file

@ -272,10 +272,7 @@ var ECDSA = {
throw new Error("Pubkey recovery unsuccessful");
}
// TODO (shtylman) this is stupid because this file and eckey
// have circular dependencies
var ECPubKey = require('./eckey').ECPubKey;
return ECPubKey(Q);
return Q
},
/**
@ -289,20 +286,17 @@ var ECDSA = {
* This function simply tries all four cases and returns the value
* that resulted in a successful pubkey recovery.
*/
calcPubkeyRecoveryParam: function (origPubkey, r, s, hash)
{
var address = origPubkey.getAddress().toString();
calcPubKeyRecoveryParam: function (origPubKey, r, s, hash) {
for (var i = 0; i < 4; i++) {
var pubkey = ECDSA.recoverPubKey(r, s, hash, i);
pubkey.compressed = origPubkey.compressed;
if (pubkey.getAddress().toString() == address) {
return i;
var pubKey = ECDSA.recoverPubKey(r, s, hash, i)
if (pubKey.equals(origPubKey)) {
return i
}
}
throw new Error("Unable to find valid recovery factor");
throw new Error("Unable to find valid recovery factor")
}
};
module.exports = ECDSA;

View file

@ -3,6 +3,7 @@
var Address = require('./address')
var convert = require('./convert')
var ecdsa = require('./ecdsa')
var ECPubKey = require('./eckey').ECPubKey
var SHA256 = require('crypto-js/sha256')
var Message = {}
@ -31,7 +32,8 @@ Message.signMessage = function (key, message) {
var hash = Message.getHash(message)
var sig = key.sign(hash)
var obj = ecdsa.parseSig(sig)
var i = ecdsa.calcPubkeyRecoveryParam(key, obj.r, obj.s, hash)
var i = ecdsa.calcPubKeyRecoveryParam(key.getPub().pub, obj.r, obj.s, hash)
i += 27
if (key.compressed) {
@ -56,7 +58,7 @@ Message.verifyMessage = function (address, sig, message) {
var hash = Message.getHash(message)
var isCompressed = !!(sig.i & 4)
var pubKey = ecdsa.recoverPubKey(sig.r, sig.s, hash, sig.i)
var pubKey = new ECPubKey(ecdsa.recoverPubKey(sig.r, sig.s, hash, sig.i))
pubKey.compressed = isCompressed
// Compare address to expected address

21
test/ecdsa.js Normal file
View file

@ -0,0 +1,21 @@
var assert = require('assert')
var convert = require('../').convert
var ecdsa = require('../').ecdsa
var ECPubKey = require('../').ECPubKey
var Message = require('../').Message
describe('ecdsa', function() {
describe('recoverPubKey', function() {
it('succesfully recovers a public key', function() {
var addr = 'mgQK8S6CfSXKjPmnujArSmVxafeJfrZsa3'
var signature = convert.base64ToBytes('H0PG6+PUo96UPTJ/DVj8aBU5it+Nuli4YdsLuTMvfJxoHH9Jb7jYTQXCCOX2jrTChD5S1ic3vCrUQHdmB5/sEQY=')
var sighex = convert.bytesToHex(signature)
var hash = Message.getHash('1111')
var obj = ecdsa.parseSigCompact(signature)
var pubKey = new ECPubKey(ecdsa.recoverPubKey(obj.r, obj.s, hash, obj.i))
assert.equal(pubKey.toHex(true), '02e8fcf4d749b35879bc1f3b14b49e67ab7301da3558c5a9b74a54f1e6339c334c')
})
})
})