@monolythium/core-sdk 0.3.15 → 0.4.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.
package/README.md CHANGED
@@ -264,6 +264,56 @@ const backend = pqm1MnemonicToMlDsa65Backend(mnemonic);
264
264
  const signature = backend.sign(new Uint8Array([1, 2, 3]));
265
265
  ```
266
266
 
267
+ ### LythiumSeal scheme-3 (encrypted mempool)
268
+
269
+ The SDK can seal a signed transaction to a cluster's post-quantum
270
+ threshold recipient set so that no single operator can read the body. The
271
+ scheme is cluster-ML-KEM-768 (FIPS-203) + GF(256) Shamir `t`-of-`n` +
272
+ committing ChaCha20-Poly1305 with an explicit SHAKE256 key-commitment. The
273
+ TypeScript seal is byte-exact against the chain: a cross-language known-
274
+ answer test reproduces the exact envelope bincode bytes the node accepts.
275
+
276
+ ```ts
277
+ import {
278
+ getClusterSealKeys,
279
+ parseClusterSealKeys,
280
+ sealTransaction,
281
+ submitSealedTransaction,
282
+ MempoolClass,
283
+ } from "@monolythium/core-sdk/crypto";
284
+
285
+ // Read the cluster seal roster. On nodes that disable
286
+ // `lyth_getClusterSealKeys` (the public profile), read the roster from
287
+ // genesis (`[[clusters.members]]` `seal_ek`) and pass it through
288
+ // `parseClusterSealKeys` instead - the roster hash is recomputed and
289
+ // verified against the ek set so a wallet cannot seal under a mismatched
290
+ // roster hash.
291
+ const clusterSealKeys = await getClusterSealKeys(client, 0);
292
+
293
+ // `aad` fee fields MUST mirror the signed inner tx exactly (Law §3.6).
294
+ const submission = await sealTransaction({
295
+ signedTxBincode, // bincode SignedTransaction wire bytes
296
+ clusterSealKeys,
297
+ aad: {
298
+ sender, // 20-byte address
299
+ nonce,
300
+ chainId,
301
+ class: MempoolClass.Transfer,
302
+ maxFeePerGas,
303
+ maxPriorityFeePerGas,
304
+ gasLimit,
305
+ },
306
+ senderAddress: sender,
307
+ senderPubkey, // 1952-byte ML-DSA-65 public key
308
+ signOuterDigest: (digest) => backend.sign(digest),
309
+ });
310
+
311
+ await submitSealedTransaction(client, submission);
312
+ ```
313
+
314
+ The lower-level `sealToCluster` / `encodeSealEnvelope` / `sealRosterHash`
315
+ primitives are also exported for callers that build the envelope directly.
316
+
267
317
  ### ethers / viem compatibility
268
318
 
269
319
  The SDK does not ship an ethers-style provider or signer. The chain
@@ -577,9 +577,326 @@ function bytesEqual(a, b) {
577
577
  }
578
578
  return true;
579
579
  }
580
+ var SEAL_EK_LEN = 1184;
581
+ var SEAL_DK_LEN = 2400;
582
+ var SEAL_KEM_CT_LEN = 1088;
583
+ var SEAL_KEM_SEED_LEN = 64;
584
+ var SEAL_KEY_LEN = 32;
585
+ var SEAL_NONCE_LEN = 12;
586
+ var SEAL_TAG_LEN = 16;
587
+ var SEAL_COMMIT_LEN = 32;
588
+ var SEAL_SECRET_LEN = 32;
589
+ var SEAL_SHARE_LEN = 1 + SEAL_SECRET_LEN;
590
+ var CLUSTER_MLKEM_SHAMIR = 3;
591
+ var COMMIT_DOMAIN = new TextEncoder().encode("lythiumseal/commit/v1");
592
+ var KEK_DOMAIN = new TextEncoder().encode("lythiumseal/kek/v1");
593
+ var NONCE_DOMAIN = new TextEncoder().encode("lythiumseal/nonce/v1");
594
+ var BODY_AAD_DOMAIN = new TextEncoder().encode("lythiumseal/body/v1");
595
+ var SHARE_AAD_DOMAIN = new TextEncoder().encode("lythiumseal/share/v1");
596
+ var ROSTER_DOMAIN = new TextEncoder().encode("lythiumseal/roster/v1");
597
+ function cryptoRandomSource() {
598
+ return {
599
+ fillBytes(dest) {
600
+ crypto.getRandomValues(dest);
601
+ }
602
+ };
603
+ }
604
+ function u32le(n) {
605
+ const out = new Uint8Array(4);
606
+ out[0] = n & 255;
607
+ out[1] = n >>> 8 & 255;
608
+ out[2] = n >>> 16 & 255;
609
+ out[3] = n >>> 24 & 255;
610
+ return out;
611
+ }
612
+ function u64le(n) {
613
+ const out = new Uint8Array(8);
614
+ let v = n;
615
+ for (let i = 0; i < 8; i++) {
616
+ out[i] = Number(v & 0xffn);
617
+ v >>= 8n;
618
+ }
619
+ return out;
620
+ }
621
+ function framed(field) {
622
+ return concatBytes(u32le(field.length), field);
623
+ }
624
+ function keyCommitment(key) {
625
+ return sha3_js.shake256(concatBytes(framed(COMMIT_DOMAIN), key), { dkLen: SEAL_COMMIT_LEN });
626
+ }
627
+ function deriveKek(sharedSecret, domain, clusterId, epoch, opIndex) {
628
+ const input = concatBytes(
629
+ framed(KEK_DOMAIN),
630
+ framed(sharedSecret),
631
+ framed(domain),
632
+ u32le(clusterId),
633
+ u64le(epoch),
634
+ Uint8Array.of(opIndex)
635
+ );
636
+ return sha3_js.shake256(input, { dkLen: SEAL_KEY_LEN });
637
+ }
638
+ function deriveNonce(domain, context) {
639
+ const input = concatBytes(framed(NONCE_DOMAIN), framed(domain), framed(context));
640
+ return sha3_js.shake256(input, { dkLen: SEAL_NONCE_LEN });
641
+ }
642
+ function bodyAad(ctx, k, n) {
643
+ return concatBytes(
644
+ BODY_AAD_DOMAIN,
645
+ u32le(ctx.clusterId),
646
+ u64le(ctx.epoch),
647
+ Uint8Array.of(k),
648
+ Uint8Array.of(n),
649
+ ctx.rosterHash
650
+ );
651
+ }
652
+ function shareAad(ctx, opIndex) {
653
+ return concatBytes(
654
+ SHARE_AAD_DOMAIN,
655
+ u32le(ctx.clusterId),
656
+ u64le(ctx.epoch),
657
+ Uint8Array.of(opIndex),
658
+ ctx.rosterHash
659
+ );
660
+ }
661
+ function aeadSeal(key, nonce, plaintext, aad) {
662
+ const cipher = chacha_js.chacha20poly1305(key, nonce, aad);
663
+ const ct = cipher.encrypt(plaintext);
664
+ return { nonce, ct, commitment: keyCommitment(key) };
665
+ }
666
+ function gfMul(a, b) {
667
+ let product = 0;
668
+ let x = a & 255;
669
+ let y = b & 255;
670
+ for (let i = 0; i < 8; i++) {
671
+ const mask = -(y & 1) & 255;
672
+ product ^= x & mask;
673
+ const high = -(x >> 7 & 1) & 255;
674
+ x = x << 1 & 255;
675
+ x ^= 27 & high;
676
+ y >>= 1;
677
+ }
678
+ return product & 255;
679
+ }
680
+ function polyEval(coeffs, x) {
681
+ let acc = 0;
682
+ for (let i = coeffs.length - 1; i >= 0; i--) {
683
+ acc = gfMul(acc, x) ^ coeffs[i];
684
+ }
685
+ return acc & 255;
686
+ }
687
+ function shamirSplit(secret, t, n, rng) {
688
+ const byteCoeffs = [];
689
+ for (let j = 0; j < SEAL_SECRET_LEN; j++) {
690
+ const c = new Uint8Array(t);
691
+ c[0] = secret[j];
692
+ if (t > 1) {
693
+ const tail = new Uint8Array(t - 1);
694
+ rng.fillBytes(tail);
695
+ c.set(tail, 1);
696
+ }
697
+ byteCoeffs.push(c);
698
+ }
699
+ const shares = [];
700
+ for (let k = 0; k < n; k++) {
701
+ const x = k + 1 & 255;
702
+ const value = new Uint8Array(SEAL_SECRET_LEN);
703
+ for (let j = 0; j < SEAL_SECRET_LEN; j++) {
704
+ value[j] = polyEval(byteCoeffs[j], x);
705
+ }
706
+ shares.push({ index: x, value });
707
+ }
708
+ return shares;
709
+ }
710
+ function shareToBytes(s) {
711
+ const out = new Uint8Array(SEAL_SHARE_LEN);
712
+ out[0] = s.index;
713
+ out.set(s.value, 1);
714
+ return out;
715
+ }
716
+ function sealRosterHash(keccak2562, clusterId, t, n, roster) {
717
+ const chunks = [ROSTER_DOMAIN, u32le(clusterId), Uint8Array.of(t), Uint8Array.of(n)];
718
+ for (const { operatorIndex, ek } of roster) {
719
+ chunks.push(Uint8Array.of(operatorIndex), ek);
720
+ }
721
+ return keccak2562(concatBytes(...chunks));
722
+ }
723
+ function encodeSealEnvelope(env) {
724
+ const chunks = [];
725
+ chunks.push(u32le(env.clusterId));
726
+ chunks.push(u64le(env.epoch));
727
+ chunks.push(expectBytes(env.rosterHash, 32, "rosterHash"));
728
+ chunks.push(Uint8Array.of(env.t));
729
+ chunks.push(Uint8Array.of(env.n));
730
+ pushAeadBody(chunks, env.aeadBody);
731
+ chunks.push(u64le(BigInt(env.recipients.length)));
732
+ for (const r of env.recipients) {
733
+ chunks.push(Uint8Array.of(r.operatorIndex));
734
+ chunks.push(u64le(BigInt(r.kemCt.length)));
735
+ chunks.push(r.kemCt);
736
+ pushAeadBody(chunks, r.wrapped);
737
+ }
738
+ return concatBytes(...chunks);
739
+ }
740
+ function pushAeadBody(chunks, body) {
741
+ chunks.push(expectBytes(body.nonce, SEAL_NONCE_LEN, "aead nonce"));
742
+ chunks.push(u64le(BigInt(body.ct.length)));
743
+ chunks.push(body.ct);
744
+ chunks.push(expectBytes(body.commitment, SEAL_COMMIT_LEN, "aead commitment"));
745
+ }
746
+ function sealToCluster(args) {
747
+ const { plaintext, recipientEks, t, clusterId } = args;
748
+ const epoch = args.epoch;
749
+ const rosterHash = expectBytes(args.rosterHash, 32, "rosterHash");
750
+ const rng = args.rng ?? cryptoRandomSource();
751
+ const n = recipientEks.length;
752
+ if (!Number.isInteger(t) || t < 1 || t > n || n < 1 || n > 255) {
753
+ throw new Error(`invalid threshold/recipient count: t=${t} n=${n}`);
754
+ }
755
+ for (let i = 0; i < n; i++) {
756
+ expectBytes(recipientEks[i], SEAL_EK_LEN, `recipientEks[${i}]`);
757
+ }
758
+ const ctx = { clusterId, epoch, rosterHash };
759
+ const bodyKey = new Uint8Array(SEAL_KEY_LEN);
760
+ rng.fillBytes(bodyKey);
761
+ const aad = bodyAad(ctx, t, n);
762
+ const bodyNonce = deriveNonce(new TextEncoder().encode("body"), aad);
763
+ const aeadBody = aeadSeal(bodyKey, bodyNonce, plaintext, aad);
764
+ const shares = shamirSplit(bodyKey, t, n, rng);
765
+ const recipients = [];
766
+ for (let i = 0; i < n; i++) {
767
+ const opIndex = i + 1 & 255;
768
+ const m = new Uint8Array(32);
769
+ rng.fillBytes(m);
770
+ const { cipherText: kemCt, sharedSecret } = mlKem_js.ml_kem768.encapsulate(recipientEks[i], m);
771
+ const kek = deriveKek(sharedSecret, rosterHash, clusterId, epoch, opIndex);
772
+ const sAad = shareAad(ctx, opIndex);
773
+ const wrapNonce = deriveNonce(new TextEncoder().encode("share"), sAad);
774
+ const wrapped = aeadSeal(kek, wrapNonce, shareToBytes(shares[i]), sAad);
775
+ recipients.push({ operatorIndex: opIndex, kemCt, wrapped });
776
+ sharedSecret.fill(0);
777
+ kek.fill(0);
778
+ }
779
+ bodyKey.fill(0);
780
+ return {
781
+ clusterId,
782
+ epoch,
783
+ rosterHash,
784
+ t,
785
+ n,
786
+ aeadBody,
787
+ recipients
788
+ };
789
+ }
790
+ var CLUSTER_MLKEM_SHAMIR_ALGO = "cluster-mlkem768-shamir";
791
+ function parseClusterSealKeys(source) {
792
+ const n = source.roster.length;
793
+ if (n === 0) {
794
+ throw new Error("cluster seal roster is empty");
795
+ }
796
+ if (source.n !== n) {
797
+ throw new Error(`cluster seal roster n=${source.n} disagrees with ${n} entries`);
798
+ }
799
+ if (!Number.isInteger(source.t) || source.t < 2 || source.t > n) {
800
+ throw new Error(`cluster seal threshold t=${source.t} out of range 2..=${n}`);
801
+ }
802
+ const sorted = [...source.roster].sort((a, b) => a.operatorIndex - b.operatorIndex);
803
+ const recipientEks = [];
804
+ const hashInput = [];
805
+ for (let i = 0; i < n; i++) {
806
+ const entry = sorted[i];
807
+ if (entry.operatorIndex !== i + 1) {
808
+ throw new Error(
809
+ `cluster seal roster operator indices must be 1..=${n}; got ${entry.operatorIndex} at slot ${i + 1}`
810
+ );
811
+ }
812
+ const ek = expectBytes(hexToBytes(entry.mlKemEk, `operator ${entry.operatorIndex} mlKemEk`), SEAL_EK_LEN, `operator ${entry.operatorIndex} ek`);
813
+ recipientEks.push(ek);
814
+ hashInput.push({ operatorIndex: entry.operatorIndex, ek });
815
+ }
816
+ const recomputed = sealRosterHash(keccak256, source.clusterId, source.t, n, hashInput);
817
+ if (source.rosterHash !== void 0) {
818
+ const supplied = expectBytes(hexToBytes(source.rosterHash, "rosterHash"), 32, "rosterHash");
819
+ if (!bytesEqual2(supplied, recomputed)) {
820
+ throw new Error(
821
+ `cluster seal roster hash mismatch: source ${bytesToHex(supplied)} != recomputed ${bytesToHex(recomputed)} (the roster hash does not commit to this ek set)`
822
+ );
823
+ }
824
+ }
825
+ return {
826
+ algo: source.algo ?? CLUSTER_MLKEM_SHAMIR_ALGO,
827
+ clusterId: source.clusterId,
828
+ epoch: toBigInt(source.epoch),
829
+ rosterHash: recomputed,
830
+ t: source.t,
831
+ n,
832
+ recipientEks
833
+ };
834
+ }
835
+ async function getClusterSealKeys(client, clusterId = 0) {
836
+ const result = await client.call(
837
+ "lyth_getClusterSealKeys",
838
+ [clusterId]
839
+ );
840
+ return parseClusterSealKeys({ ...result, clusterId: result.clusterId ?? clusterId });
841
+ }
842
+ async function sealTransaction(args) {
843
+ const keys = args.clusterSealKeys;
844
+ const senderPubkey = expectBytes(args.senderPubkey, ML_DSA_65_PUBLIC_KEY_LEN, "senderPubkey");
845
+ const senderAddress = expectBytes(args.senderAddress, 20, "senderAddress");
846
+ const env = sealToCluster({
847
+ plaintext: args.signedTxBincode,
848
+ recipientEks: keys.recipientEks,
849
+ t: keys.t,
850
+ clusterId: keys.clusterId,
851
+ epoch: keys.epoch,
852
+ rosterHash: keys.rosterHash,
853
+ rng: args.rng
854
+ });
855
+ const ciphertext = encodeSealEnvelope(env);
856
+ const decryptionHint = { epoch: keys.epoch, scheme: CLUSTER_MLKEM_SHAMIR };
857
+ const digest = outerSigDigest(args.aad, ciphertext, decryptionHint, senderPubkey);
858
+ const outerSignature = expectBytes(
859
+ await args.signOuterDigest(digest),
860
+ ML_DSA_65_SIGNATURE_LEN,
861
+ "outerSignature"
862
+ );
863
+ const envelope = {
864
+ nonceAad: args.aad,
865
+ ciphertext,
866
+ decryptionHint,
867
+ senderPubkey,
868
+ outerSignature,
869
+ sender: senderAddress
870
+ };
871
+ const envelopeWireBytes = bincodeEncryptedEnvelope(envelope);
872
+ return {
873
+ envelopeWireHex: `0x${bytesToHex(envelopeWireBytes).slice(2)}`,
874
+ envelopeWireBytes,
875
+ ciphertextBytes: ciphertext.length
876
+ };
877
+ }
878
+ async function submitSealedTransaction(client, submission) {
879
+ return client.call("lyth_submitEncrypted", [submission.envelopeWireHex]);
880
+ }
881
+ function keccak256(input) {
882
+ return sha3_js.keccak_256(input);
883
+ }
884
+ function toBigInt(value) {
885
+ if (typeof value === "bigint") return value;
886
+ return BigInt(value);
887
+ }
888
+ function bytesEqual2(a, b) {
889
+ if (a.length !== b.length) return false;
890
+ for (let i = 0; i < a.length; i++) {
891
+ if (a[i] !== b[i]) return false;
892
+ }
893
+ return true;
894
+ }
580
895
 
581
896
  exports.ADDRESS_DERIVATION_DOMAIN = ADDRESS_DERIVATION_DOMAIN;
582
897
  exports.BincodeWriter = BincodeWriter;
898
+ exports.CLUSTER_MLKEM_SHAMIR = CLUSTER_MLKEM_SHAMIR;
899
+ exports.CLUSTER_MLKEM_SHAMIR_ALGO = CLUSTER_MLKEM_SHAMIR_ALGO;
583
900
  exports.DKG_AEAD_TAG_LEN = DKG_AEAD_TAG_LEN;
584
901
  exports.DKG_NONCE_LEN = DKG_NONCE_LEN;
585
902
  exports.ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE = ENCRYPTED_SUBMISSION_UNAVAILABLE_MESSAGE;
@@ -603,6 +920,15 @@ exports.PQM1_V1_MLDSA65_DOMAIN_TAG = PQM1_V1_MLDSA65_DOMAIN_TAG;
603
920
  exports.PQM1_V1_MNEMONIC_WORDS = PQM1_V1_MNEMONIC_WORDS;
604
921
  exports.PQM1_VERSION_V1 = PQM1_VERSION_V1;
605
922
  exports.Pqm1Error = Pqm1Error;
923
+ exports.SEAL_COMMIT_LEN = SEAL_COMMIT_LEN;
924
+ exports.SEAL_DK_LEN = SEAL_DK_LEN;
925
+ exports.SEAL_EK_LEN = SEAL_EK_LEN;
926
+ exports.SEAL_KEM_CT_LEN = SEAL_KEM_CT_LEN;
927
+ exports.SEAL_KEM_SEED_LEN = SEAL_KEM_SEED_LEN;
928
+ exports.SEAL_KEY_LEN = SEAL_KEY_LEN;
929
+ exports.SEAL_NONCE_LEN = SEAL_NONCE_LEN;
930
+ exports.SEAL_SHARE_LEN = SEAL_SHARE_LEN;
931
+ exports.SEAL_TAG_LEN = SEAL_TAG_LEN;
606
932
  exports.STANDARD_ALGO_NUMBER_ML_DSA_65 = STANDARD_ALGO_NUMBER_ML_DSA_65;
607
933
  exports.assemblePqm1Payload = assemblePqm1Payload;
608
934
  exports.bincodeDecryptHint = bincodeDecryptHint;
@@ -614,25 +940,33 @@ exports.buildEncryptedSubmission = buildEncryptedSubmission;
614
940
  exports.buildPlaintextSubmission = buildPlaintextSubmission;
615
941
  exports.bytesToHex = bytesToHex;
616
942
  exports.concatBytes = concatBytes;
943
+ exports.cryptoRandomSource = cryptoRandomSource;
617
944
  exports.derivePqm1MlDsa65SeedFromPayload = derivePqm1MlDsa65SeedFromPayload;
618
945
  exports.encodeMlDsa65Opaque = encodeMlDsa65Opaque;
946
+ exports.encodeSealEnvelope = encodeSealEnvelope;
619
947
  exports.encodeTransactionForHash = encodeTransactionForHash;
620
948
  exports.encryptInnerTx = encryptInnerTx;
621
949
  exports.expectBytes = expectBytes;
622
950
  exports.fetchEncryptionKey = fetchEncryptionKey;
623
951
  exports.generatePqm1Mnemonic = generatePqm1Mnemonic;
952
+ exports.getClusterSealKeys = getClusterSealKeys;
624
953
  exports.hexToBytes = hexToBytes;
625
954
  exports.mlDsa65AddressBytes = mlDsa65AddressBytes;
626
955
  exports.mlDsa65AddressFromPublicKey = mlDsa65AddressFromPublicKey;
627
956
  exports.outerSigDigest = outerSigDigest;
957
+ exports.parseClusterSealKeys = parseClusterSealKeys;
628
958
  exports.parsePqm1Payload = parsePqm1Payload;
629
959
  exports.pqm1MnemonicToAddress = pqm1MnemonicToAddress;
630
960
  exports.pqm1MnemonicToMlDsa65Backend = pqm1MnemonicToMlDsa65Backend;
631
961
  exports.pqm1MnemonicToMlDsa65Seed = pqm1MnemonicToMlDsa65Seed;
632
962
  exports.pqm1MnemonicToPayload = pqm1MnemonicToPayload;
633
963
  exports.pqm1PayloadToMnemonic = pqm1PayloadToMnemonic;
964
+ exports.sealRosterHash = sealRosterHash;
965
+ exports.sealToCluster = sealToCluster;
966
+ exports.sealTransaction = sealTransaction;
634
967
  exports.submitEncryptedEnvelope = submitEncryptedEnvelope;
635
968
  exports.submitPlaintextTransaction = submitPlaintextTransaction;
969
+ exports.submitSealedTransaction = submitSealedTransaction;
636
970
  exports.submitTransactionWithPrivacy = submitTransactionWithPrivacy;
637
971
  //# sourceMappingURL=index.cjs.map
638
972
  //# sourceMappingURL=index.cjs.map