-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathecpair.js
More file actions
206 lines (206 loc) · 6.79 KB
/
ecpair.js
File metadata and controls
206 lines (206 loc) · 6.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import * as networks from './networks.js';
import * as types from './types.js';
import * as wif from 'wif';
import { testEcc } from './testecc.js';
export { networks };
import * as v from 'valibot';
import * as tools from 'uint8array-tools';
const ECPairOptionsSchema = v.optional(
v.object({
compressed: v.optional(v.boolean()),
network: v.optional(types.NetworkSchema),
// https://github.com/fabian-hiller/valibot/issues/243#issuecomment-2182514063
rng: v.optional(
v.pipe(
v.instance(Function),
v.transform((func) => {
return (arg) => {
const parsedArg = v.parse(v.optional(v.number()), arg);
const returnedValue = func(parsedArg);
const parsedReturn = v.parse(v.instance(Uint8Array), returnedValue);
return parsedReturn;
};
}),
),
),
}),
);
const toXOnly = (pubKey) =>
pubKey.length === 32 ? pubKey : pubKey.subarray(1, 33);
export function ECPairFactory(ecc) {
testEcc(ecc);
function isPoint(maybePoint) {
return ecc.isPoint(maybePoint);
}
function fromPrivateKey(buffer, options) {
v.parse(types.Buffer256Bit, buffer);
if (!ecc.isPrivate(buffer))
throw new TypeError('Private key not in range [1, n)');
v.parse(ECPairOptionsSchema, options);
return new ECPair(buffer, undefined, options);
}
function fromPublicKey(buffer, options) {
if (!ecc.isPoint(buffer)) {
throw new Error('Point not on the curve');
}
v.parse(ECPairOptionsSchema, options);
return new ECPair(undefined, buffer, options);
}
function fromWIF(wifString, network) {
const decoded = wif.decode(wifString);
const version = decoded.version;
// list of networks?
if (Array.isArray(network)) {
network = network
.filter((x) => {
return version === x.wif;
})
.pop();
if (!network) throw new Error('Unknown network version');
// otherwise, assume a network object (or default to bitcoin)
} else {
network = network || networks.bitcoin;
if (version !== network.wif) throw new Error('Invalid network version');
}
return fromPrivateKey(decoded.privateKey, {
compressed: decoded.compressed,
network: network,
});
}
/**
* Generates a random ECPairInterface.
*
* Uses `crypto.getRandomValues` under the hood for options.rng function, which is still an experimental feature as of Node.js 18.19.0. To work around this you can do one of the following:
* 1. Use a polyfill for crypto.getRandomValues()
* 2. Use the `--experimental-global-webcrypto` flag when running node.js.
* 3. Pass in a custom rng function to generate random values.
*
* @param {ECPairOptions} options - Options for the ECPairInterface.
* @return {ECPairInterface} A random ECPairInterface.
*/
function makeRandom(options) {
v.parse(ECPairOptionsSchema, options);
if (options === undefined) options = {};
const rng =
options.rng || ((size) => crypto.getRandomValues(new Uint8Array(size)));
let d;
do {
d = rng(32);
v.parse(types.Buffer256Bit, d);
} while (!ecc.isPrivate(d));
return fromPrivateKey(d, options);
}
class ECPair {
__D;
__Q;
compressed;
network;
lowR;
constructor(__D, __Q, options) {
this.__D = __D;
this.__Q = __Q;
this.lowR = false;
if (options === undefined) options = {};
this.compressed =
options.compressed === undefined ? true : options.compressed;
this.network = options.network || networks.bitcoin;
if (__Q !== undefined) this.__Q = ecc.pointCompress(__Q, this.compressed);
}
get privateKey() {
return this.__D;
}
get publicKey() {
if (!this.__Q) {
// It is not possible for both `__Q` and `__D` to be `undefined` at the same time.
// The factory methods guard for this.
const p = ecc.pointFromScalar(this.__D, this.compressed);
// It is not possible for `p` to be null.
// `fromPrivateKey()` checks that `__D` is a valid scalar.
this.__Q = p;
}
return this.__Q;
}
toWIF() {
if (!this.__D) throw new Error('Missing private key');
return wif.encode({
compressed: this.compressed,
privateKey: this.__D,
version: this.network.wif,
});
}
tweak(t) {
if (this.privateKey) return this.tweakFromPrivateKey(t);
return this.tweakFromPublicKey(t);
}
sign(hash, lowR) {
if (!this.__D) throw new Error('Missing private key');
if (lowR === undefined) lowR = this.lowR;
if (lowR === false) {
return ecc.sign(hash, this.__D);
} else {
let sig = ecc.sign(hash, this.__D);
const extraData = new Uint8Array(32);
let counter = 0;
// if first try is lowR, skip the loop
// for second try and on, add extra entropy counting up
while (sig[0] > 0x7f) {
counter++;
tools.writeUInt32(extraData, 0, counter, 'LE');
sig = ecc.sign(hash, this.__D, extraData);
}
return sig;
}
}
signSchnorr(hash) {
if (!this.privateKey) throw new Error('Missing private key');
if (!ecc.signSchnorr)
throw new Error('signSchnorr not supported by ecc library');
return ecc.signSchnorr(hash, this.privateKey);
}
verify(hash, signature) {
return ecc.verify(hash, this.publicKey, signature);
}
verifySchnorr(hash, signature) {
if (!ecc.verifySchnorr)
throw new Error('verifySchnorr not supported by ecc library');
return ecc.verifySchnorr(hash, this.publicKey.subarray(1, 33), signature);
}
tweakFromPublicKey(t) {
const xOnlyPubKey = toXOnly(this.publicKey);
const tweakedPublicKey = ecc.xOnlyPointAddTweak(xOnlyPubKey, t);
if (!tweakedPublicKey || tweakedPublicKey.xOnlyPubkey === null)
throw new Error('Cannot tweak public key!');
const parityByte = Uint8Array.from([
tweakedPublicKey.parity === 0 ? 0x02 : 0x03,
]);
return fromPublicKey(
tools.concat([parityByte, tweakedPublicKey.xOnlyPubkey]),
{
network: this.network,
compressed: this.compressed,
},
);
}
tweakFromPrivateKey(t) {
const hasOddY =
this.publicKey[0] === 3 ||
(this.publicKey[0] === 4 && (this.publicKey[64] & 1) === 1);
const privateKey = hasOddY
? ecc.privateNegate(this.privateKey)
: this.privateKey;
const tweakedPrivateKey = ecc.privateAdd(privateKey, t);
if (!tweakedPrivateKey) throw new Error('Invalid tweaked private key!');
return fromPrivateKey(tweakedPrivateKey, {
network: this.network,
compressed: this.compressed,
});
}
}
return {
isPoint,
fromPrivateKey,
fromPublicKey,
fromWIF,
makeRandom,
};
}