-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.js
More file actions
570 lines (490 loc) · 18.2 KB
/
Copy pathcrypto.js
File metadata and controls
570 lines (490 loc) · 18.2 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
// crypto.js — Pure JS implementations of base58check, bech32/bech32m, and keccak-256
// No external dependencies. These are small, well-specified algorithms.
'use strict';
// ============================================================================
// Keccak-256 (used for EIP-55 checksum)
// ============================================================================
// Minimal keccak-256 implementation. Ethereum uses "raw" Keccak-256, NOT SHA3-256
// (which adds domain separation). This distinction matters for EIP-55 checksums.
const Keccak = (() => {
// Round constants for Keccak-f[1600]
const RC = [
[0x00000001, 0x00000000], [0x00008082, 0x00000000],
[0x0000808a, 0x80000000], [0x80008000, 0x80000000],
[0x0000808b, 0x00000000], [0x80000001, 0x00000000],
[0x80008081, 0x80000000], [0x00008009, 0x80000000],
[0x0000008a, 0x00000000], [0x00000088, 0x00000000],
[0x80008009, 0x00000000], [0x8000000a, 0x00000000],
[0x8000808b, 0x00000000], [0x0000008b, 0x80000000],
[0x00008089, 0x80000000], [0x00008003, 0x80000000],
[0x00008002, 0x80000000], [0x00000080, 0x80000000],
[0x0000800a, 0x00000000], [0x8000000a, 0x80000000],
[0x80008081, 0x80000000], [0x00008080, 0x80000000],
[0x80000001, 0x00000000], [0x80008008, 0x80000000],
];
// Rotation offsets
const ROTC = [
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14,
27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44,
];
// Lane index permutation
const PI = [
10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4,
15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1,
];
function rotl64(lo, hi, n) {
if (n >= 32) {
n -= 32;
[lo, hi] = [hi, lo];
}
if (n === 0) return [lo, hi];
return [
(lo << n) | (hi >>> (32 - n)),
(hi << n) | (lo >>> (32 - n)),
];
}
function keccakF1600(state) {
// state is Uint32Array of length 50 (25 lanes × 2 words each)
const B = new Uint32Array(50);
const C = new Uint32Array(10);
const D = new Uint32Array(10);
for (let round = 0; round < 24; round++) {
// θ step
for (let x = 0; x < 5; x++) {
C[x * 2] = state[x * 2] ^ state[(x + 5) * 2] ^ state[(x + 10) * 2] ^ state[(x + 15) * 2] ^ state[(x + 20) * 2];
C[x * 2 + 1] = state[x * 2 + 1] ^ state[(x + 5) * 2 + 1] ^ state[(x + 10) * 2 + 1] ^ state[(x + 15) * 2 + 1] ^ state[(x + 20) * 2 + 1];
}
for (let x = 0; x < 5; x++) {
const r = rotl64(C[((x + 1) % 5) * 2], C[((x + 1) % 5) * 2 + 1], 1);
D[x * 2] = C[((x + 4) % 5) * 2] ^ r[0];
D[x * 2 + 1] = C[((x + 4) % 5) * 2 + 1] ^ r[1];
}
for (let i = 0; i < 25; i++) {
const x = i % 5;
state[i * 2] ^= D[x * 2];
state[i * 2 + 1] ^= D[x * 2 + 1];
}
// ρ and π steps — walk the lane permutation starting at (1,0),
// rotating each lane and placing it at the π-destination.
B[0] = state[0];
B[1] = state[1];
let curLo = state[1 * 2], curHi = state[1 * 2 + 1];
for (let t = 0; t < 24; t++) {
const newPos = PI[t];
const r = rotl64(curLo, curHi, ROTC[t]);
B[newPos * 2] = r[0];
B[newPos * 2 + 1] = r[1];
curLo = state[newPos * 2];
curHi = state[newPos * 2 + 1];
}
// χ step
for (let y = 0; y < 5; y++) {
for (let x = 0; x < 5; x++) {
const i = (y * 5 + x);
state[i * 2] = B[i * 2] ^ ((~B[((y * 5 + (x + 1) % 5)) * 2]) & B[((y * 5 + (x + 2) % 5)) * 2]);
state[i * 2 + 1] = B[i * 2 + 1] ^ ((~B[((y * 5 + (x + 1) % 5)) * 2 + 1]) & B[((y * 5 + (x + 2) % 5)) * 2 + 1]);
}
}
// ι step
state[0] ^= RC[round][0];
state[1] ^= RC[round][1];
}
}
function keccak256(data) {
// data is Uint8Array
const rate = 136; // (1600 - 256*2) / 8 = 136 bytes for keccak-256
const state = new Uint32Array(50);
// Absorb
let offset = 0;
while (offset + rate <= data.length) {
for (let i = 0; i < rate; i += 4) {
const laneIdx = i >> 2;
// Read little-endian uint32 from data
const v = data[offset + i] |
(data[offset + i + 1] << 8) |
(data[offset + i + 2] << 16) |
(data[offset + i + 3] << 24);
state[laneIdx] ^= v;
}
keccakF1600(state);
offset += rate;
}
// Padding: Keccak uses 0x01 suffix (NOT SHA3's 0x06)
const remaining = data.length - offset;
const padded = new Uint8Array(rate);
for (let i = 0; i < remaining; i++) {
padded[i] = data[offset + i];
}
padded[remaining] = 0x01;
padded[rate - 1] |= 0x80;
for (let i = 0; i < rate; i += 4) {
const laneIdx = i >> 2;
const v = padded[i] |
(padded[i + 1] << 8) |
(padded[i + 2] << 16) |
(padded[i + 3] << 24);
state[laneIdx] ^= v;
}
keccakF1600(state);
// Squeeze 32 bytes
const hash = new Uint8Array(32);
for (let i = 0; i < 32; i += 4) {
const w = state[i >> 2];
hash[i] = w & 0xff;
hash[i + 1] = (w >>> 8) & 0xff;
hash[i + 2] = (w >>> 16) & 0xff;
hash[i + 3] = (w >>> 24) & 0xff;
}
return hash;
}
return { keccak256 };
})();
// ============================================================================
// Base58 / Base58Check (Bitcoin legacy addresses)
// ============================================================================
const Base58 = (() => {
const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
const ALPHABET_MAP = new Map();
for (let i = 0; i < ALPHABET.length; i++) {
ALPHABET_MAP.set(ALPHABET[i], i);
}
function decode(str) {
if (str.length === 0) return new Uint8Array(0);
// Check for invalid characters
for (const ch of str) {
if (!ALPHABET_MAP.has(ch)) {
return null; // invalid character
}
}
// Count leading '1's (they map to leading zero bytes)
let leadingZeros = 0;
for (let i = 0; i < str.length && str[i] === '1'; i++) {
leadingZeros++;
}
// Convert from base58 to a big integer (stored as byte array)
// Max size: rough estimate
const size = Math.ceil(str.length * Math.log(58) / Math.log(256));
const bytes = new Uint8Array(size);
for (let i = 0; i < str.length; i++) {
let carry = ALPHABET_MAP.get(str[i]);
for (let j = size - 1; j >= 0; j--) {
carry += 58 * bytes[j];
bytes[j] = carry & 0xff;
carry >>= 8;
}
}
// Skip leading zeros in the byte array (they come from the computation, not from '1' chars)
let start = 0;
while (start < size && bytes[start] === 0) {
start++;
}
const result = new Uint8Array(leadingZeros + (size - start));
// Leading zeros from '1' characters are already 0 in the Uint8Array
result.set(bytes.subarray(start), leadingZeros);
return result;
}
// SHA-256 using SubtleCrypto is async; we need a sync version for base58check.
// Implement a minimal SHA-256.
function sha256(data) {
// SHA-256 constants
const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const H = new Uint32Array([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
]);
// Pre-processing: padding
const bitLen = data.length * 8;
const padLen = (data.length % 64 < 56) ? (56 - data.length % 64) : (120 - data.length % 64);
const padded = new Uint8Array(data.length + padLen + 8);
padded.set(data);
padded[data.length] = 0x80;
// Length in bits as big-endian 64-bit (we only handle up to 2^32 bits)
const view = new DataView(padded.buffer);
view.setUint32(padded.length - 4, bitLen, false);
const W = new Uint32Array(64);
function rotr(x, n) { return ((x >>> n) | (x << (32 - n))) >>> 0; }
function ch(x, y, z) { return ((x & y) ^ (~x & z)) >>> 0; }
function maj(x, y, z) { return ((x & y) ^ (x & z) ^ (y & z)) >>> 0; }
function sigma0(x) { return (rotr(x, 2) ^ rotr(x, 13) ^ rotr(x, 22)) >>> 0; }
function sigma1(x) { return (rotr(x, 6) ^ rotr(x, 11) ^ rotr(x, 25)) >>> 0; }
function gamma0(x) { return (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) >>> 0; }
function gamma1(x) { return (rotr(x, 17) ^ rotr(x, 19) ^ (x >>> 10)) >>> 0; }
for (let offset = 0; offset < padded.length; offset += 64) {
for (let i = 0; i < 16; i++) {
W[i] = view.getUint32(offset + i * 4, false);
}
for (let i = 16; i < 64; i++) {
W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) >>> 0;
}
let [a, b, c, d, e, f, g, h] = H;
for (let i = 0; i < 64; i++) {
const t1 = (h + sigma1(e) + ch(e, f, g) + K[i] + W[i]) >>> 0;
const t2 = (sigma0(a) + maj(a, b, c)) >>> 0;
h = g; g = f; f = e;
e = (d + t1) >>> 0;
d = c; c = b; b = a;
a = (t1 + t2) >>> 0;
}
H[0] = (H[0] + a) >>> 0;
H[1] = (H[1] + b) >>> 0;
H[2] = (H[2] + c) >>> 0;
H[3] = (H[3] + d) >>> 0;
H[4] = (H[4] + e) >>> 0;
H[5] = (H[5] + f) >>> 0;
H[6] = (H[6] + g) >>> 0;
H[7] = (H[7] + h) >>> 0;
}
const result = new Uint8Array(32);
const rv = new DataView(result.buffer);
for (let i = 0; i < 8; i++) {
rv.setUint32(i * 4, H[i], false);
}
return result;
}
function doubleSha256(data) {
return sha256(sha256(data));
}
// Decode base58check and return { version, payload, checksum, valid, error }
function decodeCheck(str) {
const decoded = decode(str);
if (decoded === null) {
return { valid: false, error: 'Invalid base58 characters' };
}
if (decoded.length < 5) {
return { valid: false, error: 'Too short for base58check (need at least 5 bytes: 1 version + min payload + 4 checksum)' };
}
const payload = decoded.slice(0, decoded.length - 4);
const checksum = decoded.slice(decoded.length - 4);
const computed = doubleSha256(payload);
const checksumValid = checksum[0] === computed[0] &&
checksum[1] === computed[1] &&
checksum[2] === computed[2] &&
checksum[3] === computed[3];
if (!checksumValid) {
return {
valid: false,
error: 'Base58check checksum mismatch',
version: payload[0],
payload: payload.slice(1),
checksum,
expectedChecksum: computed.slice(0, 4),
raw: decoded,
};
}
return {
valid: true,
version: payload[0],
payload: payload.slice(1),
checksum,
raw: decoded,
};
}
return { decode, decodeCheck, sha256, doubleSha256, ALPHABET };
})();
// ============================================================================
// Bech32 / Bech32m (BIP-173, BIP-350)
// ============================================================================
const Bech32 = (() => {
const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
const CHARSET_MAP = new Map();
for (let i = 0; i < CHARSET.length; i++) {
CHARSET_MAP.set(CHARSET[i], i);
}
const BECH32_CONST = 1; // bech32
const BECH32M_CONST = 0x2bc830a3; // bech32m
function polymod(values) {
const GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
let chk = 1;
for (const v of values) {
const b = chk >>> 25;
chk = ((chk & 0x1ffffff) << 5) ^ v;
for (let i = 0; i < 5; i++) {
if ((b >>> i) & 1) chk ^= GEN[i];
}
}
return chk;
}
function hrpExpand(hrp) {
const ret = [];
for (let i = 0; i < hrp.length; i++) ret.push(hrp.charCodeAt(i) >>> 5);
ret.push(0);
for (let i = 0; i < hrp.length; i++) ret.push(hrp.charCodeAt(i) & 31);
return ret;
}
function verifyChecksum(hrp, data) {
const combined = hrpExpand(hrp).concat(data);
const result = polymod(combined);
if (result === BECH32_CONST) return 'bech32';
if (result === BECH32M_CONST) return 'bech32m';
return null;
}
// Decode a bech32/bech32m string
// Returns { hrp, data (5-bit values), encoding } or { error }
function decode(str) {
// Must not have mixed case
if (str !== str.toLowerCase() && str !== str.toUpperCase()) {
return { error: 'Mixed case in bech32 string' };
}
str = str.toLowerCase();
// Find the separator (last '1' character)
const sepIdx = str.lastIndexOf('1');
if (sepIdx < 1) return { error: 'Missing separator or empty HRP' };
if (sepIdx + 7 > str.length) return { error: 'Checksum too short (need 6 characters after data)' };
const hrp = str.substring(0, sepIdx);
const dataStr = str.substring(sepIdx + 1);
// Validate HRP characters
for (const ch of hrp) {
const c = ch.charCodeAt(0);
if (c < 33 || c > 126) return { error: `Invalid HRP character: ${ch}` };
}
// Decode data characters
const data = [];
for (const ch of dataStr) {
if (!CHARSET_MAP.has(ch)) {
return { error: `Invalid bech32 character: '${ch}'` };
}
data.push(CHARSET_MAP.get(ch));
}
const encoding = verifyChecksum(hrp, data);
if (!encoding) {
return { error: 'Invalid bech32/bech32m checksum' };
}
// Strip the 6-character checksum
return {
hrp,
data: data.slice(0, data.length - 6),
checksum: data.slice(data.length - 6),
encoding,
};
}
// Convert from 5-bit groups to 8-bit bytes
function convertBits(data, fromBits, toBits, pad) {
let acc = 0;
let bits = 0;
const result = [];
const maxV = (1 << toBits) - 1;
for (const value of data) {
if (value < 0 || value >= (1 << fromBits)) return null;
acc = (acc << fromBits) | value;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
result.push((acc >>> bits) & maxV);
}
}
if (pad) {
if (bits > 0) {
result.push((acc << (toBits - bits)) & maxV);
}
} else {
if (bits >= fromBits) return null;
if ((acc << (toBits - bits)) & maxV) return null;
}
return result;
}
// Decode a segwit / bech32 witness program
function decodeSegwit(hrp, str) {
const decoded = decode(str);
if (decoded.error) return decoded;
if (decoded.hrp !== hrp) {
return { error: `Expected HRP '${hrp}', got '${decoded.hrp}'` };
}
if (decoded.data.length < 1) {
return { error: 'Empty witness data' };
}
const witnessVersion = decoded.data[0];
if (witnessVersion > 16) {
return { error: `Invalid witness version: ${witnessVersion}` };
}
const program = convertBits(decoded.data.slice(1), 5, 8, false);
if (program === null) {
return { error: 'Invalid padding in witness program' };
}
// BIP-141 length constraints
if (program.length < 2 || program.length > 40) {
return { error: `Invalid witness program length: ${program.length} bytes (must be 2-40)` };
}
// v0 must be exactly 20 or 32 bytes (BIP-141)
if (witnessVersion === 0 && program.length !== 20 && program.length !== 32) {
return { error: `Witness v0 program must be 20 or 32 bytes, got ${program.length}` };
}
// v0 must use bech32, v1+ must use bech32m (BIP-350)
if (witnessVersion === 0 && decoded.encoding !== 'bech32') {
return { error: 'Witness v0 must use bech32 encoding, not bech32m' };
}
if (witnessVersion >= 1 && decoded.encoding !== 'bech32m') {
return { error: `Witness v${witnessVersion} must use bech32m encoding, not bech32` };
}
return {
hrp: decoded.hrp,
witnessVersion,
program: new Uint8Array(program),
encoding: decoded.encoding,
checksum: decoded.checksum,
data5bit: decoded.data,
};
}
return { decode, decodeSegwit, convertBits, CHARSET };
})();
// ============================================================================
// EIP-55 mixed-case checksum for Ethereum addresses
// ============================================================================
const EIP55 = (() => {
function checksumAddress(address) {
// Remove 0x prefix, lowercase
const addr = address.replace(/^0x/i, '').toLowerCase();
// Keccak-256 of the lowercase hex address (as ASCII bytes)
const encoder = new TextEncoder();
const hash = Keccak.keccak256(encoder.encode(addr));
const hashHex = bytesToHex(hash);
let result = '0x';
for (let i = 0; i < 40; i++) {
const hashNibble = parseInt(hashHex[i], 16);
if (hashNibble >= 8) {
result += addr[i].toUpperCase();
} else {
result += addr[i].toLowerCase();
}
}
return result;
}
function validateChecksum(address) {
const addr = address.replace(/^0x/, '');
// If all lowercase or all uppercase, no checksum to validate
if (addr === addr.toLowerCase() || addr === addr.toUpperCase()) {
return { hasChecksum: false, valid: true };
}
// Mixed case — verify EIP-55
const expected = checksumAddress(address);
return {
hasChecksum: true,
valid: address === expected,
expected,
};
}
return { checksumAddress, validateChecksum };
})();
// ============================================================================
// Utility functions
// ============================================================================
function bytesToHex(bytes) {
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
function hexToBytes(hex) {
hex = hex.replace(/^0x/i, '');
if (hex.length % 2 !== 0) hex = '0' + hex;
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
}
return bytes;
}