@monolythium/core-sdk 0.4.23 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,9 +5,6 @@ var blake3_js = require('@noble/hashes/blake3.js');
5
5
  var sha3_js = require('@noble/hashes/sha3.js');
6
6
  var bip39 = require('@scure/bip39');
7
7
  var english_js = require('@scure/bip39/wordlists/english.js');
8
- var mlKem_js = require('@noble/post-quantum/ml-kem.js');
9
- var chacha_js = require('@noble/ciphers/chacha.js');
10
- var utils_js = require('@noble/hashes/utils.js');
11
8
 
12
9
  // src/crypto/bincode.ts
13
10
  var BincodeWriter = class {
@@ -355,105 +352,69 @@ function encodeMlDsa65Opaque(raw) {
355
352
  out.set(bytes, 14);
356
353
  return out;
357
354
  }
358
- var PQM1_ALGO_TAG_MLDSA65 = 1;
359
- var PQM1_ALGO_TAG_MLDSA87_RESERVED = 2;
360
- var PQM1_ALGO_TAG_SLHDSA128S_RESERVED = 3;
361
- var PQM1_ALGO_TAG_FALCON512_RESERVED = 4;
362
- var PQM1_VERSION_V1 = 1;
363
- var PQM1_PAYLOAD_LEN = 32;
364
- var PQM1_ENTROPY_LEN = 30;
365
- var PQM1_V1_MNEMONIC_WORDS = 24;
366
- var PQM1_V1_MLDSA65_DOMAIN_TAG = "monolythium.pqm1.v1.mldsa65";
367
- var Pqm1Error = class extends Error {
355
+ var MLDSA65_MNEMONIC_WORDS = 24;
356
+ var MLDSA65_SEED_DOMAIN = "monolythium.mldsa65.v1";
357
+ var MLDSA65_ENTROPY_LEN = 32;
358
+ var DOMAIN_BYTES = new TextEncoder().encode(MLDSA65_SEED_DOMAIN);
359
+ var MnemonicError = class extends Error {
368
360
  constructor(kind, message) {
369
361
  super(message);
370
362
  this.kind = kind;
371
- this.name = "Pqm1Error";
363
+ this.name = "MnemonicError";
372
364
  }
373
365
  kind;
374
366
  };
375
- var DOMAIN_BYTES = new TextEncoder().encode(PQM1_V1_MLDSA65_DOMAIN_TAG);
376
367
  function normalizeMnemonic(mnemonic) {
377
368
  return mnemonic.trim().toLowerCase().replace(/\s+/g, " ");
378
369
  }
379
- function ensureSupportedPayload(bytes) {
380
- if (bytes.length !== PQM1_PAYLOAD_LEN) {
381
- throw new Pqm1Error("badPayloadLength", `PQM-1 payload must be ${PQM1_PAYLOAD_LEN} bytes, got ${bytes.length}`);
382
- }
383
- if (bytes[0] !== PQM1_ALGO_TAG_MLDSA65) {
384
- throw new Pqm1Error("unsupportedAlgorithm", `unsupported PQM-1 algorithm tag 0x${bytes[0].toString(16).padStart(2, "0")}`);
385
- }
386
- if (bytes[1] !== PQM1_VERSION_V1) {
387
- throw new Pqm1Error("unsupportedVersion", `unsupported PQM-1 version 0x${bytes[1].toString(16).padStart(2, "0")}`);
388
- }
370
+ function wordCount(normalized) {
371
+ return normalized.length === 0 ? 0 : normalized.split(" ").length;
389
372
  }
390
373
  function defaultRandomFill(bytes) {
391
374
  const cryptoObj = globalThis.crypto;
392
375
  if (!cryptoObj?.getRandomValues) {
393
- throw new Pqm1Error("missingRandom", "globalThis.crypto.getRandomValues is unavailable");
376
+ throw new MnemonicError("missingRandom", "globalThis.crypto.getRandomValues is unavailable");
394
377
  }
395
378
  cryptoObj.getRandomValues(bytes);
396
379
  }
397
- function assemblePqm1Payload(entropy) {
398
- const ent = expectBytes(entropy, PQM1_ENTROPY_LEN, "PQM-1 entropy");
399
- const payload = new Uint8Array(PQM1_PAYLOAD_LEN);
400
- payload[0] = PQM1_ALGO_TAG_MLDSA65;
401
- payload[1] = PQM1_VERSION_V1;
402
- payload.set(ent, 2);
403
- return payload;
404
- }
405
- function parsePqm1Payload(payload) {
406
- const bytes = expectBytes(payload, PQM1_PAYLOAD_LEN, "PQM-1 payload").slice();
407
- ensureSupportedPayload(bytes);
408
- return {
409
- algoTag: PQM1_ALGO_TAG_MLDSA65,
410
- version: PQM1_VERSION_V1,
411
- entropy: bytes.slice(2),
412
- bytes
413
- };
380
+ function generateMnemonic(rng = defaultRandomFill) {
381
+ const entropy = new Uint8Array(MLDSA65_ENTROPY_LEN);
382
+ rng(entropy);
383
+ return bip39.entropyToMnemonic(entropy, english_js.wordlist);
414
384
  }
415
- function pqm1PayloadToMnemonic(payload) {
416
- const parsed = parsePqm1Payload(payload);
417
- return bip39.entropyToMnemonic(parsed.bytes, english_js.wordlist);
385
+ function validateMnemonic(mnemonic) {
386
+ const normalized = normalizeMnemonic(mnemonic);
387
+ if (wordCount(normalized) !== MLDSA65_MNEMONIC_WORDS) {
388
+ return false;
389
+ }
390
+ return bip39.validateMnemonic(normalized, english_js.wordlist);
418
391
  }
419
- function pqm1MnemonicToPayload(mnemonic) {
392
+ function mnemonicToMlDsa65Seed(mnemonic) {
420
393
  const normalized = normalizeMnemonic(mnemonic);
421
- const words = normalized.length === 0 ? [] : normalized.split(" ");
422
- if (words.length !== PQM1_V1_MNEMONIC_WORDS) {
423
- throw new Pqm1Error("badWordCount", `PQM-1 mnemonic must be ${PQM1_V1_MNEMONIC_WORDS} words, got ${words.length}`);
394
+ const words = wordCount(normalized);
395
+ if (words !== MLDSA65_MNEMONIC_WORDS) {
396
+ throw new MnemonicError(
397
+ "badWordCount",
398
+ `mnemonic must be ${MLDSA65_MNEMONIC_WORDS} words, got ${words}`
399
+ );
424
400
  }
425
- let payload;
426
- try {
427
- payload = bip39.mnemonicToEntropy(normalized, english_js.wordlist);
428
- } catch (e) {
429
- throw new Pqm1Error("bip39Decode", `invalid PQM-1 mnemonic: ${e.message}`);
401
+ if (!bip39.validateMnemonic(normalized, english_js.wordlist)) {
402
+ throw new MnemonicError(
403
+ "bip39Decode",
404
+ "invalid BIP-39 mnemonic (unknown word or bad checksum)"
405
+ );
430
406
  }
431
- return parsePqm1Payload(payload);
432
- }
433
- function derivePqm1MlDsa65SeedFromPayload(payload) {
434
- const parsed = parsePqm1Payload(payload);
435
- return sha3_js.shake256(concatBytes(DOMAIN_BYTES, parsed.bytes), { dkLen: ML_DSA_65_SEED_LEN });
436
- }
437
- function pqm1MnemonicToMlDsa65Seed(mnemonic) {
438
- return derivePqm1MlDsa65SeedFromPayload(pqm1MnemonicToPayload(mnemonic).bytes);
407
+ const seed64 = bip39.mnemonicToSeedSync(normalized, "");
408
+ return sha3_js.shake256(concatBytes(DOMAIN_BYTES, seed64), { dkLen: ML_DSA_65_SEED_LEN });
439
409
  }
440
- function pqm1MnemonicToMlDsa65Backend(mnemonic) {
441
- return MlDsa65Backend.fromSeed(pqm1MnemonicToMlDsa65Seed(mnemonic));
410
+ function mnemonicToMlDsa65Backend(mnemonic) {
411
+ return MlDsa65Backend.fromSeed(mnemonicToMlDsa65Seed(mnemonic));
442
412
  }
443
- function pqm1MnemonicToAddress(mnemonic) {
444
- return pqm1MnemonicToMlDsa65Backend(mnemonic).getAddress();
413
+ function mnemonicToAddress(mnemonic) {
414
+ return mnemonicToMlDsa65Backend(mnemonic).getAddress();
445
415
  }
446
- function generatePqm1Mnemonic(rng = defaultRandomFill) {
447
- const entropy = new Uint8Array(PQM1_ENTROPY_LEN);
448
- rng(entropy);
449
- return pqm1PayloadToMnemonic(assemblePqm1Payload(entropy));
450
- }
451
- var DKG_AEAD_DOMAIN_TAG = new TextEncoder().encode("protocore/v2/mempool/dkg-mlkem768/1");
452
- var ML_KEM_768_CIPHERTEXT_LEN = 1088;
453
- var ML_KEM_768_ENCAPSULATION_KEY_LEN = 1184;
454
- var ML_KEM_768_SHARED_SECRET_LEN = 32;
455
- var DKG_NONCE_LEN = 12;
456
- var DKG_AEAD_TAG_LEN = 16;
416
+
417
+ // src/crypto/envelope.ts
457
418
  var MempoolClass = {
458
419
  Transfer: 0,
459
420
  ContractCall: 1,
@@ -465,430 +426,8 @@ var MempoolClass = {
465
426
  GovernanceOp: 5,
466
427
  RWAOp: 6
467
428
  };
468
- function bincodeNonceAad(aad) {
469
- const w = new BincodeWriter();
470
- w.bytes(expectBytes(aad.sender, 20, "NonceAad.sender"));
471
- w.u64(aad.nonce);
472
- w.u64(aad.chainId);
473
- w.enumVariant(aad.class);
474
- w.u128(aad.maxFeePerGas);
475
- w.u128(aad.maxPriorityFeePerGas);
476
- w.u64(aad.gasLimit);
477
- return w.toBytes();
478
- }
479
- function bincodeDecryptHint(hint) {
480
- const w = new BincodeWriter();
481
- w.u64(hint.epoch);
482
- w.u16(hint.scheme);
483
- return w.toBytes();
484
- }
485
- function bincodeEncryptedEnvelope(env) {
486
- const w = new BincodeWriter();
487
- w.rawBytes(bincodeNonceAad(env.nonceAad));
488
- w.bytes(env.ciphertext);
489
- w.rawBytes(bincodeDecryptHint(env.decryptionHint));
490
- bincodeMlDsa65OpaqueInto2(w, expectBytes(env.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, "senderPubkey"));
491
- bincodeMlDsa65OpaqueInto2(w, expectBytes(env.outerSignature, ML_DSA_65_SIGNATURE_LEN, "outerSignature"));
492
- w.bytes(expectBytes(env.sender, 20, "sender"));
493
- return w.toBytes();
494
- }
495
- function encryptInnerTx(signedInnerTxBincode, nonceAad, kemEncapsulationKey) {
496
- expectBytes(kemEncapsulationKey, ML_KEM_768_ENCAPSULATION_KEY_LEN, "kemEncapsulationKey");
497
- const { cipherText: kemCt, sharedSecret } = mlKem_js.ml_kem768.encapsulate(kemEncapsulationKey);
498
- const nonce = utils_js.randomBytes(DKG_NONCE_LEN);
499
- const cipher = chacha_js.chacha20poly1305(sharedSecret, nonce, aadFor(nonceAad));
500
- const aeadCt = cipher.encrypt(signedInnerTxBincode);
501
- sharedSecret.fill(0);
502
- return concatBytes(kemCt, nonce, aeadCt);
503
- }
504
- function outerSigDigest(nonceAad, ciphertext, decryptionHint, senderPubkey) {
505
- const aad = bincodeNonceAad(nonceAad);
506
- const hint = bincodeDecryptHint(decryptionHint);
507
- return sha3_js.keccak_256(concatBytes(aad, ciphertext, hint, expectBytes(senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, "senderPubkey")));
508
- }
509
- async function buildEncryptedEnvelope(args) {
510
- const ciphertext = encryptInnerTx(args.signedInnerTxBincode, args.nonceAad, args.kemEncapsulationKey);
511
- const digest = outerSigDigest(args.nonceAad, ciphertext, args.decryptionHint, args.senderPubkey);
512
- const outerSignature = await args.signOuterDigest(digest);
513
- const envelope = {
514
- nonceAad: args.nonceAad,
515
- ciphertext,
516
- decryptionHint: args.decryptionHint,
517
- senderPubkey: expectBytes(args.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, "senderPubkey"),
518
- outerSignature: expectBytes(outerSignature, ML_DSA_65_SIGNATURE_LEN, "outerSignature"),
519
- sender: expectBytes(args.senderAddress, 20, "senderAddress")
520
- };
521
- const wireBytes = bincodeEncryptedEnvelope(envelope);
522
- return { envelope, wireBytes, wireHex: bytesToHex(wireBytes) };
523
- }
524
- function aadFor(aad) {
525
- return concatBytes(DKG_AEAD_DOMAIN_TAG, bincodeNonceAad(aad));
526
- }
527
- function bincodeMlDsa65OpaqueInto2(w, raw) {
528
- w.enumVariant(ENUM_VARIANT_INDEX_ML_DSA_65);
529
- w.u16(STANDARD_ALGO_NUMBER_ML_DSA_65);
530
- w.bytes(raw);
531
- }
532
- var SEAL_EK_LEN = 1184;
533
- var SEAL_DK_LEN = 2400;
534
- var SEAL_KEM_CT_LEN = 1088;
535
- var SEAL_KEM_SEED_LEN = 64;
536
- var SEAL_KEY_LEN = 32;
537
- var SEAL_NONCE_LEN = 12;
538
- var SEAL_TAG_LEN = 16;
539
- var SEAL_COMMIT_LEN = 32;
540
- var SEAL_SECRET_LEN = 32;
541
- var SEAL_SHARE_LEN = 1 + SEAL_SECRET_LEN;
542
- var CLUSTER_MLKEM_SHAMIR = 3;
543
- var COMMIT_DOMAIN = new TextEncoder().encode("lythiumseal/commit/v1");
544
- var KEK_DOMAIN = new TextEncoder().encode("lythiumseal/kek/v1");
545
- var NONCE_DOMAIN = new TextEncoder().encode("lythiumseal/nonce/v1");
546
- var BODY_AAD_DOMAIN = new TextEncoder().encode("lythiumseal/body/v1");
547
- var SHARE_AAD_DOMAIN = new TextEncoder().encode("lythiumseal/share/v1");
548
- var ROSTER_DOMAIN = new TextEncoder().encode("lythiumseal/roster/v1");
549
- function cryptoRandomSource() {
550
- return {
551
- fillBytes(dest) {
552
- crypto.getRandomValues(dest);
553
- }
554
- };
555
- }
556
- function generateOperatorSealKeypair() {
557
- const { publicKey, secretKey } = mlKem_js.ml_kem768.keygen();
558
- return {
559
- encapsulationKey: expectBytes(publicKey, SEAL_EK_LEN, "encapsulationKey").slice(),
560
- decapsulationKey: expectBytes(secretKey, SEAL_DK_LEN, "decapsulationKey").slice()
561
- };
562
- }
563
- function u32le(n) {
564
- const out = new Uint8Array(4);
565
- out[0] = n & 255;
566
- out[1] = n >>> 8 & 255;
567
- out[2] = n >>> 16 & 255;
568
- out[3] = n >>> 24 & 255;
569
- return out;
570
- }
571
- function u64le(n) {
572
- const out = new Uint8Array(8);
573
- let v = n;
574
- for (let i = 0; i < 8; i++) {
575
- out[i] = Number(v & 0xffn);
576
- v >>= 8n;
577
- }
578
- return out;
579
- }
580
- function framed(field) {
581
- return concatBytes(u32le(field.length), field);
582
- }
583
- function keyCommitment(key) {
584
- return sha3_js.shake256(concatBytes(framed(COMMIT_DOMAIN), key), { dkLen: SEAL_COMMIT_LEN });
585
- }
586
- function deriveKek(sharedSecret, domain, clusterId, epoch, opIndex) {
587
- const input = concatBytes(
588
- framed(KEK_DOMAIN),
589
- framed(sharedSecret),
590
- framed(domain),
591
- u32le(clusterId),
592
- u64le(epoch),
593
- Uint8Array.of(opIndex)
594
- );
595
- return sha3_js.shake256(input, { dkLen: SEAL_KEY_LEN });
596
- }
597
- function deriveNonce(domain, context) {
598
- const input = concatBytes(framed(NONCE_DOMAIN), framed(domain), framed(context));
599
- return sha3_js.shake256(input, { dkLen: SEAL_NONCE_LEN });
600
- }
601
- function bodyAad(ctx, k, n) {
602
- return concatBytes(
603
- BODY_AAD_DOMAIN,
604
- u32le(ctx.clusterId),
605
- u64le(ctx.epoch),
606
- Uint8Array.of(k),
607
- Uint8Array.of(n),
608
- ctx.rosterHash
609
- );
610
- }
611
- function shareAad(ctx, opIndex) {
612
- return concatBytes(
613
- SHARE_AAD_DOMAIN,
614
- u32le(ctx.clusterId),
615
- u64le(ctx.epoch),
616
- Uint8Array.of(opIndex),
617
- ctx.rosterHash
618
- );
619
- }
620
- function aeadSeal(key, nonce, plaintext, aad) {
621
- const cipher = chacha_js.chacha20poly1305(key, nonce, aad);
622
- const ct = cipher.encrypt(plaintext);
623
- return { nonce, ct, commitment: keyCommitment(key) };
624
- }
625
- function gfMul(a, b) {
626
- let product = 0;
627
- let x = a & 255;
628
- let y = b & 255;
629
- for (let i = 0; i < 8; i++) {
630
- const mask = -(y & 1) & 255;
631
- product ^= x & mask;
632
- const high = -(x >> 7 & 1) & 255;
633
- x = x << 1 & 255;
634
- x ^= 27 & high;
635
- y >>= 1;
636
- }
637
- return product & 255;
638
- }
639
- function polyEval(coeffs, x) {
640
- let acc = 0;
641
- for (let i = coeffs.length - 1; i >= 0; i--) {
642
- acc = gfMul(acc, x) ^ coeffs[i];
643
- }
644
- return acc & 255;
645
- }
646
- function shamirSplit(secret, t, n, rng) {
647
- const byteCoeffs = [];
648
- for (let j = 0; j < SEAL_SECRET_LEN; j++) {
649
- const c = new Uint8Array(t);
650
- c[0] = secret[j];
651
- if (t > 1) {
652
- const tail = new Uint8Array(t - 1);
653
- rng.fillBytes(tail);
654
- c.set(tail, 1);
655
- }
656
- byteCoeffs.push(c);
657
- }
658
- const shares = [];
659
- for (let k = 0; k < n; k++) {
660
- const x = k + 1 & 255;
661
- const value = new Uint8Array(SEAL_SECRET_LEN);
662
- for (let j = 0; j < SEAL_SECRET_LEN; j++) {
663
- value[j] = polyEval(byteCoeffs[j], x);
664
- }
665
- shares.push({ index: x, value });
666
- }
667
- return shares;
668
- }
669
- function shareToBytes(s) {
670
- const out = new Uint8Array(SEAL_SHARE_LEN);
671
- out[0] = s.index;
672
- out.set(s.value, 1);
673
- return out;
674
- }
675
- function sealRosterHash(keccak2562, clusterId, t, n, roster) {
676
- const chunks = [ROSTER_DOMAIN, u32le(clusterId), Uint8Array.of(t), Uint8Array.of(n)];
677
- for (const { operatorIndex, ek } of roster) {
678
- chunks.push(Uint8Array.of(operatorIndex), ek);
679
- }
680
- return keccak2562(concatBytes(...chunks));
681
- }
682
- function encodeSealEnvelope(env) {
683
- const chunks = [];
684
- chunks.push(u32le(env.clusterId));
685
- chunks.push(u64le(env.epoch));
686
- chunks.push(expectBytes(env.rosterHash, 32, "rosterHash"));
687
- chunks.push(Uint8Array.of(env.t));
688
- chunks.push(Uint8Array.of(env.n));
689
- pushAeadBody(chunks, env.aeadBody);
690
- chunks.push(u64le(BigInt(env.recipients.length)));
691
- for (const r of env.recipients) {
692
- chunks.push(Uint8Array.of(r.operatorIndex));
693
- chunks.push(u64le(BigInt(r.kemCt.length)));
694
- chunks.push(r.kemCt);
695
- pushAeadBody(chunks, r.wrapped);
696
- }
697
- return concatBytes(...chunks);
698
- }
699
- function pushAeadBody(chunks, body) {
700
- chunks.push(expectBytes(body.nonce, SEAL_NONCE_LEN, "aead nonce"));
701
- chunks.push(u64le(BigInt(body.ct.length)));
702
- chunks.push(body.ct);
703
- chunks.push(expectBytes(body.commitment, SEAL_COMMIT_LEN, "aead commitment"));
704
- }
705
- function sealToCluster(args) {
706
- const { plaintext, recipientEks, t, clusterId } = args;
707
- const epoch = args.epoch;
708
- const rosterHash = expectBytes(args.rosterHash, 32, "rosterHash");
709
- const rng = args.rng ?? cryptoRandomSource();
710
- const n = recipientEks.length;
711
- if (!Number.isInteger(t) || t < 1 || t > n || n < 1 || n > 255) {
712
- throw new Error(`invalid threshold/recipient count: t=${t} n=${n}`);
713
- }
714
- for (let i = 0; i < n; i++) {
715
- expectBytes(recipientEks[i], SEAL_EK_LEN, `recipientEks[${i}]`);
716
- }
717
- const ctx = { clusterId, epoch, rosterHash };
718
- const bodyKey = new Uint8Array(SEAL_KEY_LEN);
719
- rng.fillBytes(bodyKey);
720
- const aad = bodyAad(ctx, t, n);
721
- const bodyNonce = deriveNonce(new TextEncoder().encode("body"), aad);
722
- const aeadBody = aeadSeal(bodyKey, bodyNonce, plaintext, aad);
723
- const shares = shamirSplit(bodyKey, t, n, rng);
724
- const recipients = [];
725
- for (let i = 0; i < n; i++) {
726
- const opIndex = i + 1 & 255;
727
- const m = new Uint8Array(32);
728
- rng.fillBytes(m);
729
- const { cipherText: kemCt, sharedSecret } = mlKem_js.ml_kem768.encapsulate(recipientEks[i], m);
730
- const kek = deriveKek(sharedSecret, rosterHash, clusterId, epoch, opIndex);
731
- const sAad = shareAad(ctx, opIndex);
732
- const wrapNonce = deriveNonce(new TextEncoder().encode("share"), sAad);
733
- const wrapped = aeadSeal(kek, wrapNonce, shareToBytes(shares[i]), sAad);
734
- recipients.push({ operatorIndex: opIndex, kemCt, wrapped });
735
- sharedSecret.fill(0);
736
- kek.fill(0);
737
- }
738
- bodyKey.fill(0);
739
- return {
740
- clusterId,
741
- epoch,
742
- rosterHash,
743
- t,
744
- n,
745
- aeadBody,
746
- recipients
747
- };
748
- }
749
-
750
- // src/crypto/seal.ts
751
- var CLUSTER_MLKEM_SHAMIR_ALGO = "cluster-mlkem768-shamir";
752
- function parseClusterSealKeys(source) {
753
- const n = source.roster.length;
754
- if (n === 0) {
755
- throw new Error("cluster seal roster is empty");
756
- }
757
- if (source.n !== n) {
758
- throw new Error(`cluster seal roster n=${source.n} disagrees with ${n} entries`);
759
- }
760
- if (!Number.isInteger(source.t) || source.t < 2 || source.t > n) {
761
- throw new Error(`cluster seal threshold t=${source.t} out of range 2..=${n}`);
762
- }
763
- const sorted = [...source.roster].sort((a, b) => a.operatorIndex - b.operatorIndex);
764
- const recipientEks = [];
765
- const hashInput = [];
766
- for (let i = 0; i < n; i++) {
767
- const entry = sorted[i];
768
- if (entry.operatorIndex !== i + 1) {
769
- throw new Error(
770
- `cluster seal roster operator indices must be 1..=${n}; got ${entry.operatorIndex} at slot ${i + 1}`
771
- );
772
- }
773
- const ek = expectBytes(hexToBytes(entry.mlKemEk, `operator ${entry.operatorIndex} mlKemEk`), SEAL_EK_LEN, `operator ${entry.operatorIndex} ek`);
774
- recipientEks.push(ek);
775
- hashInput.push({ operatorIndex: entry.operatorIndex, ek });
776
- }
777
- const recomputed = sealRosterHash(keccak256, source.clusterId, source.t, n, hashInput);
778
- if (source.rosterHash !== void 0) {
779
- const supplied = expectBytes(hexToBytes(source.rosterHash, "rosterHash"), 32, "rosterHash");
780
- if (!bytesEqual(supplied, recomputed)) {
781
- throw new Error(
782
- `cluster seal roster hash mismatch: source ${bytesToHex(supplied)} != recomputed ${bytesToHex(recomputed)} (the roster hash does not commit to this ek set)`
783
- );
784
- }
785
- }
786
- return {
787
- algo: source.algo ?? CLUSTER_MLKEM_SHAMIR_ALGO,
788
- clusterId: source.clusterId,
789
- epoch: toBigInt(source.epoch),
790
- rosterHash: recomputed,
791
- t: source.t,
792
- n,
793
- recipientEks
794
- };
795
- }
796
- async function getClusterSealKeys(client, clusterId = 0) {
797
- const result = await client.call(
798
- "lyth_getClusterSealKeys",
799
- [clusterId]
800
- );
801
- return parseClusterSealKeys({ ...result, clusterId: result.clusterId ?? clusterId });
802
- }
803
- async function sealTransaction(args) {
804
- const keys = args.clusterSealKeys;
805
- const senderPubkey = expectBytes(args.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, "senderPubkey");
806
- const senderAddress = expectBytes(args.senderAddress, 20, "senderAddress");
807
- const env = sealToCluster({
808
- plaintext: args.signedTxBincode,
809
- recipientEks: keys.recipientEks,
810
- t: keys.t,
811
- clusterId: keys.clusterId,
812
- epoch: keys.epoch,
813
- rosterHash: keys.rosterHash,
814
- rng: args.rng
815
- });
816
- const ciphertext = encodeSealEnvelope(env);
817
- const decryptionHint = { epoch: keys.epoch, scheme: CLUSTER_MLKEM_SHAMIR };
818
- const digest = outerSigDigest(args.aad, ciphertext, decryptionHint, senderPubkey);
819
- const outerSignature = expectBytes(
820
- await args.signOuterDigest(digest),
821
- ML_DSA_65_SIGNATURE_LEN,
822
- "outerSignature"
823
- );
824
- const envelope = {
825
- nonceAad: args.aad,
826
- ciphertext,
827
- decryptionHint,
828
- senderPubkey,
829
- outerSignature,
830
- sender: senderAddress
831
- };
832
- const envelopeWireBytes = bincodeEncryptedEnvelope(envelope);
833
- return {
834
- envelopeWireHex: `0x${bytesToHex(envelopeWireBytes).slice(2)}`,
835
- envelopeWireBytes,
836
- ciphertextBytes: ciphertext.length
837
- };
838
- }
839
- async function submitSealedTransaction(client, submission) {
840
- return client.call("lyth_submitEncrypted", [submission.envelopeWireHex]);
841
- }
842
- function keccak256(input) {
843
- return sha3_js.keccak_256(input);
844
- }
845
- function toBigInt(value) {
846
- if (typeof value === "bigint") return value;
847
- return BigInt(value);
848
- }
849
- function bytesEqual(a, b) {
850
- if (a.length !== b.length) return false;
851
- for (let i = 0; i < a.length; i++) {
852
- if (a[i] !== b[i]) return false;
853
- }
854
- return true;
855
- }
856
429
 
857
430
  // src/crypto/submission.ts
858
- async function fetchEncryptionKey(client) {
859
- const result = await client.call(
860
- "lyth_getEncryptionKey",
861
- []
862
- );
863
- return {
864
- algo: result.algo ?? "ml-kem-768",
865
- epoch: typeof result.epoch === "string" ? BigInt(result.epoch) : BigInt(result.epoch),
866
- encapsulationKey: hexToBytes(result.encapsulationKey, "encapsulationKey")
867
- };
868
- }
869
- var ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE = "private submission requires cluster seal keys; pass clusterSealKeysSource or enable lyth_getClusterSealKeys";
870
- async function buildEncryptedSubmission(args) {
871
- const signed = args.backend.signEvmTx(args.tx);
872
- const clusterSealKeys = await resolveClusterSealKeys(args);
873
- const aad = nonceAadForTx(args.tx, args.backend.addressBytes(), args.class);
874
- const sealed = await sealTransaction({
875
- signedTxBincode: signed.wireBytes,
876
- clusterSealKeys,
877
- aad,
878
- senderAddress: args.backend.addressBytes(),
879
- senderPubkey: args.backend.publicKey(),
880
- signOuterDigest: (digest) => args.backend.signPrehash(digest)
881
- });
882
- return {
883
- envelopeWireHex: sealed.envelopeWireHex,
884
- innerSighashHex: bytesToHex(signed.sighash),
885
- innerTxHashHex: bytesToHex(signed.txHash),
886
- innerWireBytes: signed.wireBytes.length
887
- };
888
- }
889
- async function submitEncryptedEnvelope(client, envelopeWireHex) {
890
- return client.call("lyth_submitEncrypted", [envelopeWireHex]);
891
- }
892
431
  function buildPlaintextSubmission(args) {
893
432
  const signed = args.backend.signEvmTx(args.tx);
894
433
  return {
@@ -907,29 +446,14 @@ async function submitPlaintextTransaction(client, signedTxWireHex, expectedTxHas
907
446
  );
908
447
  }
909
448
  const expectedBytes = hexToBytes(expectedTxHashHex, "expected tx hash");
910
- if (!bytesEqual2(returnedBytes, expectedBytes)) {
449
+ if (!bytesEqual(returnedBytes, expectedBytes)) {
911
450
  throw new Error(
912
451
  `mesh_submitTx returned tx hash ${bytesToHex(returnedBytes)} but the locally computed canonical hash is ${bytesToHex(expectedBytes)}`
913
452
  );
914
453
  }
915
454
  return bytesToHex(returnedBytes);
916
455
  }
917
- async function submitTransactionWithPrivacy(args) {
918
- if (args.private) {
919
- const built = await buildEncryptedSubmission({
920
- client: args.client,
921
- backend: args.backend,
922
- tx: args.tx,
923
- encryptionKey: args.encryptionKey,
924
- clusterId: args.clusterId,
925
- clusterSealKeys: args.clusterSealKeys,
926
- clusterSealKeysSource: args.clusterSealKeysSource,
927
- class: args.class
928
- });
929
- const returned = await submitEncryptedEnvelope(args.client, built.envelopeWireHex);
930
- assertRpcHash(returned, "lyth_submitEncrypted tx hash");
931
- return built.innerTxHashHex;
932
- }
456
+ async function submitTransaction(args) {
933
457
  const plaintext = buildPlaintextSubmission({ backend: args.backend, tx: args.tx });
934
458
  return submitPlaintextTransaction(
935
459
  args.client,
@@ -937,133 +461,43 @@ async function submitTransactionWithPrivacy(args) {
937
461
  plaintext.innerTxHashHex
938
462
  );
939
463
  }
940
- function bytesEqual2(a, b) {
464
+ function bytesEqual(a, b) {
941
465
  if (a.length !== b.length) return false;
942
466
  for (let i = 0; i < a.length; i++) {
943
467
  if (a[i] !== b[i]) return false;
944
468
  }
945
469
  return true;
946
470
  }
947
- async function resolveClusterSealKeys(args) {
948
- if (args.clusterSealKeys !== void 0) return args.clusterSealKeys;
949
- if (args.clusterSealKeysSource !== void 0) {
950
- return parseClusterSealKeys(args.clusterSealKeysSource);
951
- }
952
- if (args.client === void 0) {
953
- throw new Error(ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE);
954
- }
955
- const clusterId = args.clusterId ?? 0;
956
- const result = await args.client.call(
957
- "lyth_getClusterSealKeys",
958
- [clusterId]
959
- );
960
- return parseClusterSealKeys({ ...result, clusterId: result.clusterId ?? clusterId });
961
- }
962
- function nonceAadForTx(tx, sender, mempoolClass) {
963
- return {
964
- sender,
965
- nonce: parseBigint(tx.nonce, "nonce"),
966
- chainId: parseBigint(tx.chainId, "chainId"),
967
- class: mempoolClass ?? inferMempoolClass(tx),
968
- maxFeePerGas: parseBigint(tx.maxFeePerGas, "maxFeePerGas"),
969
- maxPriorityFeePerGas: parseBigint(tx.maxPriorityFeePerGas, "maxPriorityFeePerGas"),
970
- gasLimit: parseBigint(tx.gasLimit, "gasLimit")
971
- };
972
- }
973
- function inferMempoolClass(tx) {
974
- if (tx.to === null || hasInput(tx.input)) return MempoolClass.ContractCall;
975
- return MempoolClass.Transfer;
976
- }
977
- function hasInput(input) {
978
- if (input === void 0) return false;
979
- if (typeof input === "string") {
980
- const stripped = input.startsWith("0x") || input.startsWith("0X") ? input.slice(2) : input;
981
- return stripped.length > 0;
982
- }
983
- return input.length > 0;
984
- }
985
- function assertRpcHash(value, label) {
986
- const bytes = hexToBytes(value, label);
987
- if (bytes.length !== 32) {
988
- throw new Error(`${label} must be 32 bytes, got ${bytes.length}`);
989
- }
990
- }
991
471
 
992
472
  exports.ADDRESS_DERIVATION_DOMAIN = ADDRESS_DERIVATION_DOMAIN;
993
473
  exports.BincodeWriter = BincodeWriter;
994
- exports.CLUSTER_MLKEM_SHAMIR = CLUSTER_MLKEM_SHAMIR;
995
- exports.CLUSTER_MLKEM_SHAMIR_ALGO = CLUSTER_MLKEM_SHAMIR_ALGO;
996
- exports.DKG_AEAD_TAG_LEN = DKG_AEAD_TAG_LEN;
997
- exports.DKG_NONCE_LEN = DKG_NONCE_LEN;
998
- exports.ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE = ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE;
999
474
  exports.ENUM_VARIANT_INDEX_ML_DSA_65 = ENUM_VARIANT_INDEX_ML_DSA_65;
475
+ exports.MLDSA65_MNEMONIC_WORDS = MLDSA65_MNEMONIC_WORDS;
476
+ exports.MLDSA65_SEED_DOMAIN = MLDSA65_SEED_DOMAIN;
1000
477
  exports.ML_DSA_65_PUBLIC_KEY_LEN = ML_DSA_65_PUBLIC_KEY_LEN;
1001
478
  exports.ML_DSA_65_SEED_LEN = ML_DSA_65_SEED_LEN;
1002
479
  exports.ML_DSA_65_SIGNATURE_LEN = ML_DSA_65_SIGNATURE_LEN;
1003
480
  exports.ML_DSA_65_SIGNING_KEY_LEN = ML_DSA_65_SIGNING_KEY_LEN;
1004
- exports.ML_KEM_768_CIPHERTEXT_LEN = ML_KEM_768_CIPHERTEXT_LEN;
1005
- exports.ML_KEM_768_ENCAPSULATION_KEY_LEN = ML_KEM_768_ENCAPSULATION_KEY_LEN;
1006
- exports.ML_KEM_768_SHARED_SECRET_LEN = ML_KEM_768_SHARED_SECRET_LEN;
1007
481
  exports.MempoolClass = MempoolClass;
1008
482
  exports.MlDsa65Backend = MlDsa65Backend;
1009
- exports.PQM1_ALGO_TAG_FALCON512_RESERVED = PQM1_ALGO_TAG_FALCON512_RESERVED;
1010
- exports.PQM1_ALGO_TAG_MLDSA65 = PQM1_ALGO_TAG_MLDSA65;
1011
- exports.PQM1_ALGO_TAG_MLDSA87_RESERVED = PQM1_ALGO_TAG_MLDSA87_RESERVED;
1012
- exports.PQM1_ALGO_TAG_SLHDSA128S_RESERVED = PQM1_ALGO_TAG_SLHDSA128S_RESERVED;
1013
- exports.PQM1_ENTROPY_LEN = PQM1_ENTROPY_LEN;
1014
- exports.PQM1_PAYLOAD_LEN = PQM1_PAYLOAD_LEN;
1015
- exports.PQM1_V1_MLDSA65_DOMAIN_TAG = PQM1_V1_MLDSA65_DOMAIN_TAG;
1016
- exports.PQM1_V1_MNEMONIC_WORDS = PQM1_V1_MNEMONIC_WORDS;
1017
- exports.PQM1_VERSION_V1 = PQM1_VERSION_V1;
1018
- exports.Pqm1Error = Pqm1Error;
1019
- exports.SEAL_COMMIT_LEN = SEAL_COMMIT_LEN;
1020
- exports.SEAL_DK_LEN = SEAL_DK_LEN;
1021
- exports.SEAL_EK_LEN = SEAL_EK_LEN;
1022
- exports.SEAL_KEM_CT_LEN = SEAL_KEM_CT_LEN;
1023
- exports.SEAL_KEM_SEED_LEN = SEAL_KEM_SEED_LEN;
1024
- exports.SEAL_KEY_LEN = SEAL_KEY_LEN;
1025
- exports.SEAL_NONCE_LEN = SEAL_NONCE_LEN;
1026
- exports.SEAL_SHARE_LEN = SEAL_SHARE_LEN;
1027
- exports.SEAL_TAG_LEN = SEAL_TAG_LEN;
483
+ exports.MnemonicError = MnemonicError;
1028
484
  exports.STANDARD_ALGO_NUMBER_ML_DSA_65 = STANDARD_ALGO_NUMBER_ML_DSA_65;
1029
- exports.assemblePqm1Payload = assemblePqm1Payload;
1030
- exports.bincodeDecryptHint = bincodeDecryptHint;
1031
- exports.bincodeEncryptedEnvelope = bincodeEncryptedEnvelope;
1032
- exports.bincodeNonceAad = bincodeNonceAad;
1033
485
  exports.bincodeSignedTransaction = bincodeSignedTransaction;
1034
- exports.buildEncryptedEnvelope = buildEncryptedEnvelope;
1035
- exports.buildEncryptedSubmission = buildEncryptedSubmission;
1036
486
  exports.buildPlaintextSubmission = buildPlaintextSubmission;
1037
487
  exports.bytesToHex = bytesToHex;
1038
488
  exports.concatBytes = concatBytes;
1039
- exports.cryptoRandomSource = cryptoRandomSource;
1040
- exports.derivePqm1MlDsa65SeedFromPayload = derivePqm1MlDsa65SeedFromPayload;
1041
489
  exports.encodeMlDsa65Opaque = encodeMlDsa65Opaque;
1042
- exports.encodeSealEnvelope = encodeSealEnvelope;
1043
490
  exports.encodeTransactionForHash = encodeTransactionForHash;
1044
- exports.encryptInnerTx = encryptInnerTx;
1045
491
  exports.expectBytes = expectBytes;
1046
- exports.fetchEncryptionKey = fetchEncryptionKey;
1047
- exports.generateOperatorSealKeypair = generateOperatorSealKeypair;
1048
- exports.generatePqm1Mnemonic = generatePqm1Mnemonic;
1049
- exports.getClusterSealKeys = getClusterSealKeys;
492
+ exports.generateMnemonic = generateMnemonic;
1050
493
  exports.hexToBytes = hexToBytes;
1051
494
  exports.mlDsa65AddressBytes = mlDsa65AddressBytes;
1052
495
  exports.mlDsa65AddressFromPublicKey = mlDsa65AddressFromPublicKey;
1053
- exports.outerSigDigest = outerSigDigest;
1054
- exports.parseClusterSealKeys = parseClusterSealKeys;
1055
- exports.parsePqm1Payload = parsePqm1Payload;
1056
- exports.pqm1MnemonicToAddress = pqm1MnemonicToAddress;
1057
- exports.pqm1MnemonicToMlDsa65Backend = pqm1MnemonicToMlDsa65Backend;
1058
- exports.pqm1MnemonicToMlDsa65Seed = pqm1MnemonicToMlDsa65Seed;
1059
- exports.pqm1MnemonicToPayload = pqm1MnemonicToPayload;
1060
- exports.pqm1PayloadToMnemonic = pqm1PayloadToMnemonic;
1061
- exports.sealRosterHash = sealRosterHash;
1062
- exports.sealToCluster = sealToCluster;
1063
- exports.sealTransaction = sealTransaction;
1064
- exports.submitEncryptedEnvelope = submitEncryptedEnvelope;
496
+ exports.mnemonicToAddress = mnemonicToAddress;
497
+ exports.mnemonicToMlDsa65Backend = mnemonicToMlDsa65Backend;
498
+ exports.mnemonicToMlDsa65Seed = mnemonicToMlDsa65Seed;
1065
499
  exports.submitPlaintextTransaction = submitPlaintextTransaction;
1066
- exports.submitSealedTransaction = submitSealedTransaction;
1067
- exports.submitTransactionWithPrivacy = submitTransactionWithPrivacy;
500
+ exports.submitTransaction = submitTransaction;
501
+ exports.validateMnemonic = validateMnemonic;
1068
502
  //# sourceMappingURL=index.cjs.map
1069
503
  //# sourceMappingURL=index.cjs.map