-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1089 lines (976 loc) · 43 KB
/
Copy pathapp.js
File metadata and controls
1089 lines (976 loc) · 43 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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import init, {
generateRecoveryPhrase,
Builder,
setLogger,
} from './pkg/sia_storage_wasm.js';
// Import registration wizard
import { initRegistrationWizard } from './register.js';
// Import syncer WASM, chain service, and explorer module
import syncerInit, {
connect_and_discover_ip, sync_chain, scan_balance_filtered,
generate_filters, generate_txindex, lookup_txid, lookup_utxos,
listen_for_relays, sync_headers, explore_query,
scan_wallet_utxos,
generate_mnemonic, mnemonic_to_entropy, entropy_to_mnemonic,
encrypt_entropy, decrypt_entropy, derive_addresses,
derive_manifest_info,
build_private_manifest_transaction, build_public_manifest_transaction,
build_channel_manifest_transaction, build_group_manifest_transaction,
open_private_manifest, open_channel_manifest, open_group_manifest,
build_v2_transaction, broadcast_v2_transaction,
compute_utxo_proofs, v2_output_id, attestation_key_hash,
} from './pkg/syncer_wasm.js';
import { init as chainInit, onChange as chainOnChange, getSyncState, getEnabledNetworks, getNetworkConfig, getGenesisHex, getAttestationIndexUrl, getActiveNetwork, setActiveNetwork, getRelayState, getMempool, getMempoolTransactions, clearMempool, loadAttestationEntries, exploreQuery as chainExploreQuery, isReady } from './chain.js';
import { initExplorer, explore as explorerQuery } from './explorer.js';
import { initSyncerConfig } from './syncer-config.js';
import { createNetSelector } from './net-selector.js';
// Extracted modules
import { _dbg, _dbgWarn, _esc, hex, fromHex, randomHex } from './utils.js';
import { initKdfWorker } from './kdf.js';
import {
getWalletEntropy, walletUpdateUI, walletResetLockTimer, walletLock,
walletDbLoad, walletScanUtxos, walletEncryptAndSave, walletLoadAndDecrypt,
walletGenerateSeed, walletExportSeed, walletDeriveAddresses, walletDelete,
walletSaveResultAsJson,
} from './wallet.js';
import {
connectSdk, webcodecStream, transmuxAndStream, getUrl, getKeyHex,
} from './config.js';
import { initDownloadUI } from './download-ui.js';
import { initUploadUI } from './upload-ui.js';
import { initUploadSiteUI } from './upload-site-ui.js';
import { initUpdateSiteUI } from './update-site-ui.js';
import { initObjectsUI } from './objects-ui.js';
import { initAccountUI } from './account-ui.js';
import { loadContentWithAutoDetect } from './browser.js';
import { setLoadContentHandler as setManifestLoadContent } from './manifest.js';
import {
PANEL_URLS, URL_TO_PANEL, PANEL_TITLES,
tabs, activeTabId, streamingTabId, loadContentInProgress,
activePanel, lastBrowserUrl,
setLoadContentHandler, setLoadContentInProgress, setStreamingTabId, setLastBrowserUrl, setActivePanel,
saveTabState, loadTabState,
createTab, activateTab, closeTab, renderTabBar,
getActiveTab, getActiveTabIframe, findTabByIframeWindow,
openOrActivateInternalTab, getOrCreateActiveBrowserTab,
updateAddressBarForTab, highlightActiveMenuItem,
updateConnectionStatus, setBrowserView,
pushTabNav, updateNavButtons, isNavInProgress, setNavInProgress,
goBack, navigateTabNavEntry,
} from './tabs.js';
// Debug helpers (accessible from console)
window._dbg = { getMempool, getMempoolTransactions };
// Check browser compatibility on page load
window.addEventListener('DOMContentLoaded', () => {
// Register download streaming Service Worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('./sw-download.js').catch(err => {
console.warn('SW registration failed:', err);
});
}
_dbg('🌐 Browser compatibility check:');
_dbg(' WebTransport:', typeof WebTransport !== 'undefined' ? '✅ Available' : '❌ Not available');
_dbg(' Secure context:', window.isSecureContext ? '✅ Yes' : '❌ No (requires HTTPS)');
_dbg(' Browser:', navigator.userAgent);
// Safari banner is handled by an inline script in index.html so it
// still shows if any module import fails. Here we only warn about
// non-Safari compat issues.
if (typeof WebTransport === 'undefined') {
const warning = document.createElement('div');
warning.style.cssText = 'position:fixed;top:0;left:0;right:0;background:#dc2626;color:white;padding:1rem;text-align:center;z-index:9999;font-weight:bold;';
warning.innerHTML = '⚠️ WebTransport not supported in this browser. Downloads will fail.<br>Please use Chrome 97+, Edge 97+, or Firefox 114+.';
document.body.prepend(warning);
} else if (!window.isSecureContext) {
const warning = document.createElement('div');
warning.style.cssText = 'position:fixed;top:0;left:0;right:0;background:#dc2626;color:white;padding:1rem;text-align:center;z-index:9999;font-weight:bold;';
warning.innerHTML = '⚠️ Page must be served over HTTPS for WebTransport to work. Use https://localhost or deploy to HTTPS server.';
document.body.prepend(warning);
}
});
// Tab management, nav history, panel URLs → tabs.js
// Wire loadContentWithAutoDetect into tabs.js (async function declarations are hoisted)
setLoadContentHandler(loadContentWithAutoDetect);
// Install the Sia-site postMessage bridge so sandboxed iframes can
// request resources from the SDK. Idempotent if called again.
import('./sia-site.js').then(m => m.initSiaSiteHandler());
// --- Attestation Explorer ---
function initAttestationExplorer() {
const queryEl = document.getElementById('att-query');
const btnEl = document.getElementById('att-btn-search');
const summaryEl = document.getElementById('att-summary');
const resultsEl = document.getElementById('att-results');
const bodyEl = document.getElementById('att-results-body');
if (!queryEl || !btnEl) return;
async function doSearch() {
const raw = queryEl.value.trim();
if (!raw) return;
btnEl.disabled = true;
summaryEl.style.display = 'none';
resultsEl.style.display = 'none';
bodyEl.innerHTML = '';
try {
if (!getAttestationIndexUrl()) {
summaryEl.textContent = 'No attestation index loaded. Sync a network first.';
summaryEl.style.display = 'block';
return;
}
const entries = await loadAttestationEntries();
if (!entries.length) {
summaryEl.textContent = 'Attestation index is empty.';
summaryEl.style.display = 'block';
return;
}
let matches;
let queryType;
const stripped = raw.startsWith('ed25519:') ? raw.slice(8) : raw;
if (/^[0-9a-fA-F]{64}$/.test(stripped)) {
// Pubkey search
const pk = stripped.toLowerCase();
matches = entries.filter(e => e.pubkeyHex === pk);
queryType = 'pubkey';
} else {
// Key string search — hash to 8-byte prefix
const kh = attestation_key_hash(raw).toLowerCase();
matches = entries.filter(e => e.keyHashHex === kh);
queryType = 'key';
}
if (!matches.length) {
summaryEl.textContent = queryType === 'pubkey'
? 'No attestations found for this public key.'
: `No attestations found for key "${raw}".`;
summaryEl.style.display = 'block';
return;
}
// Show most recent first
matches.sort((a, b) => b.height - a.height);
// Unique pubkeys for summary
const uniquePubkeys = new Set(matches.map(m => m.pubkeyHex));
summaryEl.textContent = `${matches.length} attestation${matches.length > 1 ? 's' : ''} found` +
(queryType === 'key' ? ` from ${uniquePubkeys.size} public key${uniquePubkeys.size > 1 ? 's' : ''}` : '') +
'. Fetching details...';
summaryEl.style.display = 'block';
// Build rows with placeholders
const rows = [];
for (const m of matches) {
const tr = document.createElement('tr');
tr.style.cssText = 'border-bottom:1px solid #222;';
const pkFull = 'ed25519:' + m.pubkeyHex;
const pkShort = 'ed25519:' + m.pubkeyHex.slice(0, 8) + '…' + m.pubkeyHex.slice(-6);
const keyCol = queryType === 'key' ? raw : m.keyHashHex.slice(0, 12) + '…';
tr.innerHTML =
`<td style="padding:6px 8px; font-family:monospace; color:#aaa; cursor:pointer;" title="Click to copy: ${_esc(pkFull)}" class="att-pubkey-cell">${_esc(pkShort)}</td>` +
`<td style="padding:6px 8px; text-align:right;"><a href="#" style="color:#60a5fa; text-decoration:none;" class="att-height-link">${_esc(m.height.toLocaleString())}</a></td>` +
`<td class="att-key-cell" style="padding:6px 8px; color:#ccc;">${_esc(keyCol)}</td>` +
`<td class="att-val-cell" style="padding:6px 8px; color:#666; font-size:0.75rem;">loading…</td>`;
tr.querySelector('.att-pubkey-cell').addEventListener('click', () => {
navigator.clipboard.writeText('ed25519:' + m.pubkeyHex).then(() => {
const cell = tr.querySelector('.att-pubkey-cell');
const orig = cell.textContent;
cell.textContent = 'copied!';
cell.style.color = '#4ade80';
setTimeout(() => { cell.textContent = orig; cell.style.color = '#aaa'; }, 1200);
});
});
tr.querySelector('.att-height-link').addEventListener('click', (e) => {
e.preventDefault();
document.getElementById('exp-query').value = String(m.height);
explorerQuery();
});
bodyEl.appendChild(tr);
rows.push({ tr, m });
}
resultsEl.style.display = 'block';
// Fetch blocks to fill in key + value — one fetch per unique height
const uniqueHeights = [...new Set(matches.map(m => m.height))];
const blockCache = {};
let fetched = 0;
for (const h of uniqueHeights) {
try {
const result = await chainExploreQuery(String(h), () => { });
if (result?.type === 'block' && result.block?.v2?.transactions) {
// Collect all attestations from this block
const atts = [];
for (const txn of result.block.v2.transactions) {
for (const att of (txn.attestations || [])) {
atts.push(att);
}
}
blockCache[h] = atts;
}
} catch (e) {
console.warn('Failed to fetch block', h, e);
}
fetched++;
summaryEl.textContent = `${matches.length} attestation${matches.length > 1 ? 's' : ''} found` +
(queryType === 'key' ? ` from ${uniquePubkeys.size} public key${uniquePubkeys.size > 1 ? 's' : ''}` : '') +
`. Fetching details... ${fetched}/${uniqueHeights.length}`;
}
// Fill in key + value from fetched blocks
for (const { tr, m } of rows) {
const atts = blockCache[m.height] || [];
// Match by pubkey (block data has ed25519: prefix)
const match = atts.find(a =>
(a.publicKey || '').replace('ed25519:', '').toLowerCase() === m.pubkeyHex
);
const keyCell = tr.querySelector('.att-key-cell');
const valCell = tr.querySelector('.att-val-cell');
if (match) {
keyCell.textContent = match.key || '—';
let decoded = '';
try { decoded = atob(match.value || ''); } catch (_) { decoded = match.value || ''; }
valCell.textContent = decoded || '—';
valCell.title = decoded;
valCell.style.color = '#aaa';
} else {
valCell.textContent = '—';
}
}
summaryEl.textContent = `${matches.length} attestation${matches.length > 1 ? 's' : ''} found` +
(queryType === 'key' ? ` from ${uniquePubkeys.size} public key${uniquePubkeys.size > 1 ? 's' : ''}` : '') + '.';
} catch (e) {
summaryEl.textContent = 'Error: ' + e;
summaryEl.style.display = 'block';
console.error('Attestation search error:', e);
} finally {
btnEl.disabled = false;
}
}
btnEl.addEventListener('click', doSearch);
queryEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') doSearch(); });
}
// --- Mempool actions ---
function initMempoolActions() {
const clearBtn = document.getElementById('exp-mempool-clear');
const rebroadcastBtn = document.getElementById('exp-mempool-rebroadcast');
const statusEl = document.getElementById('exp-mempool-status');
if (clearBtn) {
clearBtn.addEventListener('click', () => {
const net = getActiveNetwork();
clearMempool(net);
if (statusEl) { statusEl.style.display = 'none'; }
});
}
if (rebroadcastBtn) {
rebroadcastBtn.addEventListener('click', async () => {
const net = getActiveNetwork();
const config = getNetworkConfig(net);
if (!config.peerUrl) {
if (statusEl) {
statusEl.textContent = 'No peer URL configured.';
statusEl.style.color = '#f87171';
statusEl.style.display = 'block';
}
return;
}
const txns = getMempoolTransactions(net);
const broadcastable = txns.filter(t => t.rawJson);
if (!broadcastable.length) {
if (statusEl) {
statusEl.textContent = 'No transactions with raw data to rebroadcast.';
statusEl.style.color = '#f87171';
statusEl.style.display = 'block';
}
return;
}
rebroadcastBtn.disabled = true;
rebroadcastBtn.textContent = 'Broadcasting...';
if (statusEl) {
statusEl.textContent = `Rebroadcasting ${broadcastable.length} transaction${broadcastable.length > 1 ? 's' : ''}...`;
statusEl.style.color = '#888';
statusEl.style.display = 'block';
}
const genesisHex = getGenesisHex(net);
const certHash = config.certHash || undefined;
let ok = 0, fail = 0;
// Build a single transaction set: all broadcastable txns in one RPC call
const txnSet = broadcastable.map(t => JSON.parse(t.rawJson));
try {
await broadcast_v2_transaction(config.peerUrl, genesisHex, JSON.stringify(txnSet), certHash);
ok = broadcastable.length;
} catch (e) {
console.warn('Mempool rebroadcast failed:', e);
fail = broadcastable.length;
}
rebroadcastBtn.disabled = false;
rebroadcastBtn.textContent = 'Rebroadcast';
if (statusEl) {
if (fail === 0) {
statusEl.textContent = `Rebroadcast ${ok} transaction${ok > 1 ? 's' : ''} successfully.`;
statusEl.style.color = '#4ade80';
} else {
statusEl.textContent = `Rebroadcast failed: ${fail} transaction${fail > 1 ? 's' : ''}.`;
statusEl.style.color = '#f87171';
}
statusEl.style.display = 'block';
}
});
}
}
// Gear menu setup (runs after DOM ready)
function initGearMenu() {
const gearBtn = document.getElementById('gear-btn');
const gearMenu = document.getElementById('gear-menu');
if (!gearBtn || !gearMenu) return;
gearBtn.addEventListener('click', (e) => {
e.stopPropagation();
gearMenu.style.display = gearMenu.style.display === 'none' ? 'block' : 'none';
});
document.addEventListener('click', () => {
gearMenu.style.display = 'none';
});
gearMenu.addEventListener('click', (e) => {
e.stopPropagation();
});
document.querySelectorAll('.gear-menu-item').forEach(item => {
item.addEventListener('click', () => {
const panelName = item.dataset.panel;
if (item.disabled) return;
if (panelName === 'register') {
const hasKey = !!localStorage.getItem('app-key');
const hasUrl = !!localStorage.getItem('indexer-url');
if (hasKey || hasUrl) {
if (!confirm('You already have an indexer URL and app key configured. Re-registering will overwrite them. Continue?')) {
gearMenu.style.display = 'none';
return;
}
}
// Initialize wizard handlers if not already done
if (!window._wizardInitialized) {
initRegistrationWizard({
Builder, generateRecoveryPhrase, hex, fromHex,
closeTab, activateTab, tabs,
});
window._wizardInitialized = true;
}
}
openOrActivateInternalTab(panelName);
gearMenu.style.display = 'none';
});
});
// Address bar: detect internal pseudo-URLs on Enter
const chromeBar = document.getElementById('chrome-address-bar');
if (chromeBar) {
chromeBar.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleChromeBarNavigation();
}
});
}
}
window.handleChromeBarNavigation = function handleChromeBarNavigation() {
const bar = document.getElementById('chrome-address-bar');
if (!bar) return;
const url = bar.value.trim();
if (!url) return;
// Check for internal panel pseudo-URLs
const panelName = URL_TO_PANEL[url];
if (panelName) {
openOrActivateInternalTab(panelName);
return;
}
// sialo://homepage — quick alias for the configured Homepage site,
// so users who lose track of it can always type their way back. The
// chrome bar gets the resolved sia-site:// URL so subsequent reloads
// behave like any other sia-site navigation.
if (url === 'sialo://homepage' || url === 'sialo://home') {
bar.value = homepageUrl;
const browserTab = getOrCreateActiveBrowserTab();
browserTab.url = homepageUrl;
browserTab.label = 'Homepage';
setLastBrowserUrl(homepageUrl);
renderTabBar();
loadContentWithAutoDetect();
return;
}
// Detect Sia addresses: 76 hex chars (with checksum) — explorer lookup
// Note: 64 hex chars are treated as object IDs, not addresses
if (/^[0-9a-fA-F]{76}$/.test(url)) {
openOrActivateInternalTab('explorer');
document.getElementById('exp-query').value = url;
explorerQuery();
return;
}
// sia:// content — load into the active browser tab, or create one
const browserTab = getOrCreateActiveBrowserTab();
browserTab.url = url;
browserTab.label = url.length > 30 ? url.substring(0, 30) + '...' : url;
setLastBrowserUrl(url);
bar.value = url; // restore after activateTab may have cleared it
renderTabBar();
loadContentWithAutoDetect();
}
// Safety net for iframe link-click navigation. The sandbox bridge is
// supposed to preventDefault() on sia:// and sia-site:// link clicks
// inside hosted sites and postMessage('sia-navigate') to us. When that
// script fails to load or run (SW not controlling yet, blocked request,
// Firefox Feature-Policy quirk) the default navigation fires and the
// parent's CSP frame-src directive blocks it — with "none of the links
// work" as the user-visible symptom. Catch the CSP violation here and
// route the blocked URL through our normal navigation flow.
window.addEventListener('securitypolicyviolation', (e) => {
if (!e.violatedDirective || !e.violatedDirective.startsWith('frame-src')) return;
const blocked = e.blockedURI || '';
if (!/^(sia|sia-site):\/\//i.test(blocked)) return;
// Firefox can truncate cross-origin blockedURI to origin only.
// If the path is missing (no `/objects/<id>/shared`), redirecting
// would land on an unresolvable bare-host URL; warn instead.
if (!/\/objects\/[0-9a-fA-F]{64}/.test(blocked)) {
_dbgWarn('[csp-fallback] blockedURI truncated by browser, cannot redirect:', blocked);
return;
}
_dbg('[csp-fallback] redirecting blocked frame-src navigation:', blocked);
const bar = document.getElementById('chrome-address-bar');
if (bar) bar.value = blocked;
window.handleChromeBarNavigation();
});
// Streaming download helper — avoids holding the entire file in WASM memory.
// Returns { blob, elapsed } where blob is assembled from streamed chunks.
// Download helpers → download.js
// Upload helpers → upload.js
// Mouse-wheel scrolling over the tab bar pans the tabs horizontally
// instead of the page, so users with many tabs can flick between them
// without hunting for the scrollbar. Trackpad horizontal swipes are
// already native; this only maps vertical-wheel input (deltaY) into
// horizontal scrolling when the bar actually overflows.
{
const tabBar = document.getElementById('tab-bar');
if (tabBar) {
tabBar.addEventListener('wheel', (e) => {
// Only hijack if the tab bar can actually scroll horizontally.
if (tabBar.scrollWidth <= tabBar.clientWidth) return;
// If the user is already scrolling horizontally (trackpad two-finger
// swipe), let the browser handle it natively.
if (Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
if (e.deltaY === 0) return;
e.preventDefault();
tabBar.scrollLeft += e.deltaY;
}, { passive: false });
}
}
// Auto-restore config from localStorage on page load
const urlInput = document.getElementById('cfg-url');
const keyInput = document.getElementById('cfg-key');
const maxDownloadsInput = document.getElementById('cfg-max-downloads');
const maxUploadsInput = document.getElementById('cfg-max-uploads');
const debugLoggingCheckbox = document.getElementById('cfg-debug-logging');
// --- Indexer Profile Management ---
const PROFILES_KEY = 'indexer-profiles';
const profileSelect = document.getElementById('cfg-profile-select');
function loadProfiles() {
try { return JSON.parse(localStorage.getItem(PROFILES_KEY)) || null; } catch { return null; }
}
function saveProfiles(data) {
localStorage.setItem(PROFILES_KEY, JSON.stringify(data));
const active = data.profiles[data.active];
if (active) {
localStorage.setItem('indexer-url', active.url || '');
localStorage.setItem('app-key', active.key || '');
}
}
function migrateToProfiles() {
const existing = loadProfiles();
if (existing && Object.keys(existing.profiles).length > 0) return existing;
const url = localStorage.getItem('indexer-url') || '';
const key = localStorage.getItem('app-key') || '';
const name = url ? new URL(url).hostname : 'default';
const data = { profiles: { [name]: { url, key } }, active: name };
saveProfiles(data);
return data;
}
const objectsProfileSelect = document.getElementById('objects-profile-select');
function renderProfileSelect(data) {
for (const sel of [profileSelect, objectsProfileSelect]) {
sel.innerHTML = '';
for (const name of Object.keys(data.profiles)) {
const opt = document.createElement('option');
opt.value = name;
opt.textContent = name;
if (name === data.active) opt.selected = true;
sel.appendChild(opt);
}
}
}
function activateProfile(data, name) {
data.active = name;
const profile = data.profiles[name] || { url: '', key: '' };
urlInput.value = profile.url || '';
keyInput.value = profile.key || '';
saveProfiles(data);
renderProfileSelect(data);
}
function saveActiveProfile(data) {
if (!data.active) return;
const newUrl = urlInput.value.trim();
const newKey = keyInput.value.trim();
const current = data.profiles[data.active] || {};
// Guard against infinite recursion when a password manager re-injects
// its saved value after a localStorage write and re-fires `input`.
if (current.url === newUrl && current.key === newKey) return;
data.profiles[data.active] = { url: newUrl, key: newKey };
saveProfiles(data);
}
let profileData = migrateToProfiles();
renderProfileSelect(profileData);
activateProfile(profileData, profileData.active);
// Load non-profile settings
const savedMaxDownloads = localStorage.getItem('max-downloads');
const savedMaxUploads = localStorage.getItem('max-uploads');
const savedLogLevel = localStorage.getItem('log-level');
if (savedMaxDownloads) maxDownloadsInput.value = savedMaxDownloads;
if (savedMaxUploads) maxUploadsInput.value = savedMaxUploads;
if (savedLogLevel === 'debug') debugLoggingCheckbox.checked = true;
profileSelect.addEventListener('change', () => {
activateProfile(profileData, profileSelect.value);
});
objectsProfileSelect.addEventListener('change', () => {
activateProfile(profileData, objectsProfileSelect.value);
});
document.getElementById('cfg-profile-add').addEventListener('click', () => {
const name = prompt('Profile name (e.g. indexer hostname):');
if (!name || !name.trim()) return;
const trimmed = name.trim();
if (profileData.profiles[trimmed]) { alert('Profile already exists.'); return; }
profileData.profiles[trimmed] = { url: '', key: '' };
activateProfile(profileData, trimmed);
});
document.getElementById('cfg-profile-delete').addEventListener('click', () => {
const names = Object.keys(profileData.profiles);
if (names.length <= 1) { alert('Cannot delete the only profile.'); return; }
if (!confirm(`Delete profile "${profileData.active}"?`)) return;
delete profileData.profiles[profileData.active];
const remaining = Object.keys(profileData.profiles)[0];
activateProfile(profileData, remaining);
});
// Save URL and key to active profile on input
urlInput.addEventListener('input', () => { saveActiveProfile(profileData); });
keyInput.addEventListener('input', () => { saveActiveProfile(profileData); });
// The registration wizard writes to localStorage and sets the cfg-url /
// cfg-key input values programmatically, which does NOT fire `input`.
// Without this listener the profile entry stays at its old (usually
// empty) values, and on the next page reload activateProfile() writes
// those empty values back over localStorage — the app-key "disappears"
// every reload. Sync the profile from the current input values whenever
// the wizard signals a change.
window.addEventListener('profile-updated', () => { saveActiveProfile(profileData); });
document.getElementById('cfg-key-toggle').addEventListener('click', () => {
const btn = document.getElementById('cfg-key-toggle');
if (keyInput.type === 'password') { keyInput.type = 'text'; btn.textContent = 'hide'; }
else { keyInput.type = 'password'; btn.textContent = 'show'; }
});
maxDownloadsInput.addEventListener('input', () => {
localStorage.setItem('max-downloads', maxDownloadsInput.value);
});
maxUploadsInput.addEventListener('input', () => {
localStorage.setItem('max-uploads', maxUploadsInput.value);
});
debugLoggingCheckbox.addEventListener('change', () => {
const level = debugLoggingCheckbox.checked ? 'debug' : 'info';
localStorage.setItem('log-level', level);
setLogger((msg) => console.log(msg), level);
});
// Browser compatibility checks
(async () => {
const container = document.getElementById('compat-checks');
if (!container) return;
const check = (label, supported, tooltip) => {
const labelEl = document.createElement('div');
labelEl.style.color = '#999';
labelEl.style.fontSize = '0.85rem';
labelEl.textContent = label + ': ';
if (tooltip) {
const tip = document.createElement('span');
tip.className = 'info-tip';
tip.textContent = '\u2139';
const tipText = document.createElement('span');
tipText.className = 'info-tip-text';
tipText.textContent = tooltip;
tip.appendChild(tipText);
labelEl.appendChild(tip);
}
const statusEl = document.createElement('div');
statusEl.style.textAlign = 'right';
statusEl.innerHTML = supported
? '<span style="color:#10b981;">✓ Supported</span>'
: '<span style="color:#ef4444;">✗ Not available</span>';
container.appendChild(labelEl);
container.appendChild(statusEl);
};
check('WebTransport', typeof WebTransport !== 'undefined',
'Required for connecting to Sia hosts. Without this, downloads and uploads will not work.');
check('File System Access API', !!window.showSaveFilePicker,
'Streams large files directly to disk without memory limits. Falls back to Service Worker or in-memory download if unavailable.');
check('WebCodecs', typeof VideoDecoder !== 'undefined',
'Hardware-accelerated streaming video playback. Falls back to Media Source Extensions if unavailable.');
check('Media Source Extensions', typeof MediaSource !== 'undefined',
'Buffered video playback via SourceBuffer. Used as a fallback when WebCodecs is not available.');
})();
// Config helpers, SDK connection → config.js
// Surface boot progress in the #loading overlay so users hitting a hung
// module-init (Firefox-Intel-Mac WASM streaming regressions, SES lockdown
// corrupting intrinsics, etc.) can see where things stall instead of
// staring at a blank page.
function setBootStatus(msg, sub) {
const m = document.getElementById('loading-msg');
const s = document.getElementById('loading-sub');
if (m) m.textContent = msg;
if (s) s.textContent = sub || '';
}
function bootTimeout(promise, label, ms = 30000) {
return Promise.race([
promise,
new Promise((_, reject) => setTimeout(
() => reject(new Error(`${label} timed out after ${ms / 1000}s`)),
ms,
)),
]);
}
async function bootStep(label, sub, fn, timeoutMs) {
setBootStatus(label, sub);
try {
await bootTimeout(Promise.resolve().then(fn), label, timeoutMs);
} catch (e) {
setBootStatus(`Boot failed: ${label}`, e.message || String(e));
throw e;
}
}
await bootStep('Loading storage WASM…', '~1.6 MB', () => init(), 45000);
_dbg('[JS] WASM module initialized successfully');
// Initialize syncer WASM, chain service, and explorer panel
await bootStep('Loading syncer WASM…', null, () => syncerInit(), 45000);
_dbg('[JS] Syncer WASM module initialized');
initKdfWorker();
await chainInit({
connect_and_discover_ip, sync_chain, scan_balance_filtered,
generate_filters, generate_txindex, lookup_txid, lookup_utxos,
listen_for_relays, sync_headers, explore_query, scan_wallet_utxos,
generate_mnemonic, mnemonic_to_entropy, entropy_to_mnemonic,
encrypt_entropy, decrypt_entropy, derive_addresses,
});
initExplorer();
initAttestationExplorer();
initMempoolActions();
initSyncerConfig();
// --- Network status bars (embedded in each blockchain panel) ---
const NET_LABELS = { mainnet: 'Mainnet', zen: 'Zen' };
const netBarSelectors = [];
document.querySelectorAll('.net-bar').forEach(bar => {
// The syncer panel always shows every network (even disabled) — that's
// the page where users enable them. Other panels hide disabled
// networks so the chrome bar stays focused on what's live.
const isSyncerBar = !!bar.closest('#panel-syncer-config');
bar.innerHTML = `
<span class="nb-dot">●</span>
<span class="nb-name" style="cursor:pointer;" title="Open Syncer">Mainnet</span>
<span class="nb-state" style="cursor:pointer;" title="Open Syncer">Disabled</span>
<span class="nb-phase" style="cursor:pointer;" title="Open Syncer"></span>
<span class="nb-relay" style="cursor:pointer;" title="Open Syncer">Relay: off</span>
<span class="nb-sep"></span>
<span style="flex:1;"></span>
<span class="nb-sel-mount"></span>`;
// Click status area to open syncer page
for (const cls of ['.nb-name', '.nb-state', '.nb-phase', '.nb-relay']) {
bar.querySelector(cls).addEventListener('click', () => openOrActivateInternalTab('syncer-config'));
}
const sel = createNetSelector({
mode: 'single',
initial: getActiveNetwork(),
onChange: async (net) => {
await setActiveNetwork(net);
updateNetBars();
},
});
bar.querySelector('.nb-sel-mount').appendChild(sel.el);
netBarSelectors.push({ sel, isSyncerBar });
// Position fixed tooltips on hover so they escape overflow containers
bar.addEventListener('mouseenter', (e) => {
const tip = e.target.closest('.info-tip');
if (!tip) return;
const text = tip.querySelector('.info-tip-text');
if (!text) return;
const rect = tip.getBoundingClientRect();
text.style.top = (rect.bottom + 6) + 'px';
text.style.left = rect.left + 'px';
}, true);
});
function updateNetBars() {
const enabled = getEnabledNetworks();
const enabledSet = new Set(enabled);
const allNets = ['mainnet', 'zen'];
const disabledSet = new Set(allNets.filter(n => !enabledSet.has(n)));
// Don't auto-revert when active network is disabled. The user can
// legitimately want to view a disabled network's panel — most often
// on the syncer page, where the whole point of selecting it is to
// configure / enable it. Auto-reverting fights that intent: clicking
// Zen would silently snap back to Mainnet on the next onChange tick.
const net = getActiveNetwork();
for (const { sel, isSyncerBar } of netBarSelectors) {
// Syncer bar shows every network unconditionally — disabling buttons
// there would defeat its purpose (it's the place to enable them).
sel.setDisabled(isSyncerBar ? new Set() : disabledSet);
sel.setSelected(net);
}
const config = getNetworkConfig(net);
const syncState = getSyncState(net);
const relayState = getRelayState(net);
document.querySelectorAll('.net-bar').forEach(bar => {
bar.querySelector('.nb-name').textContent = NET_LABELS[net] || net;
const dotEl = bar.querySelector('.nb-dot');
const stateEl = bar.querySelector('.nb-state');
const phaseEl = bar.querySelector('.nb-phase');
if (syncState.status === 'syncing') {
const isHeaders = syncState.phase === 'headers';
const color = isHeaders ? '#f59e0b' : '#60a5fa';
dotEl.style.color = color;
stateEl.textContent = 'Syncing';
stateEl.style.color = color;
const pct = syncState.currentHeight && syncState.networkHeight
? ' ' + Math.round(syncState.currentHeight / syncState.networkHeight * 100) + '%'
: '';
phaseEl.textContent = pct;
phaseEl.style.color = color;
} else if (syncState.status === 'synced') {
dotEl.style.color = '#4ade80';
stateEl.textContent = 'Synced';
stateEl.style.color = '#4ade80';
phaseEl.textContent = syncState.lastSync ? 'Last: ' + new Date(syncState.lastSync).toLocaleTimeString() : '';
phaseEl.style.color = '#888';
} else if (syncState.status === 'error') {
dotEl.style.color = '#f87171';
stateEl.textContent = 'Error';
stateEl.style.color = '#f87171';
phaseEl.textContent = '';
} else {
dotEl.style.color = '#555';
stateEl.textContent = config.enabled ? 'Idle' : 'Disabled';
stateEl.style.color = '#888';
phaseEl.textContent = '';
}
const relayEl = bar.querySelector('.nb-relay');
if (relayState.connected) {
relayEl.textContent = 'Relay: connected';
relayEl.style.color = '#4ade80';
} else if (relayState.running) {
relayEl.textContent = 'Relay: connecting';
relayEl.style.color = '#f59e0b';
} else {
relayEl.textContent = 'Relay: off';
relayEl.style.color = '#666';
}
});
}
updateNetBars();
chainOnChange(updateNetBars);
// Toggle chain-dependent pages based on active networks
function updateChainPageAvailability() {
const enabled = getEnabledNetworks();
const hasSynced = isReady() || enabled.some(net => {
const s = getSyncState(net);
return s.status === 'synced';
});
for (const prefix of ['exp', 'wallet', 'manifest']) {
const overlay = document.getElementById(`${prefix}-disabled-overlay`);
const content = document.getElementById(`${prefix}-main-content`);
if (overlay && content) {
overlay.style.display = hasSynced ? 'none' : '';
content.style.display = hasSynced ? '' : 'none';
}
}
}
updateChainPageAvailability();
chainOnChange(updateChainPageAvailability);
// Sync indicator in chrome bar + status bar height display
const syncHeightEl = document.getElementById('sync-height-indicator');
const syncHeightSep = document.getElementById('sync-height-sep');
const syncHeightDot = document.getElementById('sync-height-dot');
syncHeightEl.addEventListener('click', (e) => {
const heightEl = e.target.closest('[data-block-height]');
if (heightEl) {
const height = heightEl.dataset.blockHeight;
const net = heightEl.dataset.net;
if (net) setActiveNetwork(net);
// While filters/txindex are still generating for this network the
// displayed height is the in-flight progress tip — jumping to the
// explorer for it doesn't help; the user wants to see the sync log.
// Once the network is fully synced, the height is a real block the
// explorer can show, so we keep that behavior post-sync.
const stillSyncing = net && getSyncState(net).status === 'syncing';
if (stillSyncing) {
openOrActivateInternalTab('syncer-config');
return;
}
openOrActivateInternalTab('explorer');
setTimeout(() => {
document.getElementById('exp-query').value = height;
explorerQuery();
}, 150);
} else {
openOrActivateInternalTab('syncer-config');
}
});
chainOnChange(() => {
const enabled = getEnabledNetworks();
if (enabled.length === 0) {
syncHeightEl.style.display = 'none';
syncHeightSep.style.display = 'none';
syncHeightDot.style.display = 'none';
return;
}
// Collect height info from all enabled networks, coloring each individually
let spans = [];
let worstStatus = 'synced'; // track worst for the dot: synced < syncing < error
for (const net of enabled) {
const s = getSyncState(net);
const showLabel = enabled.length > 1;
const label = net === 'mainnet' ? 'M' : net === 'zen' ? 'Z' : net.slice(0, 2).toUpperCase();
const prefix = showLabel ? label + ':' : '';
let text, color;
if (s.status === 'syncing') {
if (s.currentHeight != null && s.networkHeight != null && s.currentHeight < s.networkHeight) {
text = prefix + s.currentHeight.toLocaleString() + '/' + s.networkHeight.toLocaleString();
} else if (s.currentHeight != null && s.networkHeight != null) {
text = prefix + s.networkHeight.toLocaleString();
} else {
text = prefix + 'syncing';
}
color = '#60a5fa';
if (worstStatus === 'synced') worstStatus = 'syncing';
} else if (s.status === 'synced') {
text = s.networkHeight != null ? prefix + s.networkHeight.toLocaleString() : prefix + 'synced';
color = '#4ade80';
} else if (s.status === 'error') {
text = prefix + 'err';
color = '#f87171';
worstStatus = 'error';
} else {
text = prefix + 'idle';
color = '#888';
}
const height = s.networkHeight || s.currentHeight;
if (height != null && (s.status === 'synced' || s.status === 'syncing')) {
const tip = s.status === 'syncing'
? 'Sync in progress — click to view sync log'
: 'View block ' + height + ' in Explorer';
spans.push('<span style="color:' + color + '">' + prefix + '<span data-block-height="' + height + '" data-net="' + net + '" style="cursor:pointer;" title="' + tip + '">' + height.toLocaleString() + '</span></span>');
} else {
spans.push('<span style="color:' + color + '; cursor:pointer;" title="Open Syncer">' + text + '</span>');
}
}
// Status bar: dot + per-network colored text
if (spans.length > 0) {
const dotColor = worstStatus === 'error' ? '#f87171' : worstStatus === 'syncing' ? '#60a5fa' : '#4ade80';
syncHeightDot.style.display = '';
syncHeightDot.style.background = dotColor;
syncHeightEl.style.display = '';
syncHeightEl.innerHTML = spans.join(' <span style="color:#333">|</span> ');
syncHeightEl.style.color = '';
syncHeightSep.style.display = '';
} else {
syncHeightEl.style.display = 'none';
syncHeightSep.style.display = 'none';
syncHeightDot.style.display = 'none';
}
});
// Long task detection: logs any task that blocks the main thread > 50ms
if (typeof PerformanceObserver !== 'undefined') {
try {
const longTaskObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
_dbgWarn(`[LONG-TASK] ${entry.duration.toFixed(1)}ms at ${entry.startTime.toFixed(1)} (name: ${entry.name})`);
}
});
longTaskObserver.observe({ type: 'longtask', buffered: false });
_dbg('[JS] Long task observer installed');
} catch (e) {
_dbgWarn('[JS] Long task observer not supported:', e.message);
}
}
// rAF gap detector: logs when any animation frame takes > 500ms gap
// (only fires during significant stalls, not normal frame variance)
let _rafGapLast = performance.now();
function _rafGapCheck() {
const now = performance.now();
const gap = now - _rafGapLast;
if (gap > 500) {
_dbgWarn(`[RAF-GAP] ${gap.toFixed(0)}ms stall at ${(now / 1000).toFixed(1)}s`);
}
_rafGapLast = now;
requestAnimationFrame(_rafGapCheck);
}
requestAnimationFrame(_rafGapCheck);
if (debugLoggingCheckbox.checked) setLogger((msg) => console.log(msg), 'debug');
document.getElementById('loading').style.display = 'none';
document.getElementById('app').style.display = 'flex';