1 | var ECPointFp = require('ecurve').ECPointFp;
|
2 | var ecparams = require('ecurve-names')('secp256k1');
|
3 | var BigInteger = require('bigi');
|
4 |
|
5 | module.exports = ECKey
|
6 |
|
7 |
|
8 | function ECKey (bytes, compressed) {
|
9 | if (!(this instanceof ECKey)) return new ECKey(bytes, compressed);
|
10 |
|
11 | this._compressed = compressed || !!ECKey.compressByDefault;
|
12 |
|
13 | if (bytes)
|
14 | this.privateKey = bytes;
|
15 | }
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 | ECKey.compressByDefault = false;
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 | Object.defineProperty(ECKey.prototype, 'privateKey', {
|
28 | enumerable: true, configurable: true,
|
29 | get: function() {
|
30 | return this.key;
|
31 | },
|
32 | set: function(bytes) {
|
33 | var byteArr;
|
34 | if (Buffer.isBuffer(bytes)) {
|
35 | this.key = bytes;
|
36 | byteArr = [].slice.call(bytes);
|
37 | } else if (bytes instanceof Uint8Array) {
|
38 | byteArr = [].slice.call(bytes);
|
39 | this.key = new Buffer(byteArr);
|
40 | } else if (Array.isArray(bytes)) {
|
41 | byteArr = bytes;
|
42 | this.key = new Buffer(byteArr);
|
43 | } else {
|
44 | throw new Error('private key bytes must be either a Buffer, Array, or Uint8Array.');
|
45 | }
|
46 |
|
47 | if (bytes.length != 32)
|
48 | throw new Error("private key bytes must have a length of 32");
|
49 |
|
50 |
|
51 | if (this._compressed)
|
52 | this._exportKey = Buffer.concat([ this.key, new Buffer([0x01]) ]);
|
53 | else
|
54 | this._exportKey = Buffer.concat([ this.key ]);
|
55 |
|
56 | this.keyBigInteger = BigInteger.fromByteArrayUnsigned(byteArr);
|
57 |
|
58 |
|
59 | this._publicPoint = null;
|
60 | this._pubKeyHash = null;
|
61 | }
|
62 | })
|
63 |
|
64 | Object.defineProperty(ECKey.prototype, 'privateExportKey', {
|
65 | get: function() {
|
66 | return this._exportKey;
|
67 | }
|
68 | })
|
69 |
|
70 | Object.defineProperty(ECKey.prototype, 'publicKey', {
|
71 | get: function() {
|
72 | return new Buffer(this.publicPoint.getEncoded(this.compressed));
|
73 | }
|
74 | })
|
75 |
|
76 | Object.defineProperty(ECKey.prototype, 'publicPoint', {
|
77 | get: function() {
|
78 | if (!this._publicPoint)
|
79 | this._publicPoint = ecparams.getG().multiply(this.keyBigInteger);
|
80 | return this._publicPoint;
|
81 | }
|
82 | })
|
83 |
|
84 | Object.defineProperty(ECKey.prototype, 'compressed', {
|
85 | get: function() {
|
86 | return this._compressed;
|
87 | },
|
88 | set: function(val) {
|
89 | var c = !!val;
|
90 | if (c === this._compressed) return;
|
91 |
|
92 |
|
93 | var pk = this.privateKey;
|
94 | this._compressed = c;
|
95 | this.privateKey = pk;
|
96 | }
|
97 | })
|
98 |
|
99 |
|
100 |
|
101 |
|
102 |
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 | ECKey.prototype.toString = function (format) {
|
109 | return this.privateKey.toString('hex');
|
110 | }
|
111 |
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|
118 |
|
119 |
|