bitcoinjs-lib/src/ecdsa.js

317 lines
8.1 KiB
JavaScript
Raw Normal View History

var assert = require('assert')
var crypto = require('crypto')
2014-04-21 18:19:30 +02:00
var sec = require('./sec')
2014-03-31 05:47:47 +02:00
var ecparams = sec("secp256k1")
2014-04-21 18:19:30 +02:00
var BigInteger = require('./bigi')
var ECPointFp = require('./ec').ECPointFp
2014-03-31 05:47:47 +02:00
var P_OVER_FOUR = null
2011-05-04 18:02:56 +02:00
2014-03-31 05:47:47 +02:00
function implShamirsTrick(P, k, Q, l) {
var m = Math.max(k.bitLength(), l.bitLength())
var Z = P.add2D(Q)
var R = P.curve.getInfinity()
2011-05-04 18:02:56 +02:00
for (var i = m - 1; i >= 0; --i) {
2014-03-31 05:47:47 +02:00
R = R.twice2D()
2011-05-04 18:02:56 +02:00
2014-03-31 05:47:47 +02:00
R.z = BigInteger.ONE
2012-01-11 02:40:45 +01:00
if (k.testBit(i)) {
if (l.testBit(i)) {
2014-03-31 05:47:47 +02:00
R = R.add2D(Z)
} else {
2014-03-31 05:47:47 +02:00
R = R.add2D(P)
}
2012-01-11 02:40:45 +01:00
} else {
if (l.testBit(i)) {
2014-03-31 05:47:47 +02:00
R = R.add2D(Q)
}
2012-01-11 02:40:45 +01:00
}
}
2014-03-31 05:47:47 +02:00
return R
}
2011-05-04 18:02:56 +02:00
2014-04-08 19:58:55 +02:00
var ecdsa = {
deterministicGenerateK: function(hash, D) {
function HmacSHA256(buffer, secret) {
return crypto.createHmac('sha256', secret).update(buffer).digest()
}
2014-04-25 18:37:48 +02:00
assert(Buffer.isBuffer(hash), 'Hash must be a Buffer')
assert.equal(hash.length, 32, 'Hash must be 256 bit')
assert(D instanceof BigInteger, 'Private key must be a BigInteger')
var x = D.toBuffer(32)
var k = new Buffer(32)
var v = new Buffer(32)
k.fill(0)
v.fill(1)
k = HmacSHA256(Buffer.concat([v, new Buffer([0]), x, hash]), k)
v = HmacSHA256(v, k)
k = HmacSHA256(Buffer.concat([v, new Buffer([1]), x, hash]), k)
v = HmacSHA256(v, k)
v = HmacSHA256(v, k)
2014-04-25 18:37:48 +02:00
var n = ecparams.getN()
var kB = BigInteger.fromBuffer(v).mod(n)
assert(kB.compareTo(BigInteger.ONE) > 0, 'Invalid k value')
assert(kB.compareTo(ecparams.getN()) < 0, 'Invalid k value')
2014-04-25 18:37:48 +02:00
return kB
},
sign: function (hash, D) {
var k = ecdsa.deterministicGenerateK(hash, D)
var n = ecparams.getN()
2014-03-31 05:47:47 +02:00
var G = ecparams.getG()
var Q = G.multiply(k)
var e = BigInteger.fromBuffer(hash)
2014-03-31 05:47:47 +02:00
var r = Q.getX().toBigInteger().mod(n)
2014-04-25 18:37:48 +02:00
assert.notEqual(r.signum(), 0, 'Invalid R value')
var s = k.modInverse(n).multiply(e.add(D.multiply(r))).mod(n)
2014-04-25 18:37:48 +02:00
assert.notEqual(s.signum(), 0, 'Invalid S value')
var N_OVER_TWO = n.divide(BigInteger.valueOf(2))
// Make 's' value 'low' as per bip62
if (s.compareTo(N_OVER_TWO) > 0) {
s = n.subtract(s)
2014-04-17 06:05:41 +02:00
}
2014-04-08 19:58:55 +02:00
return ecdsa.serializeSig(r, s)
},
verify: function (hash, sig, pubkey) {
2014-03-31 05:47:47 +02:00
var r,s
2014-04-16 20:13:51 +02:00
if (Array.isArray(sig) || Buffer.isBuffer(sig)) {
2014-04-08 19:58:55 +02:00
var obj = ecdsa.parseSig(sig)
2014-03-31 05:47:47 +02:00
r = obj.r
s = obj.s
} else if ("object" === typeof sig && sig.r && sig.s) {
2014-03-31 05:47:47 +02:00
r = sig.r
s = sig.s
} else {
2014-03-31 05:47:47 +02:00
throw new Error("Invalid value for signature")
2012-01-11 02:40:45 +01:00
}
2011-05-04 18:02:56 +02:00
2014-03-31 05:47:47 +02:00
var Q
if (pubkey instanceof ECPointFp) {
2014-03-31 05:47:47 +02:00
Q = pubkey
2014-04-16 20:13:51 +02:00
} else if (Array.isArray(pubkey) || Buffer.isBuffer(pubkey)) {
2014-03-31 05:47:47 +02:00
Q = ECPointFp.decodeFrom(ecparams.getCurve(), pubkey)
} else {
2014-03-31 05:47:47 +02:00
throw new Error("Invalid format for pubkey value, must be byte array or ECPointFp")
}
2014-04-21 18:19:30 +02:00
var e = BigInteger.fromBuffer(hash)
2014-04-08 19:58:55 +02:00
return ecdsa.verifyRaw(e, r, s, Q)
},
verifyRaw: function (e, r, s, Q) {
2014-03-31 05:47:47 +02:00
var n = ecparams.getN()
var G = ecparams.getG()
2014-03-31 05:47:47 +02:00
if (r.compareTo(BigInteger.ONE) < 0 || r.compareTo(n) >= 0) {
return false
}
2014-03-31 05:47:47 +02:00
if (s.compareTo(BigInteger.ONE) < 0 || s.compareTo(n) >= 0) {
return false
}
2014-03-31 05:47:47 +02:00
var c = s.modInverse(n)
2014-03-31 05:47:47 +02:00
var u1 = e.multiply(c).mod(n)
var u2 = r.multiply(c).mod(n)
// TODO(!!!): For some reason Shamir's trick isn't working with
// signed message verification!? Probably an implementation
// error!
2014-03-31 05:47:47 +02:00
//var point = implShamirsTrick(G, u1, Q, u2)
var point = G.multiply(u1).add(Q.multiply(u2))
2014-03-31 05:47:47 +02:00
var v = point.getX().toBigInteger().mod(n)
2014-03-31 05:47:47 +02:00
return v.equals(r)
},
/**
* Serialize a signature into DER format.
*
* Takes two BigIntegers representing r and s and returns a byte array.
*/
serializeSig: function (r, s) {
2014-03-31 05:47:47 +02:00
var rBa = r.toByteArraySigned()
var sBa = s.toByteArraySigned()
2014-03-31 05:47:47 +02:00
var sequence = []
sequence.push(0x02); // INTEGER
2014-03-31 05:47:47 +02:00
sequence.push(rBa.length)
sequence = sequence.concat(rBa)
sequence.push(0x02); // INTEGER
2014-03-31 05:47:47 +02:00
sequence.push(sBa.length)
sequence = sequence.concat(sBa)
2014-03-31 05:47:47 +02:00
sequence.unshift(sequence.length)
sequence.unshift(0x30); // SEQUENCE
2014-03-31 05:47:47 +02:00
return sequence
},
/**
* Parses a byte array containing a DER-encoded signature.
*
* This function will return an object of the form:
*
* {
* r: BigInteger,
* s: BigInteger
* }
*/
parseSig: function (sig) {
2014-03-31 05:47:47 +02:00
var cursor
if (sig[0] != 0x30) {
throw new Error("Signature not a valid DERSequence")
}
2014-03-31 05:47:47 +02:00
cursor = 2
if (sig[cursor] != 0x02) {
throw new Error("First element in signature must be a DERInteger")
}
var rBa = sig.slice(cursor+2, cursor+2+sig[cursor+1])
2014-03-31 05:47:47 +02:00
cursor += 2+sig[cursor+1]
if (sig[cursor] != 0x02) {
throw new Error("Second element in signature must be a DERInteger")
}
var sBa = sig.slice(cursor+2, cursor+2+sig[cursor+1])
2014-03-31 05:47:47 +02:00
cursor += 2+sig[cursor+1]
//if (cursor != sig.length)
2014-03-31 05:47:47 +02:00
// throw new Error("Extra bytes in signature")
2014-04-21 18:19:30 +02:00
var r = BigInteger.fromBuffer(rBa)
var s = BigInteger.fromBuffer(sBa)
2014-03-31 05:47:47 +02:00
return {r: r, s: s}
},
parseSigCompact: function (sig) {
if (sig.length !== 65) {
2014-03-31 05:47:47 +02:00
throw new Error("Signature has the wrong length")
2012-01-11 02:40:45 +01:00
}
// Signature is prefixed with a type byte storing three bits of
// information.
2014-03-31 05:47:47 +02:00
var i = sig[0] - 27
if (i < 0 || i > 7) {
2014-03-31 05:47:47 +02:00
throw new Error("Invalid signature type")
}
2014-03-31 05:47:47 +02:00
var n = ecparams.getN()
2014-04-21 18:19:30 +02:00
var r = BigInteger.fromBuffer(sig.slice(1, 33)).mod(n)
var s = BigInteger.fromBuffer(sig.slice(33, 65)).mod(n)
2014-03-31 05:47:47 +02:00
return {r: r, s: s, i: i}
},
/**
* Recover a public key from a signature.
*
* See SEC 1: Elliptic Curve Cryptography, section 4.1.6, "Public
* Key Recovery Operation".
*
* http://www.secg.org/download/aid-780/sec1-v2.pdf
*/
recoverPubKey: function (r, s, hash, i) {
// The recovery parameter i has two bits.
2014-03-31 05:47:47 +02:00
i = i & 3
// The less significant bit specifies whether the y coordinate
// of the compressed point is even or not.
2014-03-31 05:47:47 +02:00
var isYEven = i & 1
// The more significant bit specifies whether we should use the
// first or second candidate key.
2014-03-31 05:47:47 +02:00
var isSecondKey = i >> 1
2014-03-31 05:47:47 +02:00
var n = ecparams.getN()
var G = ecparams.getG()
var curve = ecparams.getCurve()
var p = curve.getQ()
var a = curve.getA().toBigInteger()
var b = curve.getB().toBigInteger()
// We precalculate (p + 1) / 4 where p is if the field order
if (!P_OVER_FOUR) {
2014-03-31 05:47:47 +02:00
P_OVER_FOUR = p.add(BigInteger.ONE).divide(BigInteger.valueOf(4))
}
// 1.1 Compute x
2014-03-31 05:47:47 +02:00
var x = isSecondKey ? r.add(n) : r
// 1.3 Convert x to point
2014-03-31 05:47:47 +02:00
var alpha = x.multiply(x).multiply(x).add(a.multiply(x)).add(b).mod(p)
var beta = alpha.modPow(P_OVER_FOUR, p)
2014-03-31 05:47:47 +02:00
// var xorOdd = beta.isEven() ? (i % 2) : ((i+1) % 2)
// If beta is even, but y isn't or vice versa, then convert it,
// otherwise we're done and y == beta.
2014-03-31 05:47:47 +02:00
var y = (beta.isEven() ? !isYEven : isYEven) ? beta : p.subtract(beta)
// 1.4 Check that nR is at infinity
2014-03-31 05:47:47 +02:00
var R = new ECPointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y))
R.validate()
2011-05-04 18:02:56 +02:00
// 1.5 Compute e from M
2014-04-21 18:19:30 +02:00
var e = BigInteger.fromBuffer(hash)
2014-03-31 05:47:47 +02:00
var eNeg = BigInteger.ZERO.subtract(e).mod(n)
2011-05-04 18:02:56 +02:00
// 1.6 Compute Q = r^-1 (sR - eG)
2014-03-31 05:47:47 +02:00
var rInv = r.modInverse(n)
var Q = implShamirsTrick(R, s, G, eNeg).multiply(rInv)
2012-01-11 02:40:45 +01:00
2014-03-31 05:47:47 +02:00
Q.validate()
2014-04-08 19:58:55 +02:00
if (!ecdsa.verifyRaw(e, r, s, Q)) {
2014-03-31 05:47:47 +02:00
throw new Error("Pubkey recovery unsuccessful")
}
2014-03-29 07:44:03 +01:00
return Q
},
/**
* Calculate pubkey extraction parameter.
*
* When extracting a pubkey from a signature, we have to
* distinguish four different cases. Rather than putting this
* burden on the verifier, Bitcoin includes a 2-bit value with the
* signature.
*
* This function simply tries all four cases and returns the value
* that resulted in a successful pubkey recovery.
*/
calcPubKeyRecoveryParam: function (origPubKey, r, s, hash) {
for (var i = 0; i < 4; i++) {
2014-04-08 19:58:55 +02:00
var pubKey = ecdsa.recoverPubKey(r, s, hash, i)
2014-03-29 07:44:03 +01:00
if (pubKey.equals(origPubKey)) {
return i
}
2012-01-11 02:40:45 +01:00
}
throw new Error("Unable to find valid recovery factor")
}
2014-03-31 05:47:47 +02:00
}
2012-01-11 02:40:45 +01:00
2014-04-08 19:58:55 +02:00
module.exports = ecdsa