@unlink-xyz/core 0.1.0 → 0.1.2

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.
Files changed (110) hide show
  1. package/.eslintrc.json +4 -0
  2. package/account/zkAccount.test.ts +316 -0
  3. package/account/zkAccount.ts +222 -0
  4. package/clients/broadcaster.ts +67 -0
  5. package/clients/http.ts +94 -0
  6. package/clients/indexer.ts +150 -0
  7. package/config.ts +39 -0
  8. package/core.ts +17 -0
  9. package/dist/account/railgun-imports-prototype.d.ts +12 -0
  10. package/dist/account/railgun-imports-prototype.d.ts.map +1 -0
  11. package/dist/account/railgun-imports-prototype.js +30 -0
  12. package/dist/clients/indexer.d.ts.map +1 -1
  13. package/dist/clients/indexer.js +1 -1
  14. package/dist/state/hydrator.d.ts +16 -0
  15. package/dist/state/hydrator.d.ts.map +1 -0
  16. package/dist/state/hydrator.js +18 -0
  17. package/dist/state/job-store.d.ts +12 -0
  18. package/dist/state/job-store.d.ts.map +1 -0
  19. package/dist/state/job-store.js +118 -0
  20. package/dist/state/jobs.d.ts +50 -0
  21. package/dist/state/jobs.d.ts.map +1 -0
  22. package/dist/state/jobs.js +1 -0
  23. package/dist/state.d.ts +83 -0
  24. package/dist/state.d.ts.map +1 -0
  25. package/dist/state.js +171 -0
  26. package/dist/transactions/deposit.d.ts +0 -2
  27. package/dist/transactions/deposit.d.ts.map +1 -1
  28. package/dist/transactions/deposit.js +5 -9
  29. package/dist/transactions/note-sync.d.ts.map +1 -1
  30. package/dist/transactions/note-sync.js +1 -1
  31. package/dist/transactions/shield.d.ts +5 -0
  32. package/dist/transactions/shield.d.ts.map +1 -0
  33. package/dist/transactions/shield.js +93 -0
  34. package/dist/transactions/transact.d.ts +0 -5
  35. package/dist/transactions/transact.d.ts.map +1 -1
  36. package/dist/transactions/transact.js +2 -2
  37. package/dist/transactions/utils.d.ts +10 -0
  38. package/dist/transactions/utils.d.ts.map +1 -0
  39. package/dist/transactions/utils.js +17 -0
  40. package/dist/tsconfig.tsbuildinfo +1 -1
  41. package/dist/utils/time.d.ts +2 -0
  42. package/dist/utils/time.d.ts.map +1 -0
  43. package/dist/utils/time.js +3 -0
  44. package/dist/utils/witness.d.ts +11 -0
  45. package/dist/utils/witness.d.ts.map +1 -0
  46. package/dist/utils/witness.js +19 -0
  47. package/errors.ts +20 -0
  48. package/index.ts +17 -0
  49. package/key-derivation/babyjubjub.ts +11 -0
  50. package/key-derivation/bech32.test.ts +90 -0
  51. package/key-derivation/bech32.ts +124 -0
  52. package/key-derivation/bip32.ts +56 -0
  53. package/key-derivation/bip39.ts +76 -0
  54. package/key-derivation/bytes.ts +118 -0
  55. package/key-derivation/hash.ts +13 -0
  56. package/key-derivation/index.ts +7 -0
  57. package/key-derivation/wallet-node.ts +155 -0
  58. package/keys.ts +47 -0
  59. package/package.json +4 -5
  60. package/prover/config.ts +104 -0
  61. package/prover/index.ts +1 -0
  62. package/prover/prover.integration.test.ts +162 -0
  63. package/prover/prover.test.ts +309 -0
  64. package/prover/prover.ts +405 -0
  65. package/prover/registry.test.ts +90 -0
  66. package/prover/registry.ts +82 -0
  67. package/schema.ts +17 -0
  68. package/setup-artifacts.sh +57 -0
  69. package/state/index.ts +2 -0
  70. package/state/merkle/hydrator.ts +69 -0
  71. package/state/merkle/index.ts +12 -0
  72. package/state/merkle/merkle-tree.test.ts +50 -0
  73. package/state/merkle/merkle-tree.ts +163 -0
  74. package/state/store/ciphertext-store.ts +28 -0
  75. package/state/store/index.ts +24 -0
  76. package/state/store/job-store.ts +162 -0
  77. package/state/store/jobs.ts +64 -0
  78. package/state/store/leaf-store.ts +39 -0
  79. package/state/store/note-store.ts +177 -0
  80. package/state/store/nullifier-store.ts +39 -0
  81. package/state/store/records.ts +61 -0
  82. package/state/store/root-store.ts +34 -0
  83. package/state/store/store.ts +25 -0
  84. package/state.test.ts +235 -0
  85. package/storage/index.ts +3 -0
  86. package/storage/indexeddb.test.ts +99 -0
  87. package/storage/indexeddb.ts +235 -0
  88. package/storage/memory.test.ts +59 -0
  89. package/storage/memory.ts +93 -0
  90. package/transactions/deposit.test.ts +160 -0
  91. package/transactions/deposit.ts +227 -0
  92. package/transactions/index.ts +20 -0
  93. package/transactions/note-sync.test.ts +155 -0
  94. package/transactions/note-sync.ts +452 -0
  95. package/transactions/reconcile.ts +73 -0
  96. package/transactions/transact.test.ts +451 -0
  97. package/transactions/transact.ts +811 -0
  98. package/transactions/types.ts +141 -0
  99. package/tsconfig.json +14 -0
  100. package/types/global.d.ts +15 -0
  101. package/types.ts +24 -0
  102. package/utils/async.ts +15 -0
  103. package/utils/bigint.ts +34 -0
  104. package/utils/crypto.test.ts +69 -0
  105. package/utils/crypto.ts +58 -0
  106. package/utils/json-codec.ts +38 -0
  107. package/utils/polling.ts +6 -0
  108. package/utils/signature.ts +16 -0
  109. package/utils/validators.test.ts +64 -0
  110. package/utils/validators.ts +86 -0
package/errors.ts ADDED
@@ -0,0 +1,20 @@
1
+ export class CoreError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ this.name = "CoreError";
5
+ }
6
+ }
7
+
8
+ export class KeyValidationError extends CoreError {
9
+ constructor(message: string) {
10
+ super(message);
11
+ this.name = "KeyValidationError";
12
+ }
13
+ }
14
+
15
+ export class SchemaMismatchError extends CoreError {
16
+ constructor(current: number, expected: number) {
17
+ super(`schema mismatch (current ${current}, expected ${expected})`);
18
+ this.name = "SchemaMismatchError";
19
+ }
20
+ }
package/index.ts ADDED
@@ -0,0 +1,17 @@
1
+ export * from "./types.js";
2
+ export * from "./errors.js";
3
+ export * from "./keys.js";
4
+ export * from "./storage/index.js";
5
+ export * from "./schema.js";
6
+ export * from "./core.js";
7
+ export * from "./state/index.js";
8
+ export * from "./utils/validators.js";
9
+ export * from "./utils/bigint.js";
10
+ export * from "./account/zkAccount.js";
11
+ export * from "./key-derivation/index.js";
12
+ export * from "./transactions/index.js";
13
+ export { createJobReconciler } from "./transactions/reconcile.js";
14
+ export { serviceConfig } from "./config.js";
15
+ export type { ServiceConfig } from "./config.js";
16
+ export * from "./clients/broadcaster.js";
17
+ export * from "./clients/indexer.js";
@@ -0,0 +1,11 @@
1
+ import { babyjub } from "@railgun-community/circomlibjs";
2
+
3
+ /**
4
+ * Lightweight wrapper exposing the BabyJubJub point packing helpers we rely on for
5
+ * derivation and address encoding. Re-exported for consumers that need raw curve ops.
6
+ */
7
+ export class Babyjubjub {
8
+ static packPoint = babyjub.packPoint;
9
+
10
+ static unpackPoint = babyjub.unpackPoint;
11
+ }
@@ -0,0 +1,90 @@
1
+ import { bech32m } from "@scure/base";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ import {
5
+ ADDRESS_LENGTH_LIMIT,
6
+ ADDRESS_VERSION,
7
+ decodeAddress,
8
+ encodeAddress,
9
+ type Chain,
10
+ } from "./bech32.js";
11
+
12
+ describe("bech32 address encoding", () => {
13
+ const masterPublicKey = 1234567890123456789012345678901234567890n;
14
+ const viewingPublicKey = Uint8Array.from(
15
+ { length: 32 },
16
+ (_, i) => (i * 3) & 0xff,
17
+ );
18
+
19
+ it("encodes and decodes addresses without chain metadata", () => {
20
+ const address = encodeAddress({
21
+ masterPublicKey,
22
+ viewingPublicKey,
23
+ });
24
+
25
+ const decoded = decodeAddress(address);
26
+
27
+ expect(decoded.masterPublicKey).toEqual(masterPublicKey);
28
+ expect(decoded.viewingPublicKey).toEqual(viewingPublicKey);
29
+ expect(decoded.chain).toBeUndefined();
30
+ expect(decoded.version).toBe(ADDRESS_VERSION);
31
+ });
32
+
33
+ it("preserves chain metadata when provided", () => {
34
+ const chain: Chain = { type: 1, id: 42161 };
35
+ const address = encodeAddress({
36
+ masterPublicKey,
37
+ viewingPublicKey,
38
+ chain,
39
+ });
40
+
41
+ const decoded = decodeAddress(address);
42
+
43
+ expect(decoded.chain).toEqual(chain);
44
+ });
45
+
46
+ it("rejects malformed payloads", () => {
47
+ const address = encodeAddress({
48
+ masterPublicKey,
49
+ viewingPublicKey,
50
+ });
51
+
52
+ expect(() => decodeAddress("")).toThrow("No address to decode");
53
+
54
+ const decoded = bech32m.decode(address, ADDRESS_LENGTH_LIMIT);
55
+ const reencoded = bech32m.encode(
56
+ "abc",
57
+ decoded.words,
58
+ ADDRESS_LENGTH_LIMIT,
59
+ );
60
+
61
+ expect(() => decodeAddress(reencoded)).toThrow("Invalid address prefix");
62
+ });
63
+
64
+ it("throws on incorrect version", () => {
65
+ const address = encodeAddress({
66
+ masterPublicKey,
67
+ viewingPublicKey,
68
+ });
69
+
70
+ const mutated = mutatePayload(address, (payload) => {
71
+ payload[0] ^= 0xff;
72
+ });
73
+
74
+ expect(() => decodeAddress(mutated)).toThrow("Incorrect address version");
75
+ });
76
+ });
77
+
78
+ function mutatePayload(
79
+ address: string,
80
+ mutator: (payload: Uint8Array) => void,
81
+ ): string {
82
+ const decoded = bech32m.decode(address, ADDRESS_LENGTH_LIMIT);
83
+ const payload = Uint8Array.from(bech32m.fromWords(decoded.words));
84
+ mutator(payload);
85
+ return bech32m.encode(
86
+ decoded.prefix,
87
+ bech32m.toWords(payload),
88
+ ADDRESS_LENGTH_LIMIT,
89
+ );
90
+ }
@@ -0,0 +1,124 @@
1
+ import { bech32m } from "@scure/base";
2
+
3
+ import { ByteLength, ByteUtils } from "./bytes.js";
4
+
5
+ export type Chain = {
6
+ type: number;
7
+ id: number;
8
+ };
9
+
10
+ export type AddressData = {
11
+ masterPublicKey: bigint;
12
+ viewingPublicKey: Uint8Array;
13
+ chain?: Chain;
14
+ version?: number;
15
+ };
16
+
17
+ export const ADDRESS_VERSION = 1;
18
+ export const ADDRESS_LENGTH_LIMIT = 127;
19
+ export const ALL_CHAINS_NETWORK_ID = "ffffffffffffffff";
20
+
21
+ const PREFIX = "0zk";
22
+ const XOR_SALT = new TextEncoder().encode("unlink");
23
+
24
+ /**
25
+ * XOR the network identifier with a static salt to keep addresses compact and avoid
26
+ * exposing raw chain IDs directly (mirrors the reference implementation).
27
+ */
28
+ const xorNetworkID = (networkID: string): string => {
29
+ const bytes = ByteUtils.hexStringToBytes(networkID);
30
+ const result = new Uint8Array(bytes.length);
31
+ const saltLength = XOR_SALT.length;
32
+ for (let i = 0; i < bytes.length; i += 1) {
33
+ const byte = bytes[i] ?? 0;
34
+ let saltByte = 0;
35
+ if (saltLength > 0) {
36
+ const saltIndex = i % saltLength;
37
+ saltByte = XOR_SALT[saltIndex] ?? 0;
38
+ }
39
+ result[i] = byte ^ saltByte;
40
+ }
41
+ return ByteUtils.bytesToHex(result);
42
+ };
43
+
44
+ const chainToNetworkID = (chain?: Chain): string => {
45
+ if (!chain) return ALL_CHAINS_NETWORK_ID;
46
+ const { type, id } = chain;
47
+ const typeHex = (type & 0xff).toString(16).padStart(2, "0");
48
+ const idHex = BigInt(id).toString(16).padStart(14, "0");
49
+ return `${typeHex}${idHex}`;
50
+ };
51
+
52
+ const networkIDToChain = (networkID: string): Chain | undefined => {
53
+ if (networkID === ALL_CHAINS_NETWORK_ID) {
54
+ return undefined;
55
+ }
56
+ const type = parseInt(networkID.slice(0, 2), 16);
57
+ const id = parseInt(networkID.slice(2), 16);
58
+ return { type, id };
59
+ };
60
+
61
+ /**
62
+ * Encode address metadata into a Bech32m string with the 0zk prefix.
63
+ */
64
+ export const encodeAddress = (addressData: AddressData): string => {
65
+ const versionHex = (addressData.version ?? ADDRESS_VERSION)
66
+ .toString(16)
67
+ .padStart(2, "0");
68
+ const masterPublicKey = ByteUtils.nToHex(
69
+ addressData.masterPublicKey,
70
+ ByteLength.UINT_256,
71
+ false,
72
+ );
73
+ const viewingPublicKey = ByteUtils.formatToByteLength(
74
+ addressData.viewingPublicKey,
75
+ ByteLength.UINT_256,
76
+ );
77
+ const networkID = xorNetworkID(chainToNetworkID(addressData.chain));
78
+
79
+ const payloadHex = `${versionHex}${masterPublicKey}${networkID}${viewingPublicKey}`;
80
+ const payload = ByteUtils.hexStringToBytes(payloadHex);
81
+
82
+ return bech32m.encode(PREFIX, bech32m.toWords(payload), ADDRESS_LENGTH_LIMIT);
83
+ };
84
+
85
+ /**
86
+ * Decode and validate a Bech32m address, returning the structured payload.
87
+ */
88
+ export const decodeAddress = (address: string): AddressData => {
89
+ if (!address) {
90
+ throw new Error("No address to decode");
91
+ }
92
+
93
+ const decoded = bech32m.decode(
94
+ address as `${string}1${string}`,
95
+ ADDRESS_LENGTH_LIMIT,
96
+ );
97
+ if (decoded.prefix !== PREFIX) {
98
+ throw new Error("Invalid address prefix");
99
+ }
100
+
101
+ const payloadHex = ByteUtils.hexlify(bech32m.fromWords(decoded.words));
102
+ if (payloadHex.length !== 2 + 64 + 16 + 64) {
103
+ throw new Error("Incorrect address payload length");
104
+ }
105
+
106
+ const version = parseInt(payloadHex.slice(0, 2), 16);
107
+ if (version !== ADDRESS_VERSION) {
108
+ throw new Error("Incorrect address version");
109
+ }
110
+
111
+ const masterPublicKey = ByteUtils.hexToBigInt(payloadHex.slice(2, 66));
112
+ const networkID = xorNetworkID(payloadHex.slice(66, 82));
113
+ const viewingPublicKey = ByteUtils.hexStringToBytes(
114
+ payloadHex.slice(82, 146),
115
+ );
116
+ const chain = networkIDToChain(networkID);
117
+
118
+ return {
119
+ version,
120
+ masterPublicKey,
121
+ viewingPublicKey,
122
+ chain,
123
+ };
124
+ };
@@ -0,0 +1,56 @@
1
+ import { ByteUtils, fromUTF8String } from "./bytes.js";
2
+ import { sha512HMAC } from "./hash.js";
3
+
4
+ const CURVE_SEED = fromUTF8String("babyjubjub seed");
5
+
6
+ export type KeyNode = {
7
+ chainKey: string;
8
+ chainCode: string;
9
+ };
10
+
11
+ // Validates derivation paths of the form m/... with hardened segments.
12
+ const PATH_REGEX = /^m(\/[0-9]+')+$/;
13
+
14
+ const isValidPath = (path: string): boolean => {
15
+ return PATH_REGEX.test(path);
16
+ };
17
+
18
+ /**
19
+ * Parse a derivation path into hardened segment indexes.
20
+ */
21
+ export const getPathSegments = (path: string): number[] => {
22
+ if (!isValidPath(path)) {
23
+ throw new Error("Invalid derivation path");
24
+ }
25
+ return path
26
+ .split("/")
27
+ .slice(1)
28
+ .map((segment) => segment.replace("'", ""))
29
+ .map((segment) => parseInt(segment, 10));
30
+ };
31
+
32
+ /**
33
+ * Perform hardened child derivation using the BabyJubJub curve seed.
34
+ */
35
+ export const childKeyDerivationHardened = (
36
+ node: KeyNode,
37
+ index: number,
38
+ offset: number = 0x80000000,
39
+ ): KeyNode => {
40
+ const indexFormatted = ByteUtils.padToLength(index + offset, 4);
41
+ const preImage = `00${node.chainKey}${indexFormatted}`;
42
+ const I = sha512HMAC(node.chainCode, preImage);
43
+ const chainKey = I.slice(0, 64);
44
+ const chainCode = I.slice(64);
45
+ return { chainKey, chainCode };
46
+ };
47
+
48
+ /**
49
+ * Create the root BIP-32 node from a BIP-39 seed.
50
+ */
51
+ export const getMasterKeyFromSeed = (seed: string): KeyNode => {
52
+ const I = sha512HMAC(CURVE_SEED, seed);
53
+ const chainKey = I.slice(0, 64);
54
+ const chainCode = I.slice(64);
55
+ return { chainKey, chainCode };
56
+ };
@@ -0,0 +1,76 @@
1
+ import {
2
+ entropyToMnemonic,
3
+ generateMnemonic,
4
+ mnemonicToEntropy,
5
+ mnemonicToSeedSync,
6
+ validateMnemonic,
7
+ } from "@scure/bip39";
8
+ import { wordlist } from "@scure/bip39/wordlists/english.js";
9
+ import { HDKey } from "ethereum-cryptography/hdkey";
10
+ import { Mnemonic as EthersMnemonic, HDNodeWallet } from "ethers";
11
+
12
+ import { ByteUtils } from "./bytes.js";
13
+
14
+ /**
15
+ * Standard ETH derivation path helper for convenience utilities below.
16
+ * Not used for 0zk accounts but kept for backwards compatibility.
17
+ */
18
+ const derivationPath = (index = 0): string => {
19
+ return `m/44'/60'/0'/0/${index}`;
20
+ };
21
+
22
+ export class Mnemonic {
23
+ /**
24
+ * Generate a BIP-39 mnemonic using the English wordlist.
25
+ */
26
+ static generate(strength: 128 | 192 | 256 = 128): string {
27
+ return generateMnemonic(wordlist, strength);
28
+ }
29
+
30
+ /**
31
+ * Validate a mnemonic against the English wordlist checksum.
32
+ */
33
+ static validate(mnemonic: string): boolean {
34
+ return validateMnemonic(mnemonic, wordlist);
35
+ }
36
+
37
+ /**
38
+ * Convert a mnemonic to a hex-encoded BIP-39 seed. Optional password supported.
39
+ */
40
+ static toSeed(mnemonic: string, password: string = ""): string {
41
+ const seed = mnemonicToSeedSync(mnemonic, password);
42
+ return ByteUtils.bytesToHex(seed);
43
+ }
44
+
45
+ static toEntropy(mnemonic: string): string {
46
+ const entropy = mnemonicToEntropy(mnemonic, wordlist);
47
+ return ByteUtils.bytesToHex(entropy);
48
+ }
49
+
50
+ static fromEntropy(entropyHex: string): string {
51
+ const entropy = ByteUtils.hexStringToBytes(entropyHex);
52
+ return entropyToMnemonic(entropy, wordlist);
53
+ }
54
+
55
+ /**
56
+ * Convenience helper: derive a 0x private key for non-0zk flows.
57
+ */
58
+ static to0xPrivateKey(mnemonic: string, derivationIndex?: number): string {
59
+ const seed = mnemonicToSeedSync(mnemonic);
60
+ const node = HDKey.fromMasterSeed(Buffer.from(seed)).derive(
61
+ derivationPath(derivationIndex),
62
+ );
63
+ if (!node.privateKey) {
64
+ throw new Error("Failed to derive private key");
65
+ }
66
+ return ByteUtils.bytesToHex(node.privateKey);
67
+ }
68
+
69
+ static to0xAddress(mnemonic: string, derivationIndex?: number): string {
70
+ const wallet = HDNodeWallet.fromMnemonic(
71
+ EthersMnemonic.fromPhrase(mnemonic),
72
+ derivationPath(derivationIndex),
73
+ );
74
+ return wallet.address;
75
+ }
76
+ }
@@ -0,0 +1,118 @@
1
+ export enum ByteLength {
2
+ UINT_256 = 32,
3
+ UINT_512 = 64,
4
+ }
5
+
6
+ export type BytesData =
7
+ | string
8
+ | number
9
+ | bigint
10
+ | Uint8Array
11
+ | ArrayLike<number>;
12
+
13
+ const HEX_REGEX = /^[0-9a-f]*$/i;
14
+
15
+ const isPrefixed = (value: string): boolean => value.startsWith("0x");
16
+
17
+ const assertEvenLength = (hex: string): void => {
18
+ if (hex.length % 2 !== 0) {
19
+ throw new Error("Hex string must have an even length");
20
+ }
21
+ };
22
+
23
+ const assertHex = (hex: string): void => {
24
+ if (!HEX_REGEX.test(hex)) {
25
+ throw new Error("Invalid hex string");
26
+ }
27
+ };
28
+
29
+ export class ByteUtils {
30
+ static prefix0x(value: string): string {
31
+ return isPrefixed(value) ? value : `0x${value}`;
32
+ }
33
+
34
+ static strip0x(value: string): string {
35
+ return isPrefixed(value) ? value.slice(2) : value;
36
+ }
37
+
38
+ static hexlify(data: BytesData): string {
39
+ if (typeof data === "string") {
40
+ return ByteUtils.strip0x(data).toLowerCase();
41
+ }
42
+ if (typeof data === "number" || typeof data === "bigint") {
43
+ if (data < 0) throw new Error("Cannot hexlify negative values");
44
+ const hex = data.toString(16);
45
+ return hex.length % 2 === 0 ? hex : `0${hex}`;
46
+ }
47
+ const view = data instanceof Uint8Array ? data : Uint8Array.from(data);
48
+ return ByteUtils.bytesToHex(view);
49
+ }
50
+
51
+ static bytesToHex(bytes: Uint8Array): string {
52
+ let hex = "";
53
+ for (const byte of bytes) {
54
+ hex += byte.toString(16).padStart(2, "0");
55
+ }
56
+ return hex;
57
+ }
58
+
59
+ static hexStringToBytes(hex: string): Uint8Array {
60
+ const normalized = ByteUtils.strip0x(hex).toLowerCase();
61
+ assertEvenLength(normalized);
62
+ assertHex(normalized);
63
+ const byteLength = normalized.length / 2;
64
+ return Uint8Array.from({ length: byteLength }, (_, index) =>
65
+ parseInt(normalized.slice(index * 2, index * 2 + 2), 16),
66
+ );
67
+ }
68
+
69
+ static arrayify(data: BytesData): Uint8Array {
70
+ if (data instanceof Uint8Array) {
71
+ return new Uint8Array(data);
72
+ }
73
+ if (typeof data === "string") {
74
+ return ByteUtils.hexStringToBytes(data);
75
+ }
76
+ if (typeof data === "number" || typeof data === "bigint") {
77
+ return ByteUtils.hexStringToBytes(ByteUtils.hexlify(data));
78
+ }
79
+ return Uint8Array.from(data);
80
+ }
81
+
82
+ static hexToBigInt(hex: string): bigint {
83
+ return BigInt(`0x${ByteUtils.strip0x(hex)}`);
84
+ }
85
+
86
+ static padToLength(
87
+ data: BytesData,
88
+ length: number,
89
+ side: "left" | "right" = "left",
90
+ ): string {
91
+ const hex = ByteUtils.hexlify(data);
92
+ const targetLength = length * 2;
93
+ if (hex.length > targetLength) {
94
+ throw new Error("Cannot pad data that exceeds target length");
95
+ }
96
+ return side === "left"
97
+ ? hex.padStart(targetLength, "0")
98
+ : hex.padEnd(targetLength, "0");
99
+ }
100
+
101
+ static formatToByteLength(data: BytesData, length: ByteLength): string {
102
+ const hex = ByteUtils.hexlify(data);
103
+ if (hex.length > length * 2) {
104
+ return hex.slice(0, length * 2);
105
+ }
106
+ return hex.padStart(length * 2, "0");
107
+ }
108
+
109
+ static nToHex(value: bigint, length: ByteLength, prefix = false): string {
110
+ const hex = value.toString(16).padStart(length * 2, "0");
111
+ return prefix ? `0x${hex}` : hex;
112
+ }
113
+ }
114
+
115
+ export function fromUTF8String(value: string): string {
116
+ const encoder = new TextEncoder();
117
+ return ByteUtils.hexlify(encoder.encode(value));
118
+ }
@@ -0,0 +1,13 @@
1
+ import { hmac } from "@noble/hashes/hmac";
2
+ import { sha512 } from "@noble/hashes/sha2";
3
+
4
+ import { BytesData, ByteUtils } from "./bytes.js";
5
+
6
+ const toBytes = (data: BytesData): Uint8Array => {
7
+ return ByteUtils.arrayify(data);
8
+ };
9
+
10
+ export function sha512HMAC(key: BytesData, data: BytesData): string {
11
+ const mac = hmac(sha512, toBytes(key), toBytes(data));
12
+ return ByteUtils.bytesToHex(mac);
13
+ }
@@ -0,0 +1,7 @@
1
+ export * from "./babyjubjub.js";
2
+ export * from "./bip32.js";
3
+ export * from "./bip39.js";
4
+ export * from "./bech32.js";
5
+ export * from "./bytes.js";
6
+ export * from "./hash.js";
7
+ export * from "./wallet-node.js";
@@ -0,0 +1,155 @@
1
+ import { Buffer } from "buffer";
2
+ import { getPublicKey, hashes } from "@noble/ed25519";
3
+ import { sha512 } from "@noble/hashes/sha2";
4
+ import { eddsa, poseidon } from "@railgun-community/circomlibjs";
5
+
6
+ import {
7
+ childKeyDerivationHardened,
8
+ getMasterKeyFromSeed,
9
+ getPathSegments,
10
+ KeyNode,
11
+ } from "./bip32.js";
12
+ import { Mnemonic } from "./bip39.js";
13
+ import { ByteUtils } from "./bytes.js";
14
+
15
+ hashes.sha512 = sha512;
16
+ hashes.sha512Async = async (message: Uint8Array) => sha512(message);
17
+
18
+ const HARDENED_OFFSET = 0x80000000;
19
+
20
+ export type SpendingPublicKey = [bigint, bigint];
21
+ export type SpendingKeyPair = {
22
+ privateKey: Uint8Array;
23
+ pubkey: SpendingPublicKey;
24
+ };
25
+ export type ViewingKeyPair = { privateKey: Uint8Array; pubkey: Uint8Array };
26
+
27
+ /**
28
+ * Hardened base paths for spending/viewing keys. The final path becomes
29
+ * m/.../{index}' for each account slot.
30
+ */
31
+ const DERIVATION_PATH_PREFIXES = {
32
+ SPENDING: "m/44'/1984'/0'/0'/",
33
+ VIEWING: "m/420'/1984'/0'/0'/",
34
+ };
35
+
36
+ const derivePathsForIndex = (index: number = 0) => ({
37
+ spending: `${DERIVATION_PATH_PREFIXES.SPENDING}${index}'`,
38
+ viewing: `${DERIVATION_PATH_PREFIXES.VIEWING}${index}'`,
39
+ });
40
+
41
+ export type WalletNodes = { spending: WalletNode; viewing: WalletNode };
42
+
43
+ export const deriveNodes = (
44
+ mnemonic: string,
45
+ index: number = 0,
46
+ ): WalletNodes => {
47
+ const paths = derivePathsForIndex(index);
48
+ const root = WalletNode.fromMnemonic(mnemonic);
49
+ return {
50
+ spending: root.derive(paths.spending),
51
+ viewing: root.derive(paths.viewing),
52
+ };
53
+ };
54
+
55
+ export const deriveNodesFromSeed = (
56
+ seed: Uint8Array,
57
+ index: number = 0,
58
+ ): WalletNodes => {
59
+ const paths = derivePathsForIndex(index);
60
+ const root = WalletNode.fromSeed(seed);
61
+ return {
62
+ spending: root.derive(paths.spending),
63
+ viewing: root.derive(paths.viewing),
64
+ };
65
+ };
66
+
67
+ export class WalletNode {
68
+ private readonly chainKey: string;
69
+
70
+ private readonly chainCode: string;
71
+
72
+ constructor(node: KeyNode) {
73
+ this.chainKey = node.chainKey;
74
+ this.chainCode = node.chainCode;
75
+ }
76
+
77
+ static fromMnemonic(mnemonic: string): WalletNode {
78
+ const seedHex = Mnemonic.toSeed(mnemonic);
79
+ return new WalletNode(getMasterKeyFromSeed(seedHex));
80
+ }
81
+
82
+ /**
83
+ * Convenience constructor for callers that already hold a seed or mnemonic-derived hex.
84
+ */
85
+ static fromSeed(seed: Uint8Array | string): WalletNode {
86
+ const seedHex =
87
+ typeof seed === "string"
88
+ ? ByteUtils.hexlify(seed)
89
+ : ByteUtils.bytesToHex(seed);
90
+ return new WalletNode(getMasterKeyFromSeed(seedHex));
91
+ }
92
+
93
+ /**
94
+ * Traverse a derivation path, returning the resulting hardened node.
95
+ */
96
+ derive(path: string): WalletNode {
97
+ const segments = getPathSegments(path);
98
+ const derived = segments.reduce(
99
+ (parent, segment) =>
100
+ childKeyDerivationHardened(parent, segment, HARDENED_OFFSET),
101
+ { chainKey: this.chainKey, chainCode: this.chainCode },
102
+ );
103
+ return new WalletNode(derived);
104
+ }
105
+
106
+ /**
107
+ * Derive the BabyJubJub spending key pair (private scalar + affine point).
108
+ */
109
+ getSpendingKeyPair(): SpendingKeyPair {
110
+ const privateKey = ByteUtils.hexStringToBytes(this.chainKey);
111
+ if (privateKey.length !== 32) {
112
+ throw new Error("Spending private key must be 32 bytes");
113
+ }
114
+ const pubkey = eddsa.prv2pub(Buffer.from(privateKey)) as SpendingPublicKey;
115
+ return { privateKey, pubkey };
116
+ }
117
+
118
+ static getMasterPublicKey(
119
+ spendingPublicKey: SpendingPublicKey,
120
+ nullifyingKey: bigint,
121
+ ): bigint {
122
+ return poseidon([...spendingPublicKey, nullifyingKey]);
123
+ }
124
+
125
+ static getNullifyingKey(viewingPrivateKey: Uint8Array): bigint {
126
+ if (!(viewingPrivateKey instanceof Uint8Array)) {
127
+ throw new Error("Viewing private key must be a Uint8Array");
128
+ }
129
+ if (viewingPrivateKey.length !== 32) {
130
+ throw new Error("Viewing private key must be 32 bytes");
131
+ }
132
+ const privateKeyHex = ByteUtils.bytesToHex(viewingPrivateKey);
133
+ return poseidon([ByteUtils.hexToBigInt(privateKeyHex)]);
134
+ }
135
+
136
+ /**
137
+ * Derive the Ed25519 viewing key pair for encrypted note retrieval.
138
+ */
139
+ async getViewingKeyPair(): Promise<ViewingKeyPair> {
140
+ const privateKey = ByteUtils.hexStringToBytes(this.chainKey);
141
+ if (privateKey.length !== 32) {
142
+ throw new Error("Viewing private key must be 32 bytes");
143
+ }
144
+ const pubkey = await getPublicKey(privateKey);
145
+ return { privateKey, pubkey };
146
+ }
147
+
148
+ /**
149
+ * Compute the Poseidon-based nullifying key used in note nullifier generation.
150
+ */
151
+ async getNullifyingKey(): Promise<bigint> {
152
+ const { privateKey } = await this.getViewingKeyPair();
153
+ return WalletNode.getNullifyingKey(privateKey);
154
+ }
155
+ }