const { expect } = require("chai"); const { ethers } = require("hardhat"); const time = { latest: async () => (await ethers.provider.getBlock("latest")).timestamp, increase: async (s) => { await ethers.provider.send("evm_increaseTime", [s]); await ethers.provider.send("evm_mine", []); }, }; const OP = ethers.toUtf8Bytes("HASHFORT_V3_OP"), REC = ethers.toUtf8Bytes("HASHFORT_V3_RECOVERY"); const E = (n) => ethers.parseEther(String(n)); describe("QuantumVaultV3: ML-DSA-65 primary key, SLH-DSA-SHA2-128s recovery key", function () { this.timeout(900_000); let ml, slh, sdk, factory, mv, owner, relayer, alice, sentinelW, g1, g2, vault, key1, rec1, keyArgs1; const mlKey = (label) => { const k = ml.keygen(ethers.getBytes(ethers.id(label))); const { A, B } = sdk.precompute(k.publicKey); return { ...k, A, B, pkHash: ethers.keccak256(k.publicKey) }; }; const slhKey = (label) => slh.keygen(ethers.getBytes(ethers.id(label) + ethers.id(label + "2").slice(2)).slice(0, 48)); const keyStruct = async (k) => [await factory.dataAddress(k.A), await factory.dataAddress(k.B), k.pkHash]; const self = (fn, args) => ({ target: vault.target, value: 0n, data: vault.interface.encodeFunctionData(fn, args) }); async function run(calls, k = key1, { deadlineIn = 600 } = {}) { const deadline = (await time.latest()) + deadlineIn; const tuples = calls.map((c) => [c.target, c.value, c.data]); const digest = await vault.opDigest(tuples, deadline); const sig = ml.sign(ethers.getBytes(digest), k.secretKey, { context: OP }); const tx = await vault.connect(relayer).execute(tuples, deadline, sig); return { tx, rc: await tx.wait(), sig, deadline, tuples }; } before(async () => { ({ ml_dsa65: ml } = await import("@noble/post-quantum/ml-dsa.js")); ({ slh_dsa_sha2_128s: slh } = await import("@noble/post-quantum/slh-dsa.js")); sdk = await import("../sdk/mldsa65.mjs"); [owner, relayer, alice, sentinelW, g1, g2] = await ethers.getSigners(); mv = await (await ethers.getContractFactory("MLDSA65Verifier")).deploy(); const sv = await (await ethers.getContractFactory("SLHDSA128sVerifier")).deploy(); factory = await (await ethers.getContractFactory("QuantumVaultFactoryV3")).deploy(mv.target, sv.target); key1 = mlKey("primary one"); rec1 = slhKey("recovery one"); }); it("creates the vault and stores the key data in one transaction, at a predictable address", async () => { const recoveryKey = ethers.hexlify(rec1.publicKey); const predicted = await factory.predict(owner.address, key1.pkHash, recoveryKey, E("0.1"), ethers.ZeroHash); const tx = await factory.createWithKey(owner.address, key1.A, key1.B, key1.pkHash, recoveryKey, E("0.1"), ethers.ZeroHash); const rc = await tx.wait(); console.log(` createWithKey: ${rc.gasUsed.toLocaleString()} gas (one-time: key data + vault)`); vault = await ethers.getContractAt("QuantumVaultV3", predicted); keyArgs1 = await keyStruct(key1); const p = await vault.primary(); expect([p.dataA, p.dataB, p.pkHash]).to.deep.equal(keyArgs1); expect(await vault.recoveryKey()).to.equal(recoveryKey); expect(await mv.checkExpansion(key1.publicKey, p.dataA, p.dataB, { gasLimit: 400_000_000 })).to.equal(true); await owner.sendTransaction({ to: vault.target, value: E(5) }); }); it("primary key: an ML-DSA-65 signature from the browser library withdraws; it works once", async () => { const before = await ethers.provider.getBalance(alice.address); const { rc, sig, deadline, tuples } = await run([{ target: alice.address, value: E(1), data: "0x" }]); console.log(` execute (1 transfer): ${rc.gasUsed.toLocaleString()} gas`); expect(await ethers.provider.getBalance(alice.address)).to.equal(before + E(1)); expect(await vault.nonce()).to.equal(1n); await expect(vault.execute(tuples, deadline, sig)).to.be.revertedWithCustomError(vault, "BadSignature"); }); it("rejects wrong keys, other contexts, tampered calls and expired deadlines", async () => { const other = mlKey("someone else"); await expect(run([{ target: alice.address, value: E(1), data: "0x" }], other)).to.be.revertedWithCustomError(vault, "BadSignature"); const deadline = (await time.latest()) + 600, tuples = [[alice.address, E(1), "0x"]]; const digest = await vault.opDigest(tuples, deadline); await expect(vault.execute(tuples, deadline, ml.sign(ethers.getBytes(digest), key1.secretKey, { context: REC }))).to.be.revertedWithCustomError(vault, "BadSignature"); const sig = ml.sign(ethers.getBytes(digest), key1.secretKey, { context: OP }); await expect(vault.execute([[alice.address, E(2), "0x"]], deadline, sig)).to.be.revertedWithCustomError(vault, "BadSignature"); await expect(run([{ target: alice.address, value: 1n, data: "0x" }], key1, { deadlineIn: -10 })).to.be.revertedWithCustomError(vault, "Expired"); }); it("daily key spends up to its limit and cannot change settings; the primary key can", async () => { await vault.connect(owner).spend(ethers.ZeroAddress, alice.address, E("0.1")); await expect(vault.connect(owner).spend(ethers.ZeroAddress, alice.address, 1n)).to.be.revertedWithCustomError(vault, "OverLimit"); await expect(vault.connect(owner).setDailyLimit(ethers.ZeroAddress, E(10))).to.be.revertedWithCustomError(vault, "NotSelf"); await run([self("setDailyLimit", [ethers.ZeroAddress, E("0.5")])]); expect(await vault.dailyLimit(ethers.ZeroAddress)).to.equal(E("0.5")); }); it("agents and Sentinel work as in v2: the Sentinel freezes, the primary key still works and unfreezes", async () => { const exp = (await time.latest()) + 7 * 86400; await run([self("setAgent", [g1.address, exp, true]), self("setAgentLimit", [g1.address, ethers.ZeroAddress, E("0.2")]), self("setSentinel", [sentinelW.address, true])]); await vault.connect(g1).agentSpend(ethers.ZeroAddress, alice.address, E("0.1")); await vault.connect(sentinelW).freeze(); await expect(vault.connect(g1).agentSpend(ethers.ZeroAddress, alice.address, 1n)).to.be.revertedWithCustomError(vault, "IsFrozen"); await expect(vault.connect(sentinelW).unfreeze()).to.be.revertedWithCustomError(vault, "NotSelf"); await run([{ target: alice.address, value: E("0.1"), data: "0x" }]); await run([self("unfreeze", [])]); expect(await vault.frozen()).to.equal(false); }); it("rotation: the primary key installs a new ML-DSA key; the old one stops working at once", async () => { const key2 = mlKey("primary two"); await factory.storeData(key2.A); await factory.storeData(key2.B); await run([self("setPrimaryKey", [await keyStruct(key2)])]); await expect(run([{ target: alice.address, value: 1n, data: "0x" }], key1)).to.be.revertedWithCustomError(vault, "BadSignature"); await run([{ target: alice.address, value: 1n, data: "0x" }], key2); key1 = key2; }); it("recovery key: an SLH-DSA signature starts a key replacement that waits 2 days and the primary key can cancel", async () => { const lost = key1, fresh = mlKey("after recovery"); await factory.storeData(fresh.A); await factory.storeData(fresh.B); const k = await keyStruct(fresh); const deadline = (await time.latest()) + 3600; const digest = await vault.recoveryDigest(k, deadline); const sig = slh.sign(ethers.getBytes(digest), rec1.secretKey, { context: REC }); const tx = await vault.connect(relayer).startKeyRecovery(k, deadline, sig); console.log(` startKeyRecovery (SLH-DSA verify): ${(await tx.wait()).gasUsed.toLocaleString()} gas`); await expect(vault.startKeyRecovery(k, deadline, sig)).to.be.revertedWithCustomError(vault, "BadSignature"); // nonce moved on await expect(vault.finishKeyRecovery()).to.be.revertedWithCustomError(vault, "NotReady"); // the owner still holds the primary key and cancels await run([self("cancelRecovery", [])], lost); expect(await vault.pendingKeyReadyAt()).to.equal(0n); await time.increase(3 * 86400); await expect(vault.finishKeyRecovery()).to.be.revertedWithCustomError(vault, "NotReady"); // a real loss: start again, nobody cancels, finish after the delay const d2 = (await time.latest()) + 3600; const sig2 = slh.sign(ethers.getBytes(await vault.recoveryDigest(k, d2)), rec1.secretKey, { context: REC }); await vault.startKeyRecovery(k, d2, sig2); await time.increase(2 * 86400 + 1); await vault.connect(alice).finishKeyRecovery(); await expect(run([{ target: alice.address, value: 1n, data: "0x" }], lost)).to.be.revertedWithCustomError(vault, "BadSignature"); await run([{ target: alice.address, value: 1n, data: "0x" }], fresh); key1 = fresh; }); it("a signature from a different recovery key is refused", async () => { const k = await keyStruct(key1), deadline = (await time.latest()) + 3600; const sig = slh.sign(ethers.getBytes(await vault.recoveryDigest(k, deadline)), slhKey("thief").secretKey, { context: REC }); await expect(vault.startKeyRecovery(k, deadline, sig)).to.be.revertedWithCustomError(vault, "BadSignature"); }); it("guardians (2 of 2) replace the daily, primary and recovery keys after their delay", async () => { await run([self("setGuardians", [[g1.address, g2.address], 2, 86400])]); const nk = mlKey("guardian key"), nr = slhKey("guardian recovery"); await factory.storeData(nk.A); await factory.storeData(nk.B); const k = await keyStruct(nk), nrk = ethers.hexlify(nr.publicKey); await vault.connect(g1).approveRecovery(alice.address, k, nrk); await vault.connect(g2).approveRecovery(alice.address, k, nrk); await expect(vault.executeRecovery(alice.address, k, nrk)).to.be.revertedWithCustomError(vault, "NotReady"); await time.increase(86401); await vault.executeRecovery(alice.address, k, nrk); expect(await vault.owner()).to.equal(alice.address); expect(await vault.recoveryKey()).to.equal(nrk); await run([{ target: g1.address, value: 1n, data: "0x" }], nk); }); it("the implementation cannot be initialised and bad key data is refused", async () => { const impl = await ethers.getContractAt("QuantumVaultV3", await factory.implementation()); await expect(impl.initialize(owner.address, keyArgs1, ethers.ZeroHash, 0)).to.be.revertedWithCustomError(impl, "AlreadyInitialized"); await expect(factory.create(owner.address, [alice.address, alice.address, ethers.id("x")], ethers.ZeroHash, 0, ethers.id("s"))).to.be.revertedWithCustomError(impl, "BadConfig"); }); });