UNPKG

2.72 kBJavaScriptView Raw
1var ECPointFp = require('ecurve').ECPointFp;
2var ecparams = require('ecurve-names')('secp256k1');
3var BigInteger = require('bigi');
4
5module.exports = ECKey
6
7
8function ECKey (bytes, compressed) {
9 if (!(this instanceof ECKey)) return new ECKey(bytes);
10
11 this._compressed = compressed || !!ECKey.compressByDefault;
12
13 if (bytes)
14 this.privateKey = bytes;
15}
16
17/********************
18 * STATIC PROPERTIES
19 ********************/
20
21ECKey.compressByDefault = false;
22
23/********************
24 * GET/SET PROPERTIES
25 ********************/
26
27Object.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 //_exportKey => privateKey + (0x01 if compressed)
51 if (this._compressed)
52 this._exportKey = Buffer.concat([ this.key, new Buffer([0x01]) ]);
53 else
54 this._exportKey = Buffer.concat([ this.key ]); //clone key as opposed to passing a reference (relevant to Node.js only)
55
56 this.keyBigInteger = BigInteger.fromByteArrayUnsigned(byteArr);
57
58 //reset
59 this._publicPoint = null;
60 this._pubKeyHash = null;
61 }
62})
63
64Object.defineProperty(ECKey.prototype, 'privateExportKey', {
65 get: function() {
66 return this._exportKey;
67 }
68})
69
70Object.defineProperty(ECKey.prototype, 'publicKey', {
71 get: function() {
72 return new Buffer(this.publicPoint.getEncoded(this.compressed));
73 }
74})
75
76Object.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
84Object.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 //reset key stuff
93 var pk = this.privateKey;
94 this._compressed = c;
95 this.privateKey = pk;
96 }
97})
98
99
100/************
101 * METHODS
102 ************/
103
104/*ECKey.prototype.setPub = function (pub) {
105 this.pub = ECPointFp.decodeFrom(ecparams.getCurve(), pub);
106};*/
107
108ECKey.prototype.toString = function (format) {
109 return this.privateKey.toString('hex');
110}
111
112
113
114
115
116
117
118
119