nostringer 0.1.6

Ring signatures (SAG, BLSAG) for Nostr
Documentation
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
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Nostringer WASM Demo</title>
    <style>
      body {
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        line-height: 1.6;
      }
      h1 {
        color: #4a4a4a;
        text-align: center;
        margin-bottom: 30px;
      }
      .section {
        margin-bottom: 30px;
        padding: 20px;
        border-radius: 8px;
        background-color: #f9f9f9;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
      button {
        background-color: #4caf50;
        color: white;
        padding: 10px 15px;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 10px;
        margin-bottom: 10px;
      }
      button:hover {
        background-color: #45a049;
      }
      pre {
        background-color: #f1f1f1;
        padding: 10px;
        border-radius: 4px;
        overflow-x: auto;
        white-space: pre-wrap;
      }
      .container {
        display: flex;
        flex-direction: column;
        gap: 20px;
      }
      #tabs {
        display: flex;
        margin-bottom: 20px;
      }
      .tab {
        padding: 10px 20px;
        background-color: #e0e0e0;
        cursor: pointer;
        border-radius: 4px 4px 0 0;
      }
      .tab.active {
        background-color: #4caf50;
        color: white;
      }
      .tab-content {
        display: none;
      }
      .tab-content.active {
        display: block;
      }
    </style>
  </head>
  <body>
    <h1>Nostringer Ring Signatures in WebAssembly</h1>

    <div id="tabs">
      <div class="tab active" data-tab="sag">SAG (Unlinkable)</div>
      <div class="tab" data-tab="blsag">BLSAG (Linkable)</div>
      <div class="tab" data-tab="compact">Compact Format</div>
    </div>

    <div class="container">
      <div id="sag" class="tab-content active">
        <div class="section">
          <h2>SAG Ring Signatures</h2>
          <p>
            Standard ring signatures provide anonymity within a group without
            linkability.
          </p>
          <button id="generate-keys">1. Generate Keys for Ring</button>
          <button id="sign-message" disabled>2. Sign Message</button>
          <button id="verify-signature" disabled>3. Verify Signature</button>
          <button id="tamper-message" disabled>4. Tamper & Verify</button>
          <pre id="sag-output">Click "Generate Keys for Ring" to start...</pre>
        </div>
      </div>

      <div id="blsag" class="tab-content">
        <div class="section">
          <h2>BLSAG Linkable Ring Signatures</h2>
          <p>
            Linkable ring signatures allow detecting when the same key signs
            multiple messages while maintaining anonymity.
          </p>
          <button id="blsag-generate-keys">1. Generate Keys for Ring</button>
          <button id="blsag-sign-message1" disabled>
            2. Sign First Message
          </button>
          <button id="blsag-sign-message2" disabled>
            3. Sign Second Message
          </button>
          <button id="blsag-check-linkability" disabled>
            4. Check Linkability
          </button>
          <pre id="blsag-output">
Click "Generate Keys for Ring" to start...</pre
          >
        </div>
      </div>

      <div id="compact" class="tab-content">
        <div class="section">
          <h2>Compact Signature Format</h2>
          <p>
            The compact format uses CBOR encoding and base64url for efficient
            transmission of signatures. Compare both formats to see the size
            difference.
          </p>
          <button id="compact-generate-keys">1. Generate Keys for Ring</button>
          <button id="compact-sign-sag" disabled>
            2. Sign with SAG (Unlinkable)
          </button>
          <button id="compact-sign-blsag" disabled>
            3. Sign with BLSAG (Linkable)
          </button>
          <button id="compact-compare-sizes" disabled>
            4. Compare Formats
          </button>
          <pre id="compact-output">
Click "Generate Keys for Ring" to start...</pre
          >
        </div>
      </div>
    </div>

    <script type="module">
      // Import the WASM module
      import init, {
        wasm_generate_keypair,
        wasm_sign,
        wasm_verify,
        wasm_sign_blsag,
        wasm_verify_blsag,
        wasm_key_images_match,
        wasm_sign_compact_sag,
        wasm_sign_compact_blsag,
        wasm_verify_compact,
        wasm_get_compact_signature_info,
      } from "./pkg/nostringer.js";

      // Initialize WASM module and set up event listeners
      async function initWasm() {
        try {
          await init();
          console.log("WASM module initialized");
          setupEventListeners();
        } catch (error) {
          console.error("Failed to initialize WASM module:", error);
          document.getElementById("sag-output").textContent =
            "Error initializing WASM module: " + error.message;
          document.getElementById("blsag-output").textContent =
            "Error initializing WASM module: " + error.message;
          document.getElementById("compact-output").textContent =
            "Error initializing WASM module: " + error.message;
        }
      }

      // Global state for SAG demo
      const state = {
        keypairs: [],
        ringPubkeys: [],
        signature: null,
        message: "This is a secret message for the ring.",
      };

      // Global state for BLSAG demo
      const blsagState = {
        keypairs: [],
        ringPubkeys: [],
        signatures: [],
        keyImages: [],
        messages: [
          "First message: Approve the proposal.",
          "Second message: Transfer the funds.",
        ],
      };

      // Global state for Compact demo
      const compactState = {
        keypairs: [],
        ringPubkeys: [],
        message: "This message will be signed with different formats.",
        signatures: {
          sag: {
            hex: null,
            compact: null,
          },
          blsag: {
            hex: null,
            compact: null,
          },
        },
      };

      function setupEventListeners() {
        // SAG Demo buttons
        document
          .getElementById("generate-keys")
          .addEventListener("click", generateKeys);
        document
          .getElementById("sign-message")
          .addEventListener("click", signMessage);
        document
          .getElementById("verify-signature")
          .addEventListener("click", verifySignature);
        document
          .getElementById("tamper-message")
          .addEventListener("click", tamperAndVerify);

        // BLSAG Demo buttons
        document
          .getElementById("blsag-generate-keys")
          .addEventListener("click", blsagGenerateKeys);
        document
          .getElementById("blsag-sign-message1")
          .addEventListener("click", () => blsagSignMessage(0));
        document
          .getElementById("blsag-sign-message2")
          .addEventListener("click", () => blsagSignMessage(1));
        document
          .getElementById("blsag-check-linkability")
          .addEventListener("click", blsagCheckLinkability);

        // Compact Format Demo buttons
        document
          .getElementById("compact-generate-keys")
          .addEventListener("click", compactGenerateKeys);
        document
          .getElementById("compact-sign-sag")
          .addEventListener("click", compactSignSAG);
        document
          .getElementById("compact-sign-blsag")
          .addEventListener("click", compactSignBLSAG);
        document
          .getElementById("compact-compare-sizes")
          .addEventListener("click", compactCompareSizes);

        // Setup tab switching
        document.querySelectorAll(".tab").forEach((tab) => {
          tab.addEventListener("click", () => {
            const tabName = tab.getAttribute("data-tab");
            switchTab(tabName);
          });
        });
      }

      // SAG Functions
      function generateKeys() {
        try {
          const output = document.getElementById("sag-output");
          output.textContent = "Generating keys for the ring...\n";

          // Generate 3 keypairs for the ring
          state.keypairs = [];
          for (let i = 0; i < 3; i++) {
            const format = "xonly";
            const keypair = wasm_generate_keypair(format);
            state.keypairs.push({
              privateKeyHex: keypair.private_key_hex,
              publicKeyHex: keypair.public_key_hex,
            });
          }

          // Prepare ring of public keys
          state.ringPubkeys = state.keypairs.map((kp) => kp.publicKeyHex);

          // Display the generated keys
          output.textContent += "Generated 3 keypairs:\n";
          state.keypairs.forEach((kp, i) => {
            output.textContent += `\nRing Member ${i + 1}:\n`;
            output.textContent += `Private Key: ${kp.privateKeyHex.substring(
              0,
              10
            )}...${kp.privateKeyHex.substring(kp.privateKeyHex.length - 10)}\n`;
            output.textContent += `Public Key: ${kp.publicKeyHex.substring(
              0,
              10
            )}...${kp.publicKeyHex.substring(kp.publicKeyHex.length - 10)}\n`;
          });

          output.textContent +=
            '\nRing is ready for signing. Click "Sign Message" to continue.';
          document.getElementById("sign-message").disabled = false;
        } catch (error) {
          document.getElementById("sag-output").textContent =
            "Error generating keys: " + error.message;
        }
      }

      function signMessage() {
        try {
          const output = document.getElementById("sag-output");
          output.textContent =
            "Signing message with Ring Member 2's private key...\n";
          output.textContent += `Message: "${state.message}"\n\n`;

          // Sign the message with the second keypair's private key
          const signerIndex = 1; // Use the second keypair (0-based index)
          const signerPrivateKey = state.keypairs[signerIndex].privateKeyHex;
          const encoder = new TextEncoder();
          const messageBytes = encoder.encode(state.message);

          state.signature = wasm_sign(
            messageBytes,
            signerPrivateKey,
            state.ringPubkeys
          );

          // Display the signature
          output.textContent += "Generated Ring Signature:\n";
          output.textContent += `c0: ${state.signature.c0.substring(
            0,
            10
          )}...${state.signature.c0.substring(
            state.signature.c0.length - 10
          )}\n`;
          output.textContent += `s values: [${state.signature.s.length} scalars]\n`;

          output.textContent +=
            '\nClick "Verify Signature" to verify it against the ring.';
          document.getElementById("verify-signature").disabled = false;
        } catch (error) {
          document.getElementById("sag-output").textContent =
            "Error signing message: " + error.message;
        }
      }

      function verifySignature() {
        try {
          const output = document.getElementById("sag-output");
          output.textContent = "Verifying signature against the ring...\n";
          output.textContent += `Message: "${state.message}"\n\n`;

          // Verify the signature
          const encoder = new TextEncoder();
          const messageBytes = encoder.encode(state.message);
          const isValid = wasm_verify(
            state.signature,
            messageBytes,
            state.ringPubkeys
          );

          // Display the result
          output.textContent += `Verification result: ${
            isValid ? "VALID ✓" : "INVALID ✗"
          }\n`;
          output.textContent +=
            "\nThe signature proves that someone in the ring signed this message,";
          output.textContent +=
            "\nbut it doesn't reveal which specific member.";

          output.textContent +=
            '\n\nClick "Tamper & Verify" to see what happens if the message is modified.';
          document.getElementById("tamper-message").disabled = false;
        } catch (error) {
          document.getElementById("sag-output").textContent =
            "Error verifying signature: " + error.message;
        }
      }

      function tamperAndVerify() {
        try {
          const output = document.getElementById("sag-output");
          const tamperedMessage = state.message + " [TAMPERED]";
          output.textContent = "Verifying signature with tampered message...\n";
          output.textContent += `Original message: "${state.message}"\n`;
          output.textContent += `Tampered message: "${tamperedMessage}"\n\n`;

          // Verify with tampered message
          const encoder = new TextEncoder();
          const tamperedBytes = encoder.encode(tamperedMessage);
          const isValid = wasm_verify(
            state.signature,
            tamperedBytes,
            state.ringPubkeys
          );

          // Display the result
          output.textContent += `Verification result: ${
            isValid ? "VALID ✓" : "INVALID ✗"
          }\n`;
          output.textContent +=
            "\nThe signature is invalid for the tampered message.";
          output.textContent +=
            "\nThis proves that the signature is bound to the original message.";

          output.textContent +=
            "\n\nDemo complete! Try the BLSAG tab for linkable signatures.";
        } catch (error) {
          document.getElementById("sag-output").textContent =
            "Error in tamper verification: " + error.message;
        }
      }

      // BLSAG Functions
      function blsagGenerateKeys() {
        try {
          const output = document.getElementById("blsag-output");
          output.textContent = "Generating keys for the BLSAG ring...\n";

          // Generate 4 keypairs for the ring
          blsagState.keypairs = [];
          for (let i = 0; i < 4; i++) {
            const format = "xonly";
            const keypair = wasm_generate_keypair(format);
            blsagState.keypairs.push({
              privateKeyHex: keypair.private_key_hex,
              publicKeyHex: keypair.public_key_hex,
            });
          }

          // Prepare ring of public keys
          blsagState.ringPubkeys = blsagState.keypairs.map(
            (kp) => kp.publicKeyHex
          );

          // Display the generated keys
          output.textContent += "Generated 4 keypairs:\n";
          blsagState.keypairs.forEach((kp, i) => {
            output.textContent += `\nRing Member ${i + 1}:\n`;
            output.textContent += `Public Key: ${kp.publicKeyHex.substring(
              0,
              10
            )}...${kp.publicKeyHex.substring(kp.publicKeyHex.length - 10)}\n`;
          });

          output.textContent +=
            '\nRing is ready for signing. Click "Sign First Message" to continue.';
          document.getElementById("blsag-sign-message1").disabled = false;
        } catch (error) {
          document.getElementById("blsag-output").textContent =
            "Error generating BLSAG keys: " + error.message;
        }
      }

      function blsagSignMessage(messageIndex) {
        try {
          const output = document.getElementById("blsag-output");
          output.textContent = `Signing message ${
            messageIndex + 1
          } with Ring Member 2's private key...\n`;
          output.textContent += `Message: "${blsagState.messages[messageIndex]}"\n\n`;

          // Sign the message with the second keypair's private key
          const signerIndex = 1; // Use the second keypair (0-based index)
          const signerPrivateKey =
            blsagState.keypairs[signerIndex].privateKeyHex;
          const encoder = new TextEncoder();
          const messageBytes = encoder.encode(
            blsagState.messages[messageIndex]
          );

          const result = wasm_sign_blsag(
            messageBytes,
            signerPrivateKey,
            blsagState.ringPubkeys
          );
          blsagState.signatures[messageIndex] = result;
          blsagState.keyImages[messageIndex] = result.key_image;

          // Display the signature
          output.textContent += "Generated BLSAG Signature:\n";
          output.textContent += `c0: ${result.c0.substring(
            0,
            10
          )}...${result.c0.substring(result.c0.length - 10)}\n`;
          output.textContent += `Key Image: ${result.key_image.substring(
            0,
            10
          )}...${result.key_image.substring(result.key_image.length - 10)}\n`;

          // Verify immediately
          const isValid = wasm_verify_blsag(
            result,
            messageBytes,
            blsagState.ringPubkeys
          );
          output.textContent += `\nVerification result: ${
            isValid ? "VALID ✓" : "INVALID ✗"
          }\n`;

          // Enable the next button based on which message was signed
          if (messageIndex === 0) {
            document.getElementById("blsag-sign-message2").disabled = false;
            output.textContent +=
              '\nClick "Sign Second Message" to sign another message with the same key.';
          } else {
            document.getElementById("blsag-check-linkability").disabled = false;
            output.textContent +=
              '\nClick "Check Linkability" to compare the key images.';
          }
        } catch (error) {
          document.getElementById("blsag-output").textContent =
            "Error signing BLSAG message: " + error.message;
        }
      }

      function blsagCheckLinkability() {
        try {
          const output = document.getElementById("blsag-output");
          output.textContent =
            "Checking linkability between the two signatures...\n\n";

          // Compare key images
          const keyImage1 = blsagState.keyImages[0];
          const keyImage2 = blsagState.keyImages[1];

          output.textContent += `Key Image 1: ${keyImage1.substring(
            0,
            10
          )}...${keyImage1.substring(keyImage1.length - 10)}\n`;
          output.textContent += `Key Image 2: ${keyImage2.substring(
            0,
            10
          )}...${keyImage2.substring(keyImage2.length - 10)}\n\n`;

          const match = wasm_key_images_match(keyImage1, keyImage2);

          output.textContent += `Key images match: ${
            match ? "YES ✓" : "NO ✗"
          }\n\n`;
          output.textContent += "Explanation:\n";
          output.textContent +=
            "- In BLSAG, each signer produces a unique key image derived from their private key\n";
          output.textContent +=
            "- This key image is the same for all signatures by the same key\n";
          output.textContent +=
            "- We can detect that both messages were signed by the same ring member\n";
          output.textContent +=
            "- Yet we still don't know which specific ring member signed\n\n";
          output.textContent +=
            "This linkability feature is useful for preventing double-voting,\n";
          output.textContent +=
            "double-spending, or other scenarios where we need to detect repeated\n";
          output.textContent +=
            "participation while still preserving anonymity within the group.";
        } catch (error) {
          document.getElementById("blsag-output").textContent =
            "Error checking linkability: " + error.message;
        }
      }

      // Compact Format Functions
      function compactGenerateKeys() {
        try {
          const output = document.getElementById("compact-output");
          output.textContent = "Generating keys for the ring...\n";

          // Generate 3 keypairs for the ring
          compactState.keypairs = [];
          for (let i = 0; i < 3; i++) {
            const format = "xonly";
            const keypair = wasm_generate_keypair(format);
            compactState.keypairs.push({
              privateKeyHex: keypair.private_key_hex,
              publicKeyHex: keypair.public_key_hex,
            });
          }

          // Prepare ring of public keys
          compactState.ringPubkeys = compactState.keypairs.map(
            (kp) => kp.publicKeyHex
          );

          // Display the generated keys
          output.textContent += "Generated 3 keypairs for the ring.\n";
          output.textContent += `Signer will be Ring Member 2 (middle keypair).\n`;
          output.textContent += `\nMessage to sign: "${compactState.message}"\n`;

          output.textContent +=
            '\nReady to sign. Click "Sign with SAG" to continue.';
          document.getElementById("compact-sign-sag").disabled = false;
        } catch (error) {
          document.getElementById("compact-output").textContent =
            "Error generating keys: " + error.message;
        }
      }

      function compactSignSAG() {
        try {
          const output = document.getElementById("compact-output");
          output.textContent = "Signing with both formats (SAG)...\n";

          // Sign with normal hex format
          const signerIndex = 1; // Use the second keypair (0-based index)
          const signerPrivateKey =
            compactState.keypairs[signerIndex].privateKeyHex;
          const encoder = new TextEncoder();
          const messageBytes = encoder.encode(compactState.message);

          // Sign with original hex format
          const hexSignature = wasm_sign(
            messageBytes,
            signerPrivateKey,
            compactState.ringPubkeys
          );
          compactState.signatures.sag.hex = hexSignature;

          // Sign with compact format
          const compactSignature = wasm_sign_compact_sag(
            messageBytes,
            signerPrivateKey,
            compactState.ringPubkeys
          );
          compactState.signatures.sag.compact = compactSignature;

          // Display the signatures
          output.textContent += "\n=== SAG Signatures ===\n";
          output.textContent += "\nOriginal Hex Format:\n";
          output.textContent += `c0: ${hexSignature.c0.substring(
            0,
            15
          )}...${hexSignature.c0.substring(hexSignature.c0.length - 15)}\n`;
          output.textContent += `s values: ${hexSignature.s.length} scalars, each ~64 chars\n`;

          output.textContent += "\nCompact Format:\n";
          output.textContent += `${compactSignature}\n`;

          // Verify both
          const hexValid = wasm_verify(
            hexSignature,
            messageBytes,
            compactState.ringPubkeys
          );
          const compactValid = wasm_verify_compact(
            compactSignature,
            messageBytes,
            compactState.ringPubkeys
          );

          output.textContent += `\nBoth signature formats are valid: ${
            hexValid && compactValid ? "✓" : "✗"
          }\n`;

          output.textContent +=
            '\nNow try "Sign with BLSAG" to create linkable signatures.';
          document.getElementById("compact-sign-blsag").disabled = false;
        } catch (error) {
          document.getElementById("compact-output").textContent =
            "Error signing with SAG: " + error.message;
        }
      }

      function compactSignBLSAG() {
        try {
          const output = document.getElementById("compact-output");
          output.textContent = "Signing with both formats (BLSAG)...\n";

          // Sign with normal hex format
          const signerIndex = 1; // Use the second keypair (0-based index)
          const signerPrivateKey =
            compactState.keypairs[signerIndex].privateKeyHex;
          const encoder = new TextEncoder();
          const messageBytes = encoder.encode(compactState.message);

          // Sign with original hex format
          const hexSignature = wasm_sign_blsag(
            messageBytes,
            signerPrivateKey,
            compactState.ringPubkeys
          );
          compactState.signatures.blsag.hex = hexSignature;

          // Sign with compact format
          const compactSignature = wasm_sign_compact_blsag(
            messageBytes,
            signerPrivateKey,
            compactState.ringPubkeys
          );
          compactState.signatures.blsag.compact = compactSignature;

          // Display the signatures
          output.textContent += "\n=== BLSAG Signatures ===\n";
          output.textContent += "\nOriginal Hex Format:\n";
          output.textContent += `c0: ${hexSignature.c0.substring(
            0,
            15
          )}...${hexSignature.c0.substring(hexSignature.c0.length - 15)}\n`;
          output.textContent += `Key Image: ${hexSignature.key_image.substring(
            0,
            15
          )}...${hexSignature.key_image.substring(
            hexSignature.key_image.length - 15
          )}\n`;
          output.textContent += `s values: ${hexSignature.s.length} scalars, each ~64 chars\n`;

          output.textContent += "\nCompact Format:\n";
          output.textContent += `${compactSignature}\n`;

          // Verify both
          const hexValid = wasm_verify_blsag(
            hexSignature,
            messageBytes,
            compactState.ringPubkeys
          );
          const compactValid = wasm_verify_compact(
            compactSignature,
            messageBytes,
            compactState.ringPubkeys
          );

          output.textContent += `\nBoth signature formats are valid: ${
            hexValid && compactValid ? "✓" : "✗"
          }\n`;

          output.textContent +=
            '\nReady to compare sizes. Click "Compare Formats" to continue.';
          document.getElementById("compact-compare-sizes").disabled = false;
        } catch (error) {
          document.getElementById("compact-output").textContent =
            "Error signing with BLSAG: " + error.message;
        }
      }

      function compactCompareSizes() {
        try {
          const output = document.getElementById("compact-output");
          output.textContent = "=== Size Comparison ===\n\n";

          // Get signature info (size and variant)
          const sagInfo = wasm_get_compact_signature_info(
            compactState.signatures.sag.compact
          );
          const blsagInfo = wasm_get_compact_signature_info(
            compactState.signatures.blsag.compact
          );

          // Calculate hex format sizes
          const sagHexSize =
            compactState.signatures.sag.hex.c0.length +
            compactState.signatures.sag.hex.s.reduce(
              (total, s) => total + s.length,
              0
            );

          const blsagHexSize =
            compactState.signatures.blsag.hex.c0.length +
            compactState.signatures.blsag.hex.s.reduce(
              (total, s) => total + s.length,
              0
            ) +
            compactState.signatures.blsag.hex.key_image.length;

          // Display size comparison
          output.textContent += "SAG (Unlinkable) Signature:\n";
          output.textContent += `  Original Hex Format: ~${sagHexSize} characters\n`;
          output.textContent += `  Compact Format: ${sagInfo.size} bytes\n`;
          output.textContent += `  Size Reduction: ${Math.round(
            ((sagHexSize - sagInfo.size) / sagHexSize) * 100
          )}%\n\n`;

          output.textContent += "BLSAG (Linkable) Signature:\n";
          output.textContent += `  Original Hex Format: ~${blsagHexSize} characters\n`;
          output.textContent += `  Compact Format: ${blsagInfo.size} bytes\n`;
          output.textContent += `  Size Reduction: ${Math.round(
            ((blsagHexSize - blsagInfo.size) / blsagHexSize) * 100
          )}%\n\n`;

          // Explain the compact format
          output.textContent += "=== How Compact Format Works ===\n\n";
          output.textContent += "The compact format ('ringA' prefix) uses:\n";
          output.textContent +=
            "1. CBOR binary encoding for compact representation\n";
          output.textContent +=
            "2. Single-character field names (v, c, s, i)\n";
          output.textContent +=
            "3. Binary storage of scalars and curve points\n";
          output.textContent +=
            "4. base64url encoding for text transmission\n\n";

          output.textContent += "Variant field indicates signature type:\n";
          output.textContent += `  SAG signature: "${sagInfo.variant}"\n`;
          output.textContent += `  BLSAG signature: "${blsagInfo.variant}"\n\n`;

          output.textContent +=
            "BLSAG signatures are larger but enable linkability detection.";
        } catch (error) {
          document.getElementById("compact-output").textContent =
            "Error comparing sizes: " + error.message;
        }
      }

      function switchTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll(".tab-content").forEach((tab) => {
          tab.classList.remove("active");
        });

        // Show the selected tab content
        document.getElementById(tabName).classList.add("active");

        // Update the tab buttons
        document.querySelectorAll(".tab").forEach((tab) => {
          tab.classList.remove("active");
        });

        // Find the clicked tab button by its data-tab attribute
        document
          .querySelector(`.tab[data-tab="${tabName}"]`)
          .classList.add("active");
      }

      // Initialize the WASM module
      initWasm();
    </script>
  </body>
</html>