diff --git a/package.json b/package.json index 7f7a57b..a63fdf2 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,6 @@ "coveralls": "~2.10.0", "mocha-lcov-reporter": "0.0.1", "helloblock-js": "^0.2.1", - "request": "~2.34.0", "browserify": "~4.1.5", "jshint": "2.5.1" }, @@ -72,6 +71,7 @@ "dependencies": { "bigi": "1.1.0", "crypto-js": "3.1.2-3", + "ecurve": "0.7.0", "secure-random": "0.2.1" } } diff --git a/src/ec.js b/src/ec.js deleted file mode 100644 index 5e37f32..0000000 --- a/src/ec.js +++ /dev/null @@ -1,419 +0,0 @@ -// Basic Javascript Elliptic Curve implementation -// Ported loosely from BouncyCastle's Java EC code -// Only Fp curves implemented for now - -var assert = require('assert') -var BigInteger = require('bigi') - -// constants -var THREE = BigInteger.valueOf(3) - -function ECFieldElementFp(q,x) { - this.x = x - // TODO if (x.compareTo(q) >= 0) error - this.q = q -} - -function feFpEquals(other) { - if (other == this) return true - return (this.q.equals(other.q) && this.x.equals(other.x)) -} - -function feFpToBigInteger() { - return this.x -} - -function feFpNegate() { - return new ECFieldElementFp(this.q, this.x.negate().mod(this.q)) -} - -function feFpAdd(b) { - return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q)) -} - -function feFpSubtract(b) { - return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q)) -} - -function feFpMultiply(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q)) -} - -function feFpSquare() { - return new ECFieldElementFp(this.q, this.x.square().mod(this.q)) -} - -function feFpDivide(b) { - return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q)) -} - -ECFieldElementFp.prototype.equals = feFpEquals -ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger -ECFieldElementFp.prototype.negate = feFpNegate -ECFieldElementFp.prototype.add = feFpAdd -ECFieldElementFp.prototype.subtract = feFpSubtract -ECFieldElementFp.prototype.multiply = feFpMultiply -ECFieldElementFp.prototype.square = feFpSquare -ECFieldElementFp.prototype.divide = feFpDivide - -// ---------------- -// ECPointFp - -// constructor -function ECPointFp(curve,x,y,z) { - this.curve = curve - this.x = x - this.y = y - - // Projective coordinates: either zinv == null or z * zinv == 1 - // z and zinv are just BigIntegers, not fieldElements - this.z = (z == undefined) ? BigInteger.ONE : z - this.zinv = null - - //TODO: compression flag -} - -function pointFpGetX() { - if (this.zinv === null) { - this.zinv = this.z.modInverse(this.curve.q) - } - - return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q)) -} - -function pointFpGetY() { - if (this.zinv === null) { - this.zinv = this.z.modInverse(this.curve.q) - } - - return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q)) -} - -function pointFpEquals(other) { - if (other == this) return true - if (this.isInfinity()) return other.isInfinity() - if (other.isInfinity()) return this.isInfinity() - - // u = Y2 * Z1 - Y1 * Z2 - var u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q) - - if (u.signum() !== 0) return false - - // v = X2 * Z1 - X1 * Z2 - var v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q) - - return v.signum() === 0 -} - -function pointFpIsInfinity() { - if ((this.x === null) && (this.y === null)) return true - return this.z.signum() === 0 && this.y.toBigInteger().signum() !== 0 -} - -function pointFpNegate() { - return new ECPointFp(this.curve, this.x, this.y.negate(), this.z) -} - -function pointFpAdd(b) { - if (this.isInfinity()) return b - if (b.isInfinity()) return this - - var x1 = this.x.toBigInteger() - var y1 = this.y.toBigInteger() - var x2 = b.x.toBigInteger() - var y2 = b.y.toBigInteger() - - // u = Y2 * Z1 - Y1 * Z2 - var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.q) - // v = X2 * Z1 - X1 * Z2 - var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.q) - - if (v.signum() === 0) { - if (u.signum() === 0) { - return this.twice() // this == b, so double - } - - return this.curve.getInfinity() // this = -b, so infinity - } - - var v2 = v.square() - var v3 = v2.multiply(v) - var x1v2 = x1.multiply(v2) - var zu2 = u.square().multiply(this.z) - - // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) - var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q) - // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 - var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q) - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q) - - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3) -} - -function pointFpTwice() { - if (this.isInfinity()) return this - if (this.y.toBigInteger().signum() === 0) return this.curve.getInfinity() - - var x1 = this.x.toBigInteger() - var y1 = this.y.toBigInteger() - - var y1z1 = y1.multiply(this.z) - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q) - var a = this.curve.a.toBigInteger() - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE) - - if (a.signum() !== 0) { - w = w.add(this.z.square().multiply(a)) - } - - w = w.mod(this.curve.q) - // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) - var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q) - // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 - var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.q) - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.q) - - return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3) -} - -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -function pointFpMultiply(k) { - if (this.isInfinity()) return this - if (k.signum() === 0) return this.curve.getInfinity() - - var e = k - var h = e.multiply(THREE) - - var neg = this.negate() - var R = this - - for (var i = h.bitLength() - 2; i > 0; --i) { - R = R.twice() - - var hBit = h.testBit(i) - var eBit = e.testBit(i) - - if (hBit != eBit) { - R = R.add(hBit ? this : neg) - } - } - - return R -} - -// Compute this*j + x*k (simultaneous multiplication) -function pointFpMultiplyTwo(j,x,k) { - var i - - if (j.bitLength() > k.bitLength()) - i = j.bitLength() - 1 - else - i = k.bitLength() - 1 - - var R = this.curve.getInfinity() - var both = this.add(x) - while (i >= 0) { - R = R.twice() - if (j.testBit(i)) { - if (k.testBit(i)) { - R = R.add(both) - } - else { - R = R.add(this) - } - } - else { - if (k.testBit(i)) { - R = R.add(x) - } - } - --i - } - - return R -} - -ECPointFp.prototype.getX = pointFpGetX -ECPointFp.prototype.getY = pointFpGetY -ECPointFp.prototype.equals = pointFpEquals -ECPointFp.prototype.isInfinity = pointFpIsInfinity -ECPointFp.prototype.negate = pointFpNegate -ECPointFp.prototype.add = pointFpAdd -ECPointFp.prototype.twice = pointFpTwice -ECPointFp.prototype.multiply = pointFpMultiply -ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo - -// ---------------- -// ECCurveFp - -// constructor -function ECCurveFp(q,a,b) { - this.q = q - this.a = this.fromBigInteger(a) - this.b = this.fromBigInteger(b) - this.infinity = new ECPointFp(this, null, null) -} - -function curveFpGetQ() { - return this.q -} - -function curveFpGetA() { - return this.a -} - -function curveFpGetB() { - return this.b -} - -function curveFpEquals(other) { - if (other == this) return true - return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b)) -} - -function curveFpGetInfinity() { - return this.infinity -} - -function curveFpFromBigInteger(x) { - return new ECFieldElementFp(this.q, x) -} - -ECCurveFp.prototype.getQ = curveFpGetQ -ECCurveFp.prototype.getA = curveFpGetA -ECCurveFp.prototype.getB = curveFpGetB -ECCurveFp.prototype.equals = curveFpEquals -ECCurveFp.prototype.getInfinity = curveFpGetInfinity -ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger - -ECFieldElementFp.prototype.getByteLength = function () { - return Math.floor((this.toBigInteger().bitLength() + 7) / 8) -} - -ECPointFp.prototype.getEncoded = function(compressed) { - var x = this.getX().toBigInteger() - var y = this.getY().toBigInteger() - var buffer - - // 0x02/0x03 | X - if (compressed) { - buffer = new Buffer(33) - buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) - - // 0x04 | X | Y - } else { - buffer = new Buffer(65) - buffer.writeUInt8(0x04, 0) - - y.toBuffer(32).copy(buffer, 33) - } - - x.toBuffer(32).copy(buffer, 1) - - return buffer -} - -ECPointFp.decodeFrom = function (curve, buffer) { - var type = buffer.readUInt8(0) - var compressed = type !== 0x04 - var x = BigInteger.fromBuffer(buffer.slice(1, 33)) - var y - - if (compressed) { - assert.equal(buffer.length, 33, 'Invalid sequence length') - assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') - - var isYEven = (type === 0x02) - var a = curve.getA().toBigInteger() - var b = curve.getB().toBigInteger() - var p = curve.getQ() - - // We precalculate (p + 1) / 4 where p is the field order - if (!curve.P_OVER_FOUR) { - curve.P_OVER_FOUR = p.add(BigInteger.ONE).shiftRight(2) - } - - // Convert x to point - var alpha = x.pow(3).add(a.multiply(x)).add(b).mod(p) - var beta = alpha.modPow(curve.P_OVER_FOUR, p) - - // If beta is even, but y isn't, or vice versa, then convert it, - // otherwise we're done and y == beta. - y = (beta.isEven() ^ isYEven) ? p.subtract(beta) : beta - - } else { - assert.equal(buffer.length, 65, 'Invalid sequence length') - - y = BigInteger.fromBuffer(buffer.slice(33)) - } - - var Q = new ECPointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)) - - return { - Q: Q, - compressed: compressed - } -} - -ECPointFp.prototype.isOnCurve = function () { - var x = this.getX().toBigInteger() - var y = this.getY().toBigInteger() - var a = this.curve.getA().toBigInteger() - var b = this.curve.getB().toBigInteger() - var p = this.curve.getQ() - var lhs = y.square().mod(p) - var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) - return lhs.equals(rhs) -} - -ECPointFp.prototype.toString = function () { - return '('+this.getX().toBigInteger().toString()+','+ - this.getY().toBigInteger().toString()+')' -} - -/** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ -ECPointFp.prototype.validate = function () { - var n = this.curve.getQ() - - // Check Q != O - if (this.isInfinity()) { - throw new Error("Point is at infinity.") - } - - // Check coordinate bounds - var x = this.getX().toBigInteger() - var y = this.getY().toBigInteger() - if (x.compareTo(BigInteger.ONE) < 0 || - x.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('x coordinate out of bounds') - } - if (y.compareTo(BigInteger.ONE) < 0 || - y.compareTo(n.subtract(BigInteger.ONE)) > 0) { - throw new Error('y coordinate out of bounds') - } - - // Check y^2 = x^3 + ax + b (mod n) - if (!this.isOnCurve()) { - throw new Error("Point is not on the curve.") - } - - // Check nQ = 0 (Q is a scalar multiple of G) - if (this.multiply(n).isInfinity()) { - // TODO: This check doesn't work - fix. - throw new Error("Point is not a scalar multiple of G.") - } - - return true -} - -module.exports = ECCurveFp -module.exports.ECPointFp = ECPointFp diff --git a/src/ecdsa.js b/src/ecdsa.js index cf4b182..ff2a8d7 100644 --- a/src/ecdsa.js +++ b/src/ecdsa.js @@ -2,9 +2,9 @@ var assert = require('assert') var crypto = require('./crypto') var BigInteger = require('bigi') -var ECPointFp = require('./ec').ECPointFp +var Point = require('ecurve').Point -function deterministicGenerateK(ecparams, hash, d) { +function deterministicGenerateK(curve, hash, d) { assert(Buffer.isBuffer(hash), 'Hash must be a Buffer, not ' + hash) assert.equal(hash.length, 32, 'Hash must be 256 bit') assert(d instanceof BigInteger, 'Private key must be a BigInteger') @@ -22,23 +22,23 @@ function deterministicGenerateK(ecparams, hash, d) { v = crypto.HmacSHA256(v, k) v = crypto.HmacSHA256(v, k) - var n = ecparams.getN() + var n = curve.params.n 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') + assert(kB.compareTo(n) < 0, 'Invalid k value') return kB } -function sign(ecparams, hash, d) { - var k = deterministicGenerateK(ecparams, hash, d) +function sign(curve, hash, d) { + var k = deterministicGenerateK(curve, hash, d) - var n = ecparams.getN() - var G = ecparams.getG() + var n = curve.params.n + var G = curve.params.G var Q = G.multiply(k) var e = BigInteger.fromBuffer(hash) - var r = Q.getX().toBigInteger().mod(n) + var r = Q.affineX.mod(n) assert.notEqual(r.signum(), 0, 'Invalid R value') var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n) @@ -54,15 +54,15 @@ function sign(ecparams, hash, d) { return {r: r, s: s} } -function verify(ecparams, hash, signature, Q) { +function verify(curve, hash, signature, Q) { var e = BigInteger.fromBuffer(hash) - return verifyRaw(ecparams, e, signature, Q) + return verifyRaw(curve, e, signature, Q) } -function verifyRaw(ecparams, e, signature, Q) { - var n = ecparams.getN() - var G = ecparams.getG() +function verifyRaw(curve, e, signature, Q) { + var n = curve.params.n + var G = curve.params.G var r = signature.r var s = signature.s @@ -76,7 +76,7 @@ function verifyRaw(ecparams, e, signature, Q) { var u2 = r.multiply(c).mod(n) var point = G.multiplyTwo(u1, Q, u2) - var v = point.getX().toBigInteger().mod(n) + var v = point.affineX.mod(n) return v.equals(r) } @@ -185,7 +185,7 @@ function parseSigCompact(buffer) { * * http://www.secg.org/download/aid-780/sec1-v2.pdf */ -function recoverPubKey(ecparams, e, signature, i) { +function recoverPubKey(curve, e, signature, i) { assert.strictEqual(i & 3, i, 'The recovery param is more than two bits') var r = signature.r @@ -199,12 +199,11 @@ function recoverPubKey(ecparams, e, signature, i) { // first or second candidate key. var isSecondKey = i >> 1 - 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() + var n = curve.params.n + var G = curve.params.G + var p = curve.p + var a = curve.a + var b = curve.b // We precalculate (p + 1) / 4 where p is the field order if (!curve.P_OVER_FOUR) { @@ -223,8 +222,8 @@ function recoverPubKey(ecparams, e, signature, i) { var y = (beta.isEven() ^ isYEven) ? p.subtract(beta) : beta // 1.4 Check that nR isn't at infinity - var R = new ECPointFp(curve, curve.fromBigInteger(x), curve.fromBigInteger(y)) - R.validate() + var R = Point.fromAffine(curve, x, y) + curve.validate(R) // 1.5 Compute -e from e var eNeg = e.negate().mod(n) @@ -234,9 +233,9 @@ function recoverPubKey(ecparams, e, signature, i) { var rInv = r.modInverse(n) var Q = R.multiplyTwo(s, G, eNeg).multiply(rInv) - Q.validate() + curve.validate(Q) - if (!verifyRaw(ecparams, e, signature, Q)) { + if (!verifyRaw(curve, e, signature, Q)) { throw new Error("Pubkey recovery unsuccessful") } @@ -254,9 +253,9 @@ function recoverPubKey(ecparams, e, signature, i) { * This function simply tries all four cases and returns the value * that resulted in a successful pubkey recovery. */ -function calcPubKeyRecoveryParam(ecparams, e, signature, Q) { +function calcPubKeyRecoveryParam(curve, e, signature, Q) { for (var i = 0; i < 4; i++) { - var Qprime = recoverPubKey(ecparams, e, signature, i) + var Qprime = recoverPubKey(curve, e, signature, i) if (Qprime.equals(Q)) { return i diff --git a/src/eckey.js b/src/eckey.js index c78c261..166da09 100644 --- a/src/eckey.js +++ b/src/eckey.js @@ -7,14 +7,14 @@ var secureRandom = require('secure-random') var BigInteger = require('bigi') var ECPubKey = require('./ecpubkey') -var sec = require('./sec') -var ecparams = sec('secp256k1') +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') function ECKey(d, compressed) { assert(d.signum() > 0, 'Private key must be greater than 0') - assert(d.compareTo(ecparams.getN()) < 0, 'Private key must be less than the curve order') + assert(d.compareTo(curve.params.n) < 0, 'Private key must be less than the curve order') - var Q = ecparams.getG().multiply(d) + var Q = curve.params.G.multiply(d) this.d = d this.pub = new ECPubKey(Q, compressed) @@ -47,7 +47,7 @@ ECKey.makeRandom = function(compressed, rng) { var buffer = new Buffer(rng(32)) var d = BigInteger.fromBuffer(buffer) - d = d.mod(ecparams.getN()) + d = d.mod(curve.params.n) return new ECKey(d, compressed) } @@ -71,7 +71,7 @@ ECKey.prototype.toWIF = function(network) { // Operations ECKey.prototype.sign = function(hash) { - return ecdsa.sign(ecparams, hash, this.d) + return ecdsa.sign(curve, hash, this.d) } module.exports = ECKey diff --git a/src/ecpubkey.js b/src/ecpubkey.js index 9f7d2fb..3716729 100644 --- a/src/ecpubkey.js +++ b/src/ecpubkey.js @@ -4,13 +4,12 @@ var ecdsa = require('./ecdsa') var networks = require('./networks') var Address = require('./address') -var ECPointFp = require('./ec').ECPointFp -var sec = require('./sec') -var ecparams = sec('secp256k1') +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') function ECPubKey(Q, compressed) { - assert(Q instanceof ECPointFp, 'Expected ECPointFP, got ' + Q) + assert(Q instanceof ecurve.Point, 'Expected Point, got ' + Q) if (compressed == undefined) compressed = true assert.strictEqual(typeof compressed, 'boolean', 'Expected boolean, got ' + compressed) @@ -21,8 +20,8 @@ function ECPubKey(Q, compressed) { // Static constructors ECPubKey.fromBuffer = function(buffer) { - var decode = ECPointFp.decodeFrom(ecparams.getCurve(), buffer) - return new ECPubKey(decode.Q, decode.compressed) + var Q = ecurve.Point.decodeFrom(curve, buffer) + return new ECPubKey(Q, Q.compressed) } ECPubKey.fromHex = function(hex) { @@ -37,7 +36,7 @@ ECPubKey.prototype.getAddress = function(network) { } ECPubKey.prototype.verify = function(hash, signature) { - return ecdsa.verify(ecparams, hash, signature, this.Q) + return ecdsa.verify(curve, hash, signature, this.Q) } // Export functions diff --git a/src/hdnode.js b/src/hdnode.js index 741c1a5..d36fe31 100644 --- a/src/hdnode.js +++ b/src/hdnode.js @@ -1,15 +1,14 @@ var assert = require('assert') var base58check = require('./base58check') - -var BigInteger = require('bigi') var crypto = require('./crypto') -var ECKey = require('./eckey') -var ECPubKey = require('./ecpubkey') -var ECPointFp = require('./ec').ECPointFp var networks = require('./networks') -var sec = require('./sec') -var ecparams = sec("secp256k1") +var BigInteger = require('bigi') +var ECKey = require('./eckey') +var ECPubKey = require('./ecpubkey') + +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') function findBIP32ParamsByVersion(version) { for (var name in networks) { @@ -100,20 +99,20 @@ HDNode.fromBuffer = function(buffer) { if (params.isPrivate) { assert.strictEqual(buffer.readUInt8(45), 0x00, 'Invalid private key') var data = buffer.slice(46, 78) - var D = BigInteger.fromBuffer(data) - hd = new HDNode(D, chainCode, params.network) + var d = BigInteger.fromBuffer(data) + hd = new HDNode(d, chainCode, params.network) // 33 bytes: public key data (0x02 + X or 0x03 + X) } else { var data = buffer.slice(45, 78) - var decode = ECPointFp.decodeFrom(ecparams.getCurve(), data) - assert.equal(decode.compressed, true, 'Invalid public key') + var Q = ecurve.Point.decodeFrom(curve, data) + assert.equal(Q.compressed, true, 'Invalid public key') // Verify that the X coordinate in the public point corresponds to a point on the curve. // If not, the extended public key is invalid. - decode.Q.validate() + curve.validate(Q) - hd = new HDNode(decode.Q, chainCode, params.network) + hd = new HDNode(Q, chainCode, params.network) } hd.depth = depth @@ -223,7 +222,7 @@ HDNode.prototype.derive = function(index) { var pIL = BigInteger.fromBuffer(IL) // In case parse256(IL) >= n, proceed with the next value for i - if (pIL.compareTo(ecparams.getN()) >= 0) { + if (pIL.compareTo(curve.params.n) >= 0) { return this.derive(index + 1) } @@ -231,7 +230,7 @@ HDNode.prototype.derive = function(index) { var hd if (this.privKey) { // ki = parse256(IL) + kpar (mod n) - var ki = pIL.add(this.privKey.d).mod(ecparams.getN()) + var ki = pIL.add(this.privKey.d).mod(curve.params.n) // In case ki == 0, proceed with the next value for i if (ki.signum() === 0) { @@ -244,10 +243,10 @@ HDNode.prototype.derive = function(index) { } else { // Ki = point(parse256(IL)) + Kpar // = G*IL + Kpar - var Ki = ecparams.getG().multiply(pIL).add(this.pubKey.Q) + var Ki = curve.params.G.multiply(pIL).add(this.pubKey.Q) // In case Ki is the point at infinity, proceed with the next value for i - if (Ki.isInfinity()) { + if (curve.isInfinity(Ki)) { return this.derive(index + 1) } diff --git a/src/index.js b/src/index.js index 69ea066..b46f2c5 100644 --- a/src/index.js +++ b/src/index.js @@ -1,4 +1,3 @@ -var ec = require('./ec') var T = require('./transaction') module.exports = { @@ -8,16 +7,13 @@ module.exports = { bufferutils: require('./bufferutils'), convert: require('./convert'), crypto: require('./crypto'), - ec: ec, ecdsa: require('./ecdsa'), ECKey: require('./eckey'), - ECPointFp: ec.ECPointFp, ECPubKey: require('./ecpubkey'), Message: require('./message'), opcodes: require('./opcodes'), HDNode: require('./hdnode'), Script: require('./script'), - sec: require('./sec'), Transaction: T.Transaction, TransactionIn: T.TransactionIn, TransactionOut: T.TransactionOut, diff --git a/src/message.js b/src/message.js index 53f4ea8..02b0b71 100644 --- a/src/message.js +++ b/src/message.js @@ -9,8 +9,8 @@ var networks = require('./networks') var Address = require('./address') var ECPubKey = require('./ecpubkey') -var sec = require('./sec') -var ecparams = sec('secp256k1') +var ecurve = require('ecurve') +var ecparams = ecurve.getCurveByName('secp256k1') function magicHash(message, network) { var magicPrefix = new Buffer(network.magicPrefix) diff --git a/src/sec.js b/src/sec.js deleted file mode 100644 index 0d47efc..0000000 --- a/src/sec.js +++ /dev/null @@ -1,84 +0,0 @@ -// Named EC curves - -var BigInteger = require('bigi') -var ECCurveFp = require('./ec') -var ECPointFp = ECCurveFp.ECPointFp - -// ---------------- -// X9ECParameters - -// constructor -function X9ECParameters(curve,g,n,h) { - this.curve = curve - this.g = g - this.n = n - this.h = h -} - -function x9getCurve() { - return this.curve -} - -function x9getG() { - return this.g -} - -function x9getN() { - return this.n -} - -function x9getH() { - return this.h -} - -X9ECParameters.prototype.getCurve = x9getCurve -X9ECParameters.prototype.getG = x9getG -X9ECParameters.prototype.getN = x9getN -X9ECParameters.prototype.getH = x9getH - -function secp256r1() { - // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 - var p = BigInteger.fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF") - var a = BigInteger.fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC") - var b = BigInteger.fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B") - //byte[] S = BigInteger.fromHex("C49D360886E704936A6678E1139D26B7819F7E90") - var n = BigInteger.fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551") - var h = BigInteger.ONE - var curve = new ECCurveFp(p, a, b) - - var x = BigInteger.fromHex("6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296") - var y = BigInteger.fromHex("4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5") - var G = new ECPointFp(curve, - curve.fromBigInteger(x), - curve.fromBigInteger(y)) - - return new X9ECParameters(curve, G, n, h) -} - -function secp256k1() { - // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 - var p = BigInteger.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F") - var a = BigInteger.ZERO - var b = BigInteger.fromHex("07") - //byte[] S = null - var n = BigInteger.fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") - var h = BigInteger.ONE - var curve = new ECCurveFp(p, a, b) - - var x = BigInteger.fromHex("79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798") - var y = BigInteger.fromHex("483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8") - var G = new ECPointFp(curve, - curve.fromBigInteger(x), - curve.fromBigInteger(y)) - - return new X9ECParameters(curve, G, n, h) -} - -function getSECCurveByName(name) { - return ({ - "secp256k1": secp256k1, - "secp256r1": secp256r1 - }[name])() -} - -module.exports = getSECCurveByName diff --git a/test/ec.js b/test/ec.js deleted file mode 100644 index 38b1784..0000000 --- a/test/ec.js +++ /dev/null @@ -1,84 +0,0 @@ -var assert = require('assert') - -var sec = require('../src/sec') -var ecparams = sec('secp256k1') - -var BigInteger = require('bigi') -var ECPointFp = require('../src/ec').ECPointFp - -var fixtures = require('./fixtures/ec.json') - -describe('ec', function() { - describe('ECPointFp', function() { - it('behaves correctly', function() { - var G = ecparams.getG() - var n = ecparams.getN() - - assert.ok(G.multiply(n).isInfinity(), "Gn is infinite") - - var k = BigInteger.ONE - var P = G.multiply(k) - assert.ok(!P.isInfinity(), "kG is not infinite") - assert.ok(P.isOnCurve(), "kG on curve") - assert.ok(P.multiply(n).isInfinity(), "kGn is infinite") - - assert.ok(P.validate(), "kG validates as a public key") - }) - - describe('getEncoded', function() { - it('encodes a point correctly', function() { - fixtures.valid.ECPointFp.forEach(function(f) { - var curve = ecparams.getCurve() - var Q = new ECPointFp( - curve, - curve.fromBigInteger(new BigInteger(f.x)), - curve.fromBigInteger(new BigInteger(f.y)) - ) - - var encoded = Q.getEncoded(f.compressed) - assert.equal(encoded.toString('hex'), f.hex) - }) - }) - }) - - describe('decodeFrom', function() { - it('decodes the correct point', function() { - fixtures.valid.ECPointFp.forEach(function(f) { - var curve = ecparams.getCurve() - var buffer = new Buffer(f.hex, 'hex') - - var decoded = ECPointFp.decodeFrom(curve, buffer) - assert.equal(decoded.Q.getX().toBigInteger().toString(), f.x) - assert.equal(decoded.Q.getY().toBigInteger().toString(), f.y) - assert.equal(decoded.compressed, f.compressed) - }) - }) - - fixtures.invalid.ECPointFp.forEach(function(f) { - it('throws on ' + f.description, function() { - var curve = ecparams.getCurve() - var buffer = new Buffer(f.hex, 'hex') - - assert.throws(function() { - ECPointFp.decodeFrom(curve, buffer) - }, /Invalid sequence length|Invalid sequence tag/) - }) - }) - - it('supports secp256r1', function() { - var f = fixtures.valid.ECPointFp[1] - var ecparams2 = sec('secp256r1') - var curve = ecparams2.getCurve() - - var d = BigInteger.ONE - var Q = ecparams2.getG().multiply(d) - - var buffer = Q.getEncoded(true) - var decoded = ECPointFp.decodeFrom(curve, buffer) - - assert(Q.equals(decoded.Q)) - assert(decoded.compressed, true) - }) - }) - }) -}) diff --git a/test/ecdsa.js b/test/ecdsa.js index 9455a6e..8569e08 100644 --- a/test/ecdsa.js +++ b/test/ecdsa.js @@ -4,11 +4,11 @@ var ecdsa = require('../src/ecdsa') var message = require('../src/message') var networks = require('../src/networks') -var sec = require('../src/sec') -var ecparams = sec("secp256k1") - var BigInteger = require('bigi') +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') + var fixtures = require('./fixtures/ecdsa.json') describe('ecdsa', function() { @@ -18,7 +18,7 @@ describe('ecdsa', function() { var d = BigInteger.fromHex(f.d) var h1 = crypto.sha256(f.message) - var k = ecdsa.deterministicGenerateK(ecparams, h1, d) + var k = ecdsa.deterministicGenerateK(curve, h1, d) assert.equal(k.toHex(), f.k) }) }) @@ -29,12 +29,12 @@ describe('ecdsa', function() { var d = BigInteger.ONE var signature = new Buffer('INcvXVVEFyIfHLbDX+xoxlKFn3Wzj9g0UbhObXdMq+YMKC252o5RHFr0/cKdQe1WsBLUBi4morhgZ77obDJVuV0=', 'base64') - var Q = ecparams.getG().multiply(d) + var Q = curve.params.G.multiply(d) var hash = message.magicHash('1111', networks.bitcoin) var e = BigInteger.fromBuffer(hash) var parsed = ecdsa.parseSigCompact(signature) - var Qprime = ecdsa.recoverPubKey(ecparams, e, parsed.signature, parsed.i) + var Qprime = ecdsa.recoverPubKey(curve, e, parsed.signature, parsed.i) assert(Q.equals(Qprime)) }) }) @@ -44,7 +44,7 @@ describe('ecdsa', function() { it('produces a deterministic signature for \"' + f.message + '\"', function() { var d = BigInteger.fromHex(f.d) var hash = crypto.sha256(f.message) - var signature = ecdsa.sign(ecparams, hash, d) + var signature = ecdsa.sign(curve, hash, d) assert.equal(signature.r.toString(), f.signature.r) assert.equal(signature.s.toString(), f.signature.s) @@ -53,10 +53,10 @@ describe('ecdsa', function() { it('should sign with low S value', function() { var hash = crypto.sha256('Vires in numeris') - var sig = ecdsa.sign(ecparams, hash, BigInteger.ONE) + var sig = ecdsa.sign(curve, hash, BigInteger.ONE) // See BIP62 for more information - var N_OVER_TWO = ecparams.getN().shiftRight(1) + var N_OVER_TWO = curve.params.n.shiftRight(1) assert(sig.s.compareTo(N_OVER_TWO) <= 0) }) }) @@ -65,7 +65,7 @@ describe('ecdsa', function() { fixtures.valid.forEach(function(f) { it('verifies a valid signature for \"' + f.message + '\"', function() { var d = BigInteger.fromHex(f.d) - var Q = ecparams.getG().multiply(d) + var Q = curve.params.G.multiply(d) var signature = { r: new BigInteger(f.signature.r), @@ -73,7 +73,7 @@ describe('ecdsa', function() { } var e = BigInteger.fromBuffer(crypto.sha256(f.message)) - assert(ecdsa.verifyRaw(ecparams, e, signature, Q)) + assert(ecdsa.verifyRaw(curve, e, signature, Q)) }) }) @@ -85,9 +85,9 @@ describe('ecdsa', function() { r: new BigInteger(f.signature.r), s: new BigInteger(f.signature.s) } - var Q = ecparams.getG().multiply(d) + var Q = curve.params.G.multiply(d) - assert.equal(ecdsa.verifyRaw(ecparams, e, signature, Q), false) + assert.equal(ecdsa.verifyRaw(curve, e, signature, Q), false) }) }) }) diff --git a/test/ecpubkey.js b/test/ecpubkey.js index 8d22f1b..62609ef 100644 --- a/test/ecpubkey.js +++ b/test/ecpubkey.js @@ -1,25 +1,23 @@ var assert = require('assert') var crypto = require('../src/crypto') var networks = require('../src/networks') -var sec = require('../src/sec') -var ecparams = sec('secp256k1') var BigInteger = require('bigi') -var ECPointFp = require('../src/ec').ECPointFp var ECPubKey = require('../src/ecpubkey') +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') + var fixtures = require('./fixtures/ecpubkey.json') describe('ECPubKey', function() { var Q beforeEach(function() { - var curve = ecparams.getCurve() - - Q = new ECPointFp( + Q = ecurve.Point.fromAffine( curve, - curve.fromBigInteger(new BigInteger(fixtures.Q.x)), - curve.fromBigInteger(new BigInteger(fixtures.Q.y)) + new BigInteger(fixtures.Q.x), + new BigInteger(fixtures.Q.y) ) }) diff --git a/test/fixtures/ec.json b/test/fixtures/ec.json deleted file mode 100644 index f4390ef..0000000 --- a/test/fixtures/ec.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "valid": { - "ECPointFp": [ - { - "x": "55066263022277343669578718895168534326250603453777594175500187360389116729240", - "y": "32670510020758816978083085130507043184471273380659243275938904335757337482424", - "compressed": false, - "hex": "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" - }, - { - "x": "55066263022277343669578718895168534326250603453777594175500187360389116729240", - "y": "32670510020758816978083085130507043184471273380659243275938904335757337482424", - "compressed": true, - "hex": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" - }, - { - "x": "83225686012142088543596389522774768397204444195709443235253141114409346958144", - "y": "23739058578904784236915560265041168694780215705543362357495033621678991351768", - "compressed": true, - "hex": "02b80011a883a0fd621ad46dfc405df1e74bf075cbaf700fd4aebef6e96f848340" - }, - { - "x": "30095590000961171681152428142595206241714764354580127609094760797518133922356", - "y": "93521207164355458151597931319591130635754976513751247168472016818884561919702", - "compressed": true, - "hex": "024289801366bcee6172b771cf5a7f13aaecd237a0b9a1ff9d769cabc2e6b70a34" - }, - { - "x": "55066263022277343669578718895168534326250603453777594175500187360389116729240", - "y": "83121579216557378445487899878180864668798711284981320763518679672151497189239", - "compressed": true, - "hex": "0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" - } - ] - }, - "invalid": { - "ECPointFp": [ - { - "description": "Invalid sequence tag", - "hex": "0179be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798" - }, - { - "description": "Sequence too short", - "hex": "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10" - }, - { - "description": "Sequence too short (compressed)", - "hex": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f8" - }, - { - "description": "Sequence too long", - "hex": "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b80000" - }, - { - "description": "Sequence too long (compressed)", - "hex": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817980000" - } - ] - } -} diff --git a/test/hdnode.js b/test/hdnode.js index 5906b27..44ef320 100644 --- a/test/hdnode.js +++ b/test/hdnode.js @@ -1,17 +1,18 @@ var assert = require('assert') var networks = require('../src/networks') -var sec = require('../src/sec') -var ecparams = sec("secp256k1") var BigInteger = require('bigi') var HDNode = require('../src/hdnode') +var ecurve = require('ecurve') +var curve = ecurve.getCurveByName('secp256k1') + var fixtures = require('./fixtures/hdnode.json') describe('HDNode', function() { describe('Constructor', function() { var d = BigInteger.ONE - var Q = ecparams.getG().multiply(d) + var Q = curve.params.G.multiply(d) var chainCode = new Buffer(32) chainCode.fill(1)