1 | 'use strict';
|
2 |
|
3 | var BN = require('./bn');
|
4 | var BufferUtil = require('../util/buffer');
|
5 |
|
6 | var EC = require('elliptic').ec;
|
7 | var ec = new EC('secp256k1');
|
8 | var ecPoint = ec.curve.point.bind(ec.curve);
|
9 | var ecPointFromX = ec.curve.pointFromX.bind(ec.curve);
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 | var Point = function Point(x, y, isRed) {
|
24 | try {
|
25 | var point = ecPoint(x, y, isRed);
|
26 | } catch (e) {
|
27 | throw new Error('Invalid Point');
|
28 | }
|
29 | point.validate();
|
30 | return point;
|
31 | };
|
32 |
|
33 | Point.prototype = Object.getPrototypeOf(ec.curve.point());
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | Point.fromX = function fromX(odd, x){
|
45 | try {
|
46 | var point = ecPointFromX(x, odd);
|
47 | } catch (e) {
|
48 | throw new Error('Invalid X');
|
49 | }
|
50 | point.validate();
|
51 | return point;
|
52 | };
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | Point.getG = function getG() {
|
62 | return ec.curve.g;
|
63 | };
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 | Point.getN = function getN() {
|
73 | return new BN(ec.curve.n.toArray());
|
74 | };
|
75 |
|
76 | Point.prototype._getX = Point.prototype.getX;
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | Point.prototype.getX = function getX() {
|
85 | return new BN(this._getX().toArray());
|
86 | };
|
87 |
|
88 | Point.prototype._getY = Point.prototype.getY;
|
89 |
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 | Point.prototype.getY = function getY() {
|
97 | return new BN(this._getY().toArray());
|
98 | };
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 |
|
109 | Point.prototype.validate = function validate() {
|
110 |
|
111 | if (this.isInfinity()){
|
112 | throw new Error('Point cannot be equal to Infinity');
|
113 | }
|
114 |
|
115 | var p2;
|
116 | try {
|
117 | p2 = ecPointFromX(this.getX(), this.getY().isOdd());
|
118 | } catch (e) {
|
119 | throw new Error('Point does not lie on the curve');
|
120 | }
|
121 |
|
122 | if (p2.y.cmp(this.y) !== 0) {
|
123 | throw new Error('Invalid y value for curve.');
|
124 | }
|
125 |
|
126 |
|
127 |
|
128 | if (!(this.mul(Point.getN()).isInfinity())) {
|
129 | throw new Error('Point times N must be infinity');
|
130 | }
|
131 |
|
132 | return this;
|
133 |
|
134 | };
|
135 |
|
136 | Point.pointToCompressed = function pointToCompressed(point) {
|
137 | var xbuf = point.getX().toBuffer({size: 32});
|
138 | var ybuf = point.getY().toBuffer({size: 32});
|
139 |
|
140 | var prefix;
|
141 | var odd = ybuf[ybuf.length - 1] % 2;
|
142 | if (odd) {
|
143 | prefix = Buffer.from([0x03]);
|
144 | } else {
|
145 | prefix = Buffer.from([0x02]);
|
146 | }
|
147 | return BufferUtil.concat([prefix, xbuf]);
|
148 | };
|
149 |
|
150 | module.exports = Point;
|