bitcore/lib/crypto/point.js

72 lines
1.8 KiB
JavaScript
Raw Normal View History

2014-11-20 07:16:27 -08:00
'use strict';
2014-09-17 16:08:42 -07:00
var BN = require('./bn');
2014-08-06 21:02:42 -07:00
var elliptic = require('elliptic');
var ec = elliptic.curves.secp256k1;
var ecpoint = ec.curve.point.bind(ec.curve);
2014-08-06 21:02:42 -07:00
var p = ec.curve.point();
var bufferUtil = require('../util/buffer');
2014-08-09 19:03:59 -07:00
var Point = function Point(x, y, isRed) {
return ecpoint(x, y, isRed);
};
2014-08-06 21:02:42 -07:00
Point.prototype = Object.getPrototypeOf(p);
Point.fromX = ec.curve.pointFromX.bind(ec.curve);
2014-08-06 21:02:42 -07:00
Point.getG = function() {
var p = Point(ec.curve.g.getX(), ec.curve.g.getY());
return p;
};
Point.getN = function() {
2014-09-17 16:08:42 -07:00
return BN(ec.curve.n.toArray());
2014-08-06 21:02:42 -07:00
};
Point.prototype._getX = Point.prototype.getX;
Point.prototype.getX = function() {
2014-09-17 16:08:42 -07:00
return BN(this._getX().toArray());
2014-08-06 21:02:42 -07:00
};
Point.prototype._getY = Point.prototype.getY;
Point.prototype.getY = function() {
2014-09-17 16:08:42 -07:00
return BN(this._getY().toArray());
2014-08-06 21:02:42 -07:00
};
2014-08-09 17:43:24 -07:00
//https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf
Point.prototype.validate = function() {
/* jshint maxcomplexity: 8 */
2014-08-09 17:43:24 -07:00
var p2 = Point.fromX(this.getY().isOdd(), this.getX());
if (p2.y.cmp(this.y) !== 0) {
throw new Error('Invalid y value of public key');
}
var xValidRange = (this.getX().gt(-1) && this.getX().lt(Point.getN()));
var yValidRange = (this.getY().gt(-1) && this.getY().lt(Point.getN()));
if (!(xValidRange && yValidRange)) {
throw new Error('Point does not lie on the curve');
}
if (!(this.mul(Point.getN()).isInfinity())) {
throw new Error('Point times N must be infinity');
}
2014-08-09 17:43:24 -07:00
return this;
};
Point.pointToCompressed = function pointToCompressed(point) {
var xbuf = point.getX().toBuffer({size: 32});
var ybuf = point.getY().toBuffer({size: 32});
var prefix;
var odd = ybuf[ybuf.length - 1] % 2;
if (odd) {
prefix = new Buffer([0x03]);
} else {
prefix = new Buffer([0x02]);
}
return bufferUtil.concat([prefix, xbuf]);
};
2014-08-06 21:02:42 -07:00
module.exports = Point;