import { describe, it, expect, vi, beforeEach } from "vitest"; import { HushKit } from "./hushkit"; import { encrypt, decrypt, generateKeyPair, bytesToHex, hexToBytes, getPublicKey } from "../crypto"; // ============ Mock Helpers ============ function createMockSigner(address = "0x1234567890abcdef1234567890abcdef12345678") { return { getAddress: vi.fn().mockResolvedValue(address), provider: { getBlockNumber: vi.fn().mockResolvedValue(100), }, } as any; } function createMockConfig(overrides: any = {}) { return { signer: createMockSigner(), contracts: { registry: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", messenger: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", }, ...overrides, }; } // ============ Constructor Tests ============ describe("HushKit", () => { describe("constructor", () => { it("should create instance with valid config", () => { const hk = new HushKit(createMockConfig()); expect(hk).toBeInstanceOf(HushKit); }); it("should throw if no provider available", () => { const signer = { provider: null } as any; expect(() => new HushKit({ signer, contracts: { registry: "0xaa", messenger: "0xbb" }, })).toThrow("Provider required"); }); it("should throw if registry address is empty", () => { expect(() => new HushKit(createMockConfig({ contracts: { registry: "", messenger: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" }, }))).toThrow("Contract addresses required"); }); it("should throw if messenger address is empty", () => { expect(() => new HushKit(createMockConfig({ contracts: { registry: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", messenger: "" }, }))).toThrow("Contract addresses required"); }); it("should throw if address format is invalid", () => { expect(() => new HushKit(createMockConfig({ contracts: { registry: "not_an_address", messenger: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" }, }))).toThrow("Invalid contract address format"); }); it("should accept explicit provider over signer provider", () => { const explicitProvider = { getBlockNumber: vi.fn() } as any; const hk = new HushKit(createMockConfig({ provider: explicitProvider })); expect(hk).toBeInstanceOf(HushKit); }); it("should default debug to false (silent)", () => { // No console output should happen during normal operations const consoleSpy = vi.spyOn(console, "log"); new HushKit(createMockConfig()); expect(consoleSpy).not.toHaveBeenCalled(); consoleSpy.mockRestore(); }); }); describe("setPrivateKey", () => { it("should accept hex string with 0x prefix", () => { const hk = new HushKit(createMockConfig()); const { privateKey } = generateKeyPair(); expect(() => hk.setPrivateKey("0x" + bytesToHex(privateKey, false))).not.toThrow(); }); it("should accept hex string without prefix", () => { const hk = new HushKit(createMockConfig()); const { privateKey } = generateKeyPair(); expect(() => hk.setPrivateKey(bytesToHex(privateKey, false))).not.toThrow(); }); }); describe("getContractAddresses", () => { it("should return contract addresses", () => { const contracts = { registry: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", messenger: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", }; const hk = new HushKit(createMockConfig({ contracts })); const result = hk.getContractAddresses(); expect(result.registry).toBe(contracts.registry); expect(result.messenger).toBe(contracts.messenger); }); it("should return a copy (not mutable reference)", () => { const hk = new HushKit(createMockConfig()); const a = hk.getContractAddresses(); const b = hk.getContractAddresses(); expect(a).not.toBe(b); expect(a).toEqual(b); }); }); }); // ============ Typed Message Protocol Tests ============ describe("Typed Message Protocol", () => { describe("sendTyped", () => { it("should serialize payload to JSON", async () => { const hk = new HushKit(createMockConfig()); const { privateKey } = generateKeyPair(); hk.setPrivateKey(bytesToHex(privateKey, false)); // Mock the send method const sendSpy = vi.spyOn(hk, "send").mockResolvedValue("0xtxhash"); interface TestMsg { type: "test"; data: number } await hk.sendTyped("0x1111111111111111111111111111111111111111", { type: "test", data: 42, }); expect(sendSpy).toHaveBeenCalledWith({ to: "0x1111111111111111111111111111111111111111", message: JSON.stringify({ type: "test", data: 42 }), }); }); }); describe("broadcastTyped", () => { it("should serialize payload and broadcast", async () => { const hk = new HushKit(createMockConfig()); const broadcastSpy = vi.spyOn(hk, "broadcast").mockResolvedValue("0xtxhash"); const recipients = [ "0x1111111111111111111111111111111111111111", "0x2222222222222222222222222222222222222222", ]; interface TaskMsg { type: "task"; id: string } await hk.broadcastTyped(recipients, { type: "task", id: "001" }); expect(broadcastSpy).toHaveBeenCalledWith( recipients, JSON.stringify({ type: "task", id: "001" }) ); }); }); describe("onMessage", () => { it("should filter messages by type field", async () => { const hk = new HushKit(createMockConfig()); // Mock subscribe to capture the callback let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: vi.fn() }; }); const handler = vi.fn(); interface ResultMsg { type: "result"; value: number } hk.onMessage("result", handler); // Simulate a matching message await subscribedCallback({ from: "0xsender", to: "0xme", content: JSON.stringify({ type: "result", value: 99 }), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 1000, txHash: "0xtx", blockNumber: 1, }); expect(handler).toHaveBeenCalledWith( { type: "result", value: 99 }, "0xsender", expect.objectContaining({ from: "0xsender" }) ); }); it("should ignore messages with different type", async () => { const hk = new HushKit(createMockConfig()); let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: vi.fn() }; }); const handler = vi.fn(); hk.onMessage("result", handler); // Send a message with a different type await subscribedCallback({ from: "0xsender", content: JSON.stringify({ type: "request", data: "hello" }), timestamp: 1000, txHash: "0xtx", blockNumber: 1, }); expect(handler).not.toHaveBeenCalled(); }); it("should silently skip non-JSON messages", async () => { const hk = new HushKit(createMockConfig()); let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: vi.fn() }; }); const handler = vi.fn(); hk.onMessage("result", handler); // Send a non-JSON message await subscribedCallback({ from: "0xsender", content: "not json at all", timestamp: 1000, txHash: "0xtx", blockNumber: 1, }); expect(handler).not.toHaveBeenCalled(); }); it("should return a subscription that can unsubscribe", () => { const hk = new HushKit(createMockConfig()); const unsubMock = vi.fn(); vi.spyOn(hk, "subscribe").mockReturnValue({ unsubscribe: unsubMock }); const sub = hk.onMessage("test", vi.fn()); sub.unsubscribe(); expect(unsubMock).toHaveBeenCalled(); }); }); describe("waitForMessage", () => { it("should resolve when matching message arrives", async () => { const hk = new HushKit(createMockConfig()); let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: vi.fn() }; }); interface AckMsg { type: "ack"; ok: boolean } const promise = hk.waitForMessage({ type: "ack" }, 5000); // Simulate the message arriving await subscribedCallback({ from: "0xsender", content: JSON.stringify({ type: "ack", ok: true }), timestamp: 1000, txHash: "0xtx", blockNumber: 1, }); const result = await promise; expect(result.payload).toEqual({ type: "ack", ok: true }); expect(result.from).toBe("0xsender"); }); it("should filter by from address when specified", async () => { const hk = new HushKit(createMockConfig()); let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: vi.fn() }; }); const targetFrom = "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; const promise = hk.waitForMessage({ type: "ack", from: targetFrom }, 5000); // Send from wrong address — should be ignored await subscribedCallback({ from: "0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", content: JSON.stringify({ type: "ack" }), timestamp: 1000, txHash: "0xtx1", blockNumber: 1, }); // Send from correct address — should resolve await subscribedCallback({ from: targetFrom, content: JSON.stringify({ type: "ack" }), timestamp: 1001, txHash: "0xtx2", blockNumber: 2, }); const result = await promise; expect(result.from).toBe(targetFrom); }); it("should timeout if no matching message arrives", async () => { const hk = new HushKit(createMockConfig()); vi.spyOn(hk, "subscribe").mockReturnValue({ unsubscribe: vi.fn() }); await expect( hk.waitForMessage({ type: "never_coming" }, 100) ).rejects.toThrow('waitForMessage timed out after 100ms waiting for "never_coming"'); }); it("should unsubscribe after resolving", async () => { const hk = new HushKit(createMockConfig()); const unsubMock = vi.fn(); let subscribedCallback: any; vi.spyOn(hk, "subscribe").mockImplementation((cb) => { subscribedCallback = cb; return { unsubscribe: unsubMock }; }); const promise = hk.waitForMessage({ type: "done" }, 5000); await subscribedCallback({ from: "0xsender", content: JSON.stringify({ type: "done" }), timestamp: 1000, txHash: "0xtx", blockNumber: 1, }); await promise; expect(unsubMock).toHaveBeenCalled(); }); it("should unsubscribe on timeout", async () => { const hk = new HushKit(createMockConfig()); const unsubMock = vi.fn(); vi.spyOn(hk, "subscribe").mockReturnValue({ unsubscribe: unsubMock }); try { await hk.waitForMessage({ type: "never" }, 50); } catch { // expected } expect(unsubMock).toHaveBeenCalled(); }); }); describe("poll", () => { beforeEach(() => { vi.useFakeTimers(); }); it("should call callback with new messages", async () => { const hk = new HushKit(createMockConfig()); const callback = vi.fn(); const mockMessages = [ { from: "0xa", content: "hello", blockNumber: 10, timestamp: 1000, txHash: "0x1", to: "0xb", value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null }, ]; vi.spyOn(hk, "getInbox").mockResolvedValueOnce(mockMessages as any); hk.poll(5000, callback); // First tick happens immediately await vi.advanceTimersByTimeAsync(0); expect(callback).toHaveBeenCalledWith(mockMessages); }); it("should return unsubscribable subscription", () => { const hk = new HushKit(createMockConfig()); vi.spyOn(hk, "getInbox").mockResolvedValue([]); const sub = hk.poll(5000, vi.fn()); expect(sub.unsubscribe).toBeInstanceOf(Function); sub.unsubscribe(); }); it("should not crash on getInbox error", async () => { const hk = new HushKit(createMockConfig({ debug: true })); vi.spyOn(hk, "getInbox").mockRejectedValueOnce(new Error("RPC down")); const callback = vi.fn(); const sub = hk.poll(5000, callback); await vi.advanceTimersByTimeAsync(0); expect(callback).not.toHaveBeenCalled(); sub.unsubscribe(); }); afterEach(() => { vi.useRealTimers(); }); }); }); // ============ Security Fix Regression Tests ============ describe("Security fixes", () => { describe("subscribe isolation", () => { it("unsubscribing one handler should not affect others", () => { const hk = new HushKit(createMockConfig()); // Track which handlers are registered/removed const offCalls: any[] = []; const onCalls: any[] = []; // Mock the messenger contract's on/off const messenger = (hk as any).messenger; const origOn = messenger.on.bind(messenger); messenger.on = vi.fn((...args: any[]) => { onCalls.push(args); }); messenger.off = vi.fn((...args: any[]) => { offCalls.push(args); }); // Mock getAddress to resolve synchronously via microtask (hk as any).signer.getAddress = vi.fn().mockResolvedValue("0x1234567890abcdef1234567890abcdef12345678"); const sub1 = hk.subscribe(vi.fn()); const sub2 = hk.subscribe(vi.fn()); // Unsubscribing sub1 should NOT call removeAllListeners sub1.unsubscribe(); // Verify removeAllListeners was NOT called expect(messenger.removeAllListeners).toBeUndefined; }); it("should set unsubscribed flag to prevent zombie listeners", () => { const hk = new HushKit(createMockConfig()); // Get subscription and immediately unsubscribe const sub = hk.subscribe(vi.fn()); sub.unsubscribe(); // The unsubscribed flag should prevent the .then() callback from registering // We verify this indirectly — no error thrown, no crash }); }); describe("poll starts from current block", () => { beforeEach(() => { vi.useFakeTimers(); }); it("should fetch current block number on first tick when no fromBlock specified", async () => { const hk = new HushKit(createMockConfig()); const getBlockNumberSpy = vi.fn().mockResolvedValue(1000); (hk as any).provider.getBlockNumber = getBlockNumberSpy; vi.spyOn(hk, "getInbox").mockResolvedValue([]); hk.poll(5000, vi.fn()); await vi.advanceTimersByTimeAsync(0); expect(getBlockNumberSpy).toHaveBeenCalled(); }); it("should use provided fromBlock and skip getBlockNumber", async () => { const hk = new HushKit(createMockConfig()); const getBlockNumberSpy = vi.fn().mockResolvedValue(1000); (hk as any).provider.getBlockNumber = getBlockNumberSpy; vi.spyOn(hk, "getInbox").mockResolvedValue([]); hk.poll(5000, vi.fn(), { fromBlock: 500 }); await vi.advanceTimersByTimeAsync(0); expect(getBlockNumberSpy).not.toHaveBeenCalled(); }); afterEach(() => { vi.useRealTimers(); }); }); }); // ============ Whitelist Tests ============ describe("Whitelist", () => { it("should be disabled by default (null)", () => { const hk = new HushKit(createMockConfig()); expect(hk.getWhitelist()).toBeNull(); }); it("should enable whitelist with setWhitelist", () => { const hk = new HushKit(createMockConfig()); hk.setWhitelist(["0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]); expect(hk.getWhitelist()).toEqual(["0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"]); }); it("should normalize addresses to lowercase", () => { const hk = new HushKit(createMockConfig()); hk.setWhitelist(["0xAABBCCDDEE1234567890AABBCCDDEEFF00112233"]); expect(hk.getWhitelist()![0]).toBe("0xaabbccddee1234567890aabbccddeeff00112233"); }); it("should add addresses with addToWhitelist", () => { const hk = new HushKit(createMockConfig()); hk.addToWhitelist("0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); hk.addToWhitelist("0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"); expect(hk.getWhitelist()).toHaveLength(2); }); it("should enable whitelist mode when addToWhitelist is called on disabled whitelist", () => { const hk = new HushKit(createMockConfig()); expect(hk.getWhitelist()).toBeNull(); hk.addToWhitelist("0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); expect(hk.getWhitelist()).not.toBeNull(); }); it("should remove addresses with removeFromWhitelist", () => { const hk = new HushKit(createMockConfig()); const addr = "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; hk.setWhitelist([addr]); expect(hk.getWhitelist()).toHaveLength(1); hk.removeFromWhitelist(addr); expect(hk.getWhitelist()).toHaveLength(0); }); it("should disable whitelist with clearWhitelist", () => { const hk = new HushKit(createMockConfig()); hk.setWhitelist(["0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]); expect(hk.getWhitelist()).not.toBeNull(); hk.clearWhitelist(); expect(hk.getWhitelist()).toBeNull(); }); it("should filter raw messages before decryption when enabled", () => { const hk = new HushKit(createMockConfig()); const allowed = "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; const blocked = "0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; hk.setWhitelist([allowed]); const rawMessages = [ { from: allowed, to: "0x00", ciphertext: new Uint8Array(), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 1, txHash: "0x1", blockNumber: 1 }, { from: blocked, to: "0x00", ciphertext: new Uint8Array(), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 2, txHash: "0x2", blockNumber: 2 }, ]; const filtered = (hk as any).filterByWhitelist(rawMessages); expect(filtered).toHaveLength(1); expect(filtered[0].from).toBe(allowed); }); it("should pass all messages through when whitelist is disabled", () => { const hk = new HushKit(createMockConfig()); const rawMessages = [ { from: "0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", to: "0x00", ciphertext: new Uint8Array(), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 1, txHash: "0x1", blockNumber: 1 }, { from: "0xBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", to: "0x00", ciphertext: new Uint8Array(), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 2, txHash: "0x2", blockNumber: 2 }, ]; const filtered = (hk as any).filterByWhitelist(rawMessages); expect(filtered).toHaveLength(2); }); it("should handle case-insensitive address matching", () => { const hk = new HushKit(createMockConfig()); hk.setWhitelist(["0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]); const rawMessages = [ { from: "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", to: "0x00", ciphertext: new Uint8Array(), value: 0n, token: "0x0", tokenAmount: 0n, replyTo: null, timestamp: 1, txHash: "0x1", blockNumber: 1 }, ]; const filtered = (hk as any).filterByWhitelist(rawMessages); expect(filtered).toHaveLength(1); }); }); // ============ TX Recovery Tests ============ describe("TX Recovery", () => { beforeEach(() => { // Replace static fallback providers with mocks that return 0 txCount // to prevent real network calls const mockFallbackProvider = { getTransactionCount: vi.fn().mockResolvedValue(0), getBlockNumber: vi.fn().mockResolvedValue(100), } as any; (HushKit as any).fallbackProviders = [ { provider: mockFallbackProvider, name: "Mock Fallback" }, ]; }); afterEach(() => { // Reset static fallback providers so other tests aren't affected (HushKit as any).fallbackProviders = null; }); it("resolvePublicKey should return registry key when available", async () => { const hk = new HushKit(createMockConfig()); const { publicKey } = generateKeyPair(); const pubKeyHex = bytesToHex(publicKey); (hk as any).registry.getPublicKey = vi.fn().mockResolvedValue(pubKeyHex); const result = await hk.resolvePublicKey("0x1111111111111111111111111111111111111111"); expect(result).not.toBeNull(); expect(result).toEqual(hexToBytes(pubKeyHex)); }); it("resolvePublicKey should fall back to tx recovery when not registered", async () => { const hk = new HushKit(createMockConfig()); // No registered key (hk as any).registry.getPublicKey = vi.fn().mockResolvedValue("0x"); // Mock provider says 0 transactions (recovery finds nothing) (hk as any).provider.getTransactionCount = vi.fn().mockResolvedValue(0); const result = await hk.resolvePublicKey("0x1111111111111111111111111111111111111111"); expect(result).toBeNull(); // Should have attempted recovery (checked txCount) expect((hk as any).provider.getTransactionCount).toHaveBeenCalled(); }); it("recovery cache should prevent repeated scans within TTL", async () => { const hk = new HushKit(createMockConfig()); (hk as any).registry.getPublicKey = vi.fn().mockResolvedValue("0x"); const getTxCountSpy = vi.fn().mockResolvedValue(0); (hk as any).provider.getTransactionCount = getTxCountSpy; await hk.resolvePublicKey("0x1111111111111111111111111111111111111111"); const firstCallCount = getTxCountSpy.mock.calls.length; await hk.resolvePublicKey("0x1111111111111111111111111111111111111111"); // Second call should hit cache — no additional provider calls expect(getTxCountSpy.mock.calls.length).toBe(firstCallCount); }); }); // ============ Gasless Registration Tests ============ describe("Gasless Registration", () => { it("signRegistration should throw without private key", async () => { const hk = new HushKit(createMockConfig()); await expect(hk.signRegistration()).rejects.toThrow("Private key required"); }); it("signRegistration should return RegistrationData with valid fields", async () => { const mockSigner = createMockSigner(); mockSigner.signTypedData = vi.fn().mockResolvedValue("0xmocksignature"); const hk = new HushKit(createMockConfig({ signer: mockSigner })); const { privateKey } = generateKeyPair(); hk.setPrivateKey(bytesToHex(privateKey, false)); (hk as any).provider.getNetwork = vi.fn().mockResolvedValue({ chainId: 84532n }); const result = await hk.signRegistration(); expect(result.account).toBe("0x1234567890abcdef1234567890abcdef12345678"); expect(result.publicKey).toMatch(/^0x0[23]/); // compressed key starts with 02 or 03 expect(result.deadline).toBeGreaterThan(Math.floor(Date.now() / 1000)); expect(result.signature).toBe("0xmocksignature"); }); it("signRegistration should use custom deadline", async () => { const mockSigner = createMockSigner(); mockSigner.signTypedData = vi.fn().mockResolvedValue("0xsig"); const hk = new HushKit(createMockConfig({ signer: mockSigner })); const { privateKey } = generateKeyPair(); hk.setPrivateKey(bytesToHex(privateKey, false)); (hk as any).provider.getNetwork = vi.fn().mockResolvedValue({ chainId: 84532n }); const customDeadline = Math.floor(Date.now() / 1000) + 7200; const result = await hk.signRegistration(customDeadline); expect(result.deadline).toBe(customDeadline); }); it("signRegistration should pass correct EIP-712 domain", async () => { const mockSigner = createMockSigner(); mockSigner.signTypedData = vi.fn().mockResolvedValue("0xsig"); const registryAddr = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const hk = new HushKit(createMockConfig({ signer: mockSigner, contracts: { registry: registryAddr, messenger: "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" }, })); const { privateKey } = generateKeyPair(); hk.setPrivateKey(bytesToHex(privateKey, false)); (hk as any).provider.getNetwork = vi.fn().mockResolvedValue({ chainId: 84532n }); await hk.signRegistration(); expect(mockSigner.signTypedData).toHaveBeenCalledWith( expect.objectContaining({ name: "HushkitRegistry", version: "1", chainId: 84532, verifyingContract: registryAddr, }), expect.objectContaining({ Register: expect.arrayContaining([ { name: "account", type: "address" }, { name: "publicKey", type: "bytes" }, { name: "deadline", type: "uint256" }, ]), }), expect.objectContaining({ account: expect.any(String), publicKey: expect.any(String), deadline: expect.any(Number), }) ); }); it("registerFor should call registry.registerFor with correct params", async () => { const hk = new HushKit(createMockConfig()); const mockTx = { hash: "0xtxhash", wait: vi.fn().mockResolvedValue({}) }; (hk as any).registry.registerFor = vi.fn().mockResolvedValue(mockTx); const data = { account: "0x1111111111111111111111111111111111111111", publicKey: "0x02" + "a".repeat(64), deadline: Math.floor(Date.now() / 1000) + 3600, signature: "0xsignature", }; const txHash = await hk.registerFor(data); expect(txHash).toBe("0xtxhash"); expect((hk as any).registry.registerFor).toHaveBeenCalledWith( data.account, data.publicKey, data.deadline, data.signature ); }); }); // ============ Input Validation Tests ============ describe("Input Validation", () => { it("send should reject empty message", async () => { const hk = new HushKit(createMockConfig()); await expect(hk.send({ to: "0x1111111111111111111111111111111111111111", message: "" })) .rejects.toThrow("Message cannot be empty"); }); }); // ============ Encryption Round-Trip with Typed Messages ============ describe("End-to-end typed message encryption", () => { it("should encrypt and decrypt a typed JSON payload", async () => { const sender = generateKeyPair(); const receiver = generateKeyPair(); interface TaskMsg { type: "task"; id: string; data: number[] } const payload: TaskMsg = { type: "task", id: "abc", data: [1, 2, 3], }; const serialized = JSON.stringify(payload); const ciphertext = await encrypt(serialized, receiver.publicKey); const decrypted = await decrypt(ciphertext, receiver.privateKey); const parsed = JSON.parse(decrypted) as TaskMsg; expect(parsed.type).toBe("task"); expect(parsed.id).toBe("abc"); expect(parsed.data).toEqual([1, 2, 3]); }); it("should handle nested objects in typed payloads", async () => { const kp = generateKeyPair(); interface ComplexMsg { type: "complex"; nested: { a: { b: number } }; arr: string[]; } const payload: ComplexMsg = { type: "complex", nested: { a: { b: 42 } }, arr: ["x", "y"], }; const ciphertext = await encrypt(JSON.stringify(payload), kp.publicKey); const decrypted = await decrypt(ciphertext, kp.privateKey); const parsed = JSON.parse(decrypted) as ComplexMsg; expect(parsed.nested.a.b).toBe(42); expect(parsed.arr).toEqual(["x", "y"]); }); });