-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.js
More file actions
687 lines (607 loc) · 28.3 KB
/
Copy pathanalyzer.js
File metadata and controls
687 lines (607 loc) · 28.3 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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// analyzer.js — Chain detection, validation, and structural breakdown
// Depends on: crypto.js, icons.js
'use strict';
// ============================================================================
// Chain / format definitions
// ============================================================================
const EVM_CHAINS = [
'Ethereum', 'Polygon', 'Arbitrum', 'Optimism', 'Base',
'BSC (BNB Chain)', 'Avalanche C-Chain', 'Fantom', 'Gnosis',
'zkSync Era', 'Linea', 'Scroll', 'Mantle', 'Celo',
];
// Base58Check version byte → chain/type mapping.
// Each entry: { chain, type, eduKey, network }
const BASE58_VERSIONS = {
0x00: { chain: 'Bitcoin', type: 'P2PKH (Pay-to-Public-Key-Hash)', eduKey: 'btc_p2pkh', network: 'Mainnet' },
0x05: { chain: 'Bitcoin', type: 'P2SH (Pay-to-Script-Hash)', eduKey: 'btc_p2sh', network: 'Mainnet' },
0x6f: { chain: 'Bitcoin', type: 'P2PKH (Testnet)', eduKey: 'btc_p2pkh', network: 'Testnet' },
0xc4: { chain: 'Bitcoin', type: 'P2SH (Testnet)', eduKey: 'btc_p2sh', network: 'Testnet' },
0x30: { chain: 'Litecoin', type: 'P2PKH (Pay-to-Public-Key-Hash)', eduKey: 'ltc', network: 'Mainnet' },
0x32: { chain: 'Litecoin', type: 'P2SH (Pay-to-Script-Hash)', eduKey: 'ltc', network: 'Mainnet' },
0x41: { chain: 'Tron', type: 'Tron Address', eduKey: 'tron', network: 'Mainnet' },
};
// Bech32/Bech32m HRP → chain config.
// segwit: true means it uses witness program structure (version byte + program).
// segwit: false means raw bech32 payload (no witness version).
// encoding: expected bech32 variant for non-segwit chains (segwit chains enforce this via witness version)
const BECH32_HRPS = {
bc: { chain: 'Bitcoin', network: 'Mainnet', segwit: true },
tb: { chain: 'Bitcoin', network: 'Testnet', segwit: true },
ltc: { chain: 'Litecoin', network: 'Mainnet', segwit: true },
tltc: { chain: 'Litecoin', network: 'Testnet', segwit: true },
iota: { chain: 'IOTA', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'IOTA Stardust Address (Legacy)', eduKey: 'iota_stardust' },
cosmos: { chain: 'Cosmos Hub', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Cosmos Hub Address', eduKey: 'cosmos' },
osmo: { chain: 'Osmosis', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Osmosis Address', eduKey: 'cosmos' },
celestia: { chain: 'Celestia', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Celestia Address', eduKey: 'cosmos' },
terra: { chain: 'Terra', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Terra Address', eduKey: 'cosmos' },
akash: { chain: 'Akash', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Akash Address', eduKey: 'cosmos' },
inj: { chain: 'Injective', network: 'Mainnet', segwit: false, encoding: 'bech32', type: 'Injective Address', eduKey: 'cosmos' },
};
const EDUCATION = {
eth: {
title: 'Ethereum / EVM Address',
description: 'A 20-byte account identifier used across all EVM-compatible chains. Derived from the last 20 bytes of the Keccak-256 hash of the public key.',
introduced: 'Ethereum launch (2015). EIP-55 mixed-case checksum introduced in 2016.',
scriptType: 'Externally Owned Account (EOA) or smart contract — indistinguishable from the address alone.',
},
btc_p2pkh: {
title: 'Bitcoin P2PKH (Pay-to-Public-Key-Hash)',
description: 'The original Bitcoin address format. Encodes a RIPEMD-160(SHA-256(pubkey)) hash using Base58Check.',
introduced: 'Bitcoin genesis (2009). Defined retroactively in BIP-13.',
scriptType: 'Locks funds to a single public key hash. Requires a signature from the corresponding private key to spend.',
},
btc_p2sh: {
title: 'Bitcoin P2SH (Pay-to-Script-Hash)',
description: 'Encodes a hash of an arbitrary script. Commonly used for multisig wallets and wrapped SegWit (P2SH-P2WPKH).',
introduced: 'BIP-16 (2012).',
scriptType: 'Locks funds to a script hash. The spending transaction must provide the full script and satisfy its conditions.',
},
btc_p2wpkh: {
title: 'Bitcoin P2WPKH (Pay-to-Witness-Public-Key-Hash)',
description: 'Native SegWit v0 address for single-key payments. Uses bech32 encoding for better error detection and QR friendliness.',
introduced: 'BIP-141 (SegWit, 2017), BIP-173 (bech32 encoding).',
scriptType: 'Witness program containing a 20-byte public key hash. Signature goes in the segregated witness area.',
},
btc_p2wsh: {
title: 'Bitcoin P2WSH (Pay-to-Witness-Script-Hash)',
description: 'Native SegWit v0 address for script-based payments. The 32-byte payload is a SHA-256 hash of the witness script.',
introduced: 'BIP-141 (2017), BIP-173 (bech32 encoding).',
scriptType: 'Witness program containing a 32-byte script hash (SHA-256). Used for multisig and complex scripts.',
},
btc_taproot: {
title: 'Bitcoin Taproot (P2TR)',
description: 'SegWit v1 address using Schnorr signatures and MAST (Merkelized Abstract Syntax Trees). Enables more private and efficient smart contracts.',
introduced: 'BIP-341, BIP-342 (Taproot, activated November 2021). Uses bech32m encoding per BIP-350.',
scriptType: 'Tweaked public key. Can be spent with a single Schnorr signature (key path) or by revealing a script branch (script path).',
},
iota_stardust: {
title: 'IOTA Stardust Address (Legacy)',
description: 'Bech32-encoded address from the IOTA Stardust era with the "iota" human-readable part. IOTA Rebased has deprecated this format in favor of 0x-prefixed 32-byte hex addresses. Legacy Stardust addresses may still be encountered during migration.',
introduced: 'IOTA Chrysalis / Stardust (TIP-0011). Deprecated in IOTA Rebased.',
scriptType: 'UTXO address on the IOTA Stardust network.',
},
iota_rebased: {
title: 'IOTA Rebased Address',
description: 'IOTA Rebased uses 0x-prefixed 32-byte hex addresses, the same format as Sui and other Move-based chains. The address is derived from the BLAKE2b-256 hash of the Ed25519 public key.',
introduced: 'IOTA Rebased (Move-based ledger, 2024).',
scriptType: 'Account address on the IOTA Rebased / Move-based network.',
},
cosmos: {
title: 'Cosmos SDK Address',
description: 'Bech32-encoded address used across the Cosmos ecosystem (Cosmos Hub, Osmosis, Celestia, etc.). Each chain uses a unique HRP but the same underlying format: a 20-byte account hash.',
introduced: 'Cosmos SDK. Cosmos Hub mainnet launched March 2019.',
scriptType: 'Account address derived from the secp256k1 public key via SHA-256 + RIPEMD-160.',
},
ltc: {
title: 'Litecoin Address',
description: 'Litecoin uses address formats very similar to Bitcoin. Legacy addresses use Base58Check with different version bytes (0x30 for P2PKH, 0x32 for P2SH). SegWit addresses use bech32/bech32m with the "ltc" HRP.',
introduced: 'Litecoin launched October 2011. SegWit activated May 2017.',
scriptType: 'Same script types as Bitcoin (P2PKH, P2SH, P2WPKH, P2WSH, P2TR) adapted for the Litecoin network.',
},
tron: {
title: 'Tron Address',
description: 'Tron addresses use Base58Check encoding with version byte 0x41. The underlying format is a 20-byte account identifier, similar to Ethereum but with a different encoding.',
introduced: 'Tron mainnet launched June 2018.',
scriptType: 'Account address. Tron uses an account-based model similar to Ethereum.',
},
solana: {
title: 'Solana Address',
description: 'Solana addresses are 32-byte Ed25519 public keys encoded in plain Base58 (no checksum). This makes them shorter but means typos cannot be detected by the encoding alone.',
introduced: 'Solana mainnet beta launched March 2020.',
scriptType: 'Ed25519 public key. Can represent a wallet, program (smart contract), or program-derived address (PDA).',
},
};
// ============================================================================
// Analyzer: detect, validate, and break down an address
// ============================================================================
function analyzeAddress(input) {
const trimmed = input.trim();
if (!trimmed) return [];
const results = [];
// Try each detection path
const detectors = [tryEthereum, tryMoveHex, tryRawHex, tryBase58Check, tryBech32, trySolana];
for (const detect of detectors) {
const result = detect(trimmed);
if (result) results.push(result);
}
return results;
}
// ============================================================================
// Ethereum / EVM detection
// ============================================================================
function tryEthereum(addr) {
if (!/^0x[0-9a-fA-F]{40}$/i.test(addr)) return null;
const hex = addr.slice(2);
const bytes = hexToBytes(hex);
const checksumResult = EIP55.validateChecksum(addr);
let status, statusText, errors = [];
if (checksumResult.hasChecksum) {
if (checksumResult.valid) {
status = 'valid';
statusText = 'Valid (EIP-55 checksum verified)';
} else {
status = 'invalid';
statusText = 'Invalid EIP-55 checksum';
errors.push(`Mixed-case address does not match EIP-55 checksum. Expected: ${checksumResult.expected}`);
}
} else {
status = 'valid';
statusText = addr.includes('0X') ? 'Valid (all uppercase, no checksum)' : 'Valid (all lowercase, no checksum)';
}
const checksummed = EIP55.checksumAddress(addr);
return {
chain: 'Ethereum',
type: 'EVM Address (20 bytes)',
status,
statusText,
errors,
segments: [
{ text: '0x', label: 'Prefix', class: 'seg-prefix' },
{ text: hex, label: 'Address (20 bytes)', class: 'seg-payload' },
],
details: [
{ label: 'Encoding', value: 'Hexadecimal with 0x prefix', isText: true },
{ label: 'Address bytes', value: bytesToHex(bytes) },
{ label: 'Byte length', value: `${bytes.length} bytes (160 bits)`, isText: true },
{ label: 'EIP-55 checksum', value: checksumResult.hasChecksum
? (checksumResult.valid ? 'Valid' : 'Invalid')
: 'Not present (single-case)', isText: true },
{ label: 'Checksummed form', value: checksummed },
],
education: EDUCATION.eth,
alsoValid: EVM_CHAINS.slice(1), // exclude Ethereum (it's the primary)
};
}
// ============================================================================
// Raw hex (40 chars, no 0x) — flag as possible Ethereum
// ============================================================================
function tryRawHex(addr) {
if (!/^[0-9a-fA-F]{40}$/.test(addr)) return null;
// Don't show this if we already matched as 0x-prefixed
if (addr.startsWith('0x') || addr.startsWith('0X')) return null;
return {
chain: 'Possibly Ethereum/EVM',
type: 'Raw hex (40 characters)',
status: 'warning',
statusText: 'Ambiguous — missing 0x prefix',
errors: ['This looks like a 40-character hex string. If this is an Ethereum address, it should be prefixed with "0x".'],
segments: [
{ text: addr, label: 'Hex data (20 bytes)', class: 'seg-payload' },
],
details: [
{ label: 'Interpretation', value: 'Could be an Ethereum/EVM address without the 0x prefix', isText: true },
{ label: 'With prefix', value: '0x' + addr },
{ label: 'Byte length', value: '20 bytes (160 bits)', isText: true },
],
education: EDUCATION.eth,
};
}
// ============================================================================
// IOTA Rebased / Sui (0x-prefixed 32-byte hex address)
// ============================================================================
const MOVE_CHAINS = ['Sui'];
function tryMoveHex(addr) {
if (!/^0x[0-9a-fA-F]{64}$/i.test(addr)) return null;
const hex = addr.slice(2);
const bytes = hexToBytes(hex);
return {
chain: 'IOTA Rebased',
type: 'Move Address (32 bytes)',
status: 'valid',
statusText: 'Valid (0x-prefixed, 32-byte hex)',
errors: [],
segments: [
{ text: '0x', label: 'Prefix', class: 'seg-prefix' },
{ text: hex, label: 'Address (32 bytes)', class: 'seg-payload' },
],
details: [
{ label: 'Encoding', value: 'Hexadecimal with 0x prefix', isText: true },
{ label: 'Address bytes', value: bytesToHex(bytes) },
{ label: 'Byte length', value: `${bytes.length} bytes (${bytes.length * 8} bits)`, isText: true },
],
education: EDUCATION.iota_rebased,
alsoValid: MOVE_CHAINS,
};
}
// ============================================================================
// Base58Check addresses (Bitcoin P2PKH/P2SH, Tron, Litecoin, etc.)
// ============================================================================
function tryBase58Check(addr) {
// Quick filter: base58 alphabet, reasonable length
if (!/^[1-9A-HJ-NP-Za-km-z]{25,35}$/.test(addr)) return null;
const decoded = Base58.decodeCheck(addr);
if (!decoded.valid && !decoded.version && decoded.version !== 0) {
return null;
}
const info = BASE58_VERSIONS[decoded.version];
if (!info) return null;
const { chain, type, eduKey, network } = info;
const status = decoded.valid ? 'valid' : 'invalid';
const statusText = decoded.valid ? 'Valid (checksum verified)' : 'Invalid checksum';
const errors = decoded.valid ? [] : [decoded.error];
const versionHex = decoded.version.toString(16).padStart(2, '0');
const payloadHex = decoded.payload ? bytesToHex(decoded.payload) : '?';
const checksumHex = decoded.checksum ? bytesToHex(decoded.checksum) : '?';
const rawHex = decoded.raw ? bytesToHex(decoded.raw) : '';
return {
chain,
type: type + (network === 'Testnet' ? ' — Testnet' : ''),
status,
statusText,
errors,
segments: [
{ text: addr.charAt(0), label: 'Version prefix', class: 'seg-version' },
{ text: addr.substring(1, addr.length - 6), label: 'Payload (encoded)', class: 'seg-payload' },
{ text: addr.substring(addr.length - 6), label: 'Checksum (encoded)', class: 'seg-checksum' },
],
details: [
{ label: 'Encoding', value: 'Base58Check', isText: true },
{ label: 'Network', value: network, isText: true },
{ label: 'Version byte', value: `0x${versionHex} (${decoded.version})` },
{ label: 'Payload hash', value: payloadHex },
{ label: 'Payload length', value: decoded.payload ? `${decoded.payload.length} bytes (${decoded.payload.length * 8} bits)` : '?', isText: true },
{ label: 'Checksum (4 bytes)', value: checksumHex },
...(decoded.expectedChecksum ? [{ label: 'Expected checksum', value: bytesToHex(decoded.expectedChecksum) }] : []),
{ label: 'Full decoded hex', value: rawHex },
],
education: EDUCATION[eduKey],
};
}
// ============================================================================
// Bech32/Bech32m addresses (Bitcoin SegWit, IOTA, Cosmos, Litecoin, etc.)
// ============================================================================
// Classify a segwit witness program by version and length.
// For non-Bitcoin chains (e.g. Litecoin), uses the chain's own eduKey.
function classifySegwitProgram(witnessVersion, programLen, config) {
const fallbackEduKey = config.eduKey || (witnessVersion >= 1 ? 'btc_taproot' : 'btc_p2wpkh');
if (witnessVersion === 0 && programLen === 20) return { type: 'P2WPKH (SegWit v0)', eduKey: config.eduKey || 'btc_p2wpkh' };
if (witnessVersion === 0 && programLen === 32) return { type: 'P2WSH (SegWit v0)', eduKey: config.eduKey || 'btc_p2wsh' };
if (witnessVersion === 1 && programLen === 32) return { type: 'P2TR (Taproot, SegWit v1)', eduKey: config.eduKey || 'btc_taproot' };
return { type: `SegWit v${witnessVersion} (${programLen}-byte program)`, eduKey: fallbackEduKey };
}
function tryBech32(addr) {
const lower = addr.toLowerCase();
// Find which registered HRP matches
let hrp = null, config = null;
for (const [h, cfg] of Object.entries(BECH32_HRPS)) {
if (lower.startsWith(h + '1')) {
hrp = h;
config = cfg;
break;
}
}
if (!config) return null;
// --- Segwit chains (Bitcoin, Litecoin) ---
if (config.segwit) {
const decoded = Bech32.decodeSegwit(hrp, addr);
if (decoded.error) {
return {
chain: config.chain,
type: `SegWit (${config.network})`,
status: 'invalid',
statusText: 'Invalid',
errors: [decoded.error],
segments: [
{ text: lower, label: 'Invalid bech32', class: 'seg-payload' },
],
details: [
{ label: 'Error', value: decoded.error, isText: true },
{ label: 'Encoding', value: 'bech32 / bech32m', isText: true },
{ label: 'Network', value: config.network, isText: true },
],
education: EDUCATION.btc_p2wpkh,
};
}
const wv = decoded.witnessVersion;
const progHex = bytesToHex(decoded.program);
const progLen = decoded.program.length;
const { type, eduKey } = classifySegwitProgram(wv, progLen, config);
const sepIdx = lower.lastIndexOf('1');
const hrpPart = lower.substring(0, sepIdx);
const dataPart = lower.substring(sepIdx + 1);
const witnessChar = dataPart.charAt(0);
const payloadChars = dataPart.substring(1, dataPart.length - 6);
const checksumChars = dataPart.substring(dataPart.length - 6);
return {
chain: config.chain,
type: type + (config.network === 'Testnet' ? ' — Testnet' : ''),
status: 'valid',
statusText: `Valid (${decoded.encoding} checksum verified)`,
errors: [],
segments: [
{ text: hrpPart, label: `HRP ("${hrp}")`, class: 'seg-hrp' },
{ text: '1', label: 'Separator', class: 'seg-separator' },
{ text: witnessChar, label: `Witness v${wv}`, class: 'seg-witness' },
{ text: payloadChars, label: 'Program (encoded)', class: 'seg-payload' },
{ text: checksumChars, label: 'Checksum', class: 'seg-checksum' },
],
details: [
{ label: 'Encoding', value: decoded.encoding === 'bech32m' ? 'Bech32m (BIP-350)' : 'Bech32 (BIP-173)', isText: true },
{ label: 'Network', value: config.network, isText: true },
{ label: 'HRP', value: hrp },
{ label: 'Witness version', value: `${wv}`, isText: true },
{ label: 'Program', value: progHex },
{ label: 'Program length', value: `${progLen} bytes (${progLen * 8} bits)`, isText: true },
{ label: 'Checksum (6 chars)', value: checksumChars },
],
education: EDUCATION[eduKey],
};
}
// --- Non-segwit bech32 chains (IOTA, Cosmos, etc.) ---
const decoded = Bech32.decode(addr);
if (decoded.error) {
return {
chain: config.chain,
type: config.type || `${config.chain} Address`,
status: 'invalid',
statusText: 'Invalid',
errors: [decoded.error],
segments: [
{ text: lower, label: 'Invalid bech32', class: 'seg-payload' },
],
details: [
{ label: 'Error', value: decoded.error, isText: true },
],
education: EDUCATION[config.eduKey],
};
}
// Enforce expected encoding variant if specified
if (config.encoding && decoded.encoding !== config.encoding) {
return {
chain: config.chain,
type: config.type || `${config.chain} Address`,
status: 'invalid',
statusText: 'Invalid',
errors: [`${config.chain} expects ${config.encoding} encoding, but this address uses ${decoded.encoding}.`],
segments: [
{ text: lower, label: `Wrong encoding (${decoded.encoding})`, class: 'seg-payload' },
],
details: [
{ label: 'Expected encoding', value: config.encoding, isText: true },
{ label: 'Actual encoding', value: decoded.encoding, isText: true },
],
education: EDUCATION[config.eduKey],
};
}
const payload = Bech32.convertBits(decoded.data, 5, 8, false);
const payloadHex = payload ? bytesToHex(new Uint8Array(payload)) : '?';
const payloadLen = payload ? payload.length : '?';
const sepIdx = lower.lastIndexOf('1');
const hrpPart = lower.substring(0, sepIdx);
const dataPart = lower.substring(sepIdx + 1);
const payloadChars = dataPart.substring(0, dataPart.length - 6);
const checksumChars = dataPart.substring(dataPart.length - 6);
return {
chain: config.chain,
type: config.type || `${config.chain} Address`,
status: 'valid',
statusText: `Valid (${decoded.encoding} checksum verified)`,
errors: [],
segments: [
{ text: hrpPart, label: `HRP ("${hrp}")`, class: 'seg-hrp' },
{ text: '1', label: 'Separator', class: 'seg-separator' },
{ text: payloadChars, label: 'Payload (encoded)', class: 'seg-payload' },
{ text: checksumChars, label: 'Checksum', class: 'seg-checksum' },
],
details: [
{ label: 'Encoding', value: decoded.encoding === 'bech32m' ? 'Bech32m' : 'Bech32', isText: true },
{ label: 'HRP', value: decoded.hrp },
{ label: 'Payload', value: payloadHex },
{ label: 'Payload length', value: `${payloadLen} bytes`, isText: true },
{ label: 'Checksum (6 chars)', value: checksumChars },
],
education: EDUCATION[config.eduKey],
};
}
// ============================================================================
// Solana (plain Base58, 32-byte Ed25519 public key, no checksum)
// ============================================================================
function trySolana(addr) {
// Solana addresses are 32-44 characters of base58 (no prefix, no checksum)
if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr)) return null;
// Reject if already matched as base58check (Bitcoin/Tron/Litecoin)
const b58check = Base58.decodeCheck(addr);
if (b58check.valid && BASE58_VERSIONS[b58check.version]) return null;
const decoded = Base58.decode(addr);
if (!decoded || decoded.length !== 32) return null;
return {
chain: 'Solana',
type: 'Solana Address (Ed25519)',
status: 'warning',
statusText: 'Likely valid (no checksum — typos cannot be detected)',
errors: [],
segments: [
{ text: addr, label: 'Public key (base58)', class: 'seg-payload' },
],
details: [
{ label: 'Encoding', value: 'Base58 (no checksum)', isText: true },
{ label: 'Public key', value: bytesToHex(decoded) },
{ label: 'Byte length', value: `${decoded.length} bytes (${decoded.length * 8} bits)`, isText: true },
{ label: 'Note', value: 'Solana uses plain Base58 without a checksum. Any 32-byte base58 string is structurally valid.', isText: true },
],
education: EDUCATION.solana,
};
}
// ============================================================================
// UI Controller
// ============================================================================
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('address-input');
const clearBtn = document.getElementById('clear-btn');
const resultsContainer = document.getElementById('results');
let debounceTimer = null;
function onInput() {
clearBtn.classList.toggle('visible', input.value.length > 0);
clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
updateResults(input.value);
}, 150);
}
input.addEventListener('input', onInput);
input.addEventListener('paste', () => {
// Run analysis immediately on paste (after the value updates)
setTimeout(() => {
clearBtn.classList.toggle('visible', input.value.length > 0);
updateResults(input.value);
}, 0);
});
clearBtn.addEventListener('click', () => {
input.value = '';
clearBtn.classList.remove('visible');
resultsContainer.innerHTML = '';
input.focus();
});
// Example chip clicks + inject icons
document.querySelectorAll('.example-chip').forEach(chip => {
if (chip.dataset.chain) {
chip.insertAdjacentHTML('afterbegin', ChainIcons.icon(chip.dataset.chain, 'chip-icon'));
}
chip.addEventListener('click', () => {
input.value = chip.dataset.address;
clearBtn.classList.add('visible');
updateResults(input.value);
input.focus();
});
});
// URL parameter support
const urlParams = new URLSearchParams(window.location.search);
const addrParam = urlParams.get('address');
if (addrParam) {
input.value = addrParam;
clearBtn.classList.add('visible');
updateResults(addrParam);
}
function updateResults(value) {
const trimmed = value.trim();
if (!trimmed) {
resultsContainer.innerHTML = '';
return;
}
const results = analyzeAddress(trimmed);
if (results.length === 0) {
resultsContainer.innerHTML = renderNoMatch(trimmed);
return;
}
resultsContainer.innerHTML = results.map(renderResult).join('');
}
});
// ============================================================================
// Rendering
// ============================================================================
function renderNoMatch(input) {
const sanitized = escapeHtml(input);
return `
<div class="result-card error-card">
<div class="result-header">
<span class="result-chain">Unknown Format</span>
<span class="result-status invalid">✗ Not recognized</span>
</div>
<p class="error-message">
"${sanitized}" does not match any supported address format.
</p>
<div class="details" style="margin-top: 0.75rem">
<div class="detail-row">
<span class="detail-label">Input length</span>
<span class="detail-value text">${input.length} characters</span>
</div>
<div class="detail-row">
<span class="detail-label">Hint</span>
<span class="detail-value text">Try one of the example addresses above, or paste a full blockchain address.</span>
</div>
</div>
</div>`;
}
function renderResult(result) {
const statusIcon = result.status === 'valid' ? '✓'
: result.status === 'warning' ? '⚠'
: '✗';
const errorsHtml = result.errors.length > 0
? result.errors.map(e => `<p class="error-message">${escapeHtml(e)}</p>`).join('')
: '';
const segmentsHtml = result.segments
.map(s => `<span class="seg ${s.class}" title="${escapeHtml(s.label)}">${escapeHtml(s.text)}</span>`)
.join('');
const legendHtml = result.segments
.map(s => {
const color = getComputedSegColor(s.class);
return `<span class="legend-item"><span class="legend-swatch" style="background:${color}"></span>${escapeHtml(s.label)}</span>`;
})
.join('');
const detailsHtml = result.details
.map(d => `
<div class="detail-row">
<span class="detail-label">${escapeHtml(d.label)}</span>
<span class="detail-value${d.isText ? ' text' : ''}">${escapeHtml(String(d.value))}</span>
</div>`)
.join('');
const alsoValidHtml = result.alsoValid && result.alsoValid.length > 0
? `<div class="also-valid"><strong>Also valid on:</strong> ${escapeHtml(result.alsoValid.join(', '))}</div>`
: '';
const eduHtml = result.education
? `<details class="education">
<summary>Learn more about this address type</summary>
<div class="edu-content">
<p><strong>${escapeHtml(result.education.title)}</strong></p>
<p>${escapeHtml(result.education.description)}</p>
<p><strong>Introduced:</strong> ${escapeHtml(result.education.introduced)}</p>
<p><strong>Script type:</strong> ${escapeHtml(result.education.scriptType)}</p>
</div>
</details>`
: '';
return `
<div class="result-card${result.status === 'invalid' ? ' error-card' : ''}">
<div class="result-header">
${ChainIcons.icon(result.chain)}<span class="result-chain">${escapeHtml(result.chain)}</span>
<span class="result-type">${escapeHtml(result.type)}</span>
<span class="result-status ${result.status}">${statusIcon} ${escapeHtml(result.statusText)}</span>
</div>
${errorsHtml}
<div class="breakdown">
<div class="breakdown-title">Structural Breakdown</div>
<div class="address-visual">${segmentsHtml}</div>
<div class="segment-legend">${legendHtml}</div>
</div>
<div class="details">
${detailsHtml}
</div>
${alsoValidHtml}
${eduHtml}
</div>`;
}
function getComputedSegColor(className) {
const map = {
'seg-prefix': '#60a5fa',
'seg-version': '#c084fc',
'seg-payload': '#34d399',
'seg-checksum': '#fb923c',
'seg-witness': '#f472b6',
'seg-hrp': '#fbbf24',
'seg-separator': '#94a3b8',
};
return map[className] || '#94a3b8';
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}