@waku/rln 0.1.4-d27db21.0 → 0.1.5-053bb95.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.
Files changed (138) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +5 -0
  3. package/bundle/_virtual/utils.js +2 -2
  4. package/bundle/_virtual/utils2.js +2 -2
  5. package/bundle/index.js +3 -1
  6. package/bundle/node_modules/@ethersproject/abi/lib.esm/coders/abstract-coder.js +1 -1
  7. package/bundle/node_modules/@ethersproject/abi/lib.esm/interface.js +1 -1
  8. package/bundle/node_modules/@ethersproject/abstract-provider/lib.esm/index.js +1 -1
  9. package/bundle/node_modules/@ethersproject/abstract-signer/lib.esm/index.js +11 -11
  10. package/bundle/node_modules/@ethersproject/bytes/lib.esm/_version.js +1 -1
  11. package/bundle/node_modules/@ethersproject/contracts/lib.esm/index.js +7 -7
  12. package/bundle/node_modules/@ethersproject/hash/lib.esm/ens-normalize/lib.js +2 -2
  13. package/bundle/node_modules/@ethersproject/hash/lib.esm/typed-data.js +2 -2
  14. package/bundle/node_modules/@ethersproject/keccak256/node_modules/js-sha3/src/sha3.js +1 -1
  15. package/bundle/node_modules/@ethersproject/logger/lib.esm/_version.js +1 -1
  16. package/bundle/node_modules/@ethersproject/properties/lib.esm/index.js +1 -1
  17. package/bundle/node_modules/@ethersproject/providers/lib.esm/base-provider.js +44 -44
  18. package/bundle/node_modules/@ethersproject/providers/lib.esm/json-rpc-provider.js +8 -8
  19. package/bundle/node_modules/@ethersproject/rlp/lib.esm/_version.js +1 -1
  20. package/bundle/node_modules/@ethersproject/transactions/lib.esm/index.js +1 -1
  21. package/bundle/node_modules/@ethersproject/web/lib.esm/geturl.js +1 -1
  22. package/bundle/node_modules/@ethersproject/web/lib.esm/index.js +2 -2
  23. package/bundle/node_modules/@multiformats/multiaddr/dist/src/multiaddr.js +1 -0
  24. package/bundle/node_modules/@noble/hashes/esm/sha3.js +1 -1
  25. package/bundle/node_modules/bn.js/lib/bn.js +1 -1
  26. package/bundle/packages/core/dist/lib/connection_manager/connection_manager.js +6 -6
  27. package/bundle/packages/rln/dist/contract/abi.js +502 -248
  28. package/bundle/packages/rln/dist/contract/constants.js +5 -9
  29. package/bundle/packages/rln/dist/contract/errors.js +62 -0
  30. package/bundle/packages/rln/dist/contract/rln_base_contract.js +347 -0
  31. package/bundle/packages/rln/dist/contract/rln_contract.js +81 -392
  32. package/bundle/packages/rln/dist/contract/types.js +9 -0
  33. package/bundle/packages/rln/dist/create.js +1 -1
  34. package/bundle/packages/rln/dist/credentials_manager.js +215 -0
  35. package/bundle/packages/rln/dist/identity.js +8 -0
  36. package/bundle/packages/rln/dist/keystore/keystore.js +20 -28
  37. package/bundle/packages/rln/dist/rln.js +56 -166
  38. package/bundle/packages/rln/dist/zerokit.js +5 -5
  39. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/checksum.js +2 -2
  40. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/cipher.js +3 -3
  41. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/class.js +4 -4
  42. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/functional.js +4 -4
  43. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/kdf.js +4 -4
  44. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/password.js +1 -1
  45. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/schema-validation-generated.js +1 -1
  46. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/lib/schema-validation.js +1 -1
  47. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/aes.js +1 -1
  48. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/pbkdf2.js +1 -1
  49. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/random.js +2 -2
  50. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/scrypt.js +1 -1
  51. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/sha256.js +1 -1
  52. package/bundle/packages/rln/node_modules/@chainsafe/bls-keystore/node_modules/ethereum-cryptography/utils.js +3 -3
  53. package/bundle/packages/rln/node_modules/@noble/hashes/_assert.js +1 -1
  54. package/bundle/packages/rln/node_modules/@noble/hashes/_sha2.js +2 -2
  55. package/bundle/packages/rln/node_modules/@noble/hashes/_u64.js +1 -1
  56. package/bundle/packages/rln/node_modules/@noble/hashes/cryptoBrowser.js +1 -1
  57. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
  58. package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
  59. package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
  60. package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
  61. package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
  62. package/bundle/packages/rln/node_modules/@noble/hashes/hmac.js +2 -2
  63. package/bundle/packages/rln/node_modules/@noble/hashes/pbkdf2.js +2 -2
  64. package/bundle/packages/rln/node_modules/@noble/hashes/scrypt.js +3 -3
  65. package/bundle/packages/rln/node_modules/@noble/hashes/sha256.js +2 -2
  66. package/bundle/packages/rln/node_modules/@noble/hashes/sha512.js +3 -3
  67. package/bundle/packages/rln/node_modules/@noble/hashes/utils.js +2 -2
  68. package/dist/.tsbuildinfo +1 -1
  69. package/dist/codec.test-utils.d.ts +36 -0
  70. package/dist/codec.test-utils.js +56 -0
  71. package/dist/codec.test-utils.js.map +1 -0
  72. package/dist/contract/abi.d.ts +21 -17
  73. package/dist/contract/abi.js +502 -248
  74. package/dist/contract/abi.js.map +1 -1
  75. package/dist/contract/constants.d.ts +23 -19
  76. package/dist/contract/constants.js +3 -3
  77. package/dist/contract/constants.js.map +1 -1
  78. package/dist/contract/errors.d.ts +30 -0
  79. package/dist/contract/errors.js +61 -0
  80. package/dist/contract/errors.js.map +1 -0
  81. package/dist/contract/rln_base_contract.d.ts +88 -0
  82. package/dist/contract/rln_base_contract.js +330 -0
  83. package/dist/contract/rln_base_contract.js.map +1 -0
  84. package/dist/contract/rln_contract.d.ts +19 -109
  85. package/dist/contract/rln_contract.js +80 -390
  86. package/dist/contract/rln_contract.js.map +1 -1
  87. package/dist/contract/test-setup.d.ts +26 -0
  88. package/dist/contract/test-setup.js +56 -0
  89. package/dist/contract/test-setup.js.map +1 -0
  90. package/dist/contract/test-utils.d.ts +39 -0
  91. package/dist/contract/test-utils.js +118 -0
  92. package/dist/contract/test-utils.js.map +1 -0
  93. package/dist/contract/types.d.ts +40 -0
  94. package/dist/contract/types.js +8 -0
  95. package/dist/contract/types.js.map +1 -0
  96. package/dist/create.js +1 -1
  97. package/dist/create.js.map +1 -1
  98. package/dist/credentials_manager.d.ts +44 -0
  99. package/dist/credentials_manager.js +197 -0
  100. package/dist/credentials_manager.js.map +1 -0
  101. package/dist/identity.d.ts +1 -0
  102. package/dist/identity.js +8 -0
  103. package/dist/identity.js.map +1 -1
  104. package/dist/index.d.ts +5 -2
  105. package/dist/index.js +4 -2
  106. package/dist/index.js.map +1 -1
  107. package/dist/keystore/keystore.d.ts +0 -1
  108. package/dist/keystore/keystore.js +20 -28
  109. package/dist/keystore/keystore.js.map +1 -1
  110. package/dist/keystore/types.d.ts +2 -1
  111. package/dist/rln.d.ts +9 -52
  112. package/dist/rln.js +54 -163
  113. package/dist/rln.js.map +1 -1
  114. package/dist/types.d.ts +27 -0
  115. package/dist/types.js +2 -0
  116. package/dist/types.js.map +1 -0
  117. package/dist/zerokit.d.ts +3 -3
  118. package/dist/zerokit.js +5 -5
  119. package/dist/zerokit.js.map +1 -1
  120. package/package.json +1 -1
  121. package/src/codec.test-utils.ts +80 -0
  122. package/src/contract/abi.ts +502 -248
  123. package/src/contract/constants.ts +3 -3
  124. package/src/contract/errors.ts +75 -0
  125. package/src/contract/rln_base_contract.ts +500 -0
  126. package/src/contract/rln_contract.ts +102 -619
  127. package/src/contract/test-setup.ts +86 -0
  128. package/src/contract/test-utils.ts +179 -0
  129. package/src/contract/types.ts +48 -0
  130. package/src/create.ts +1 -1
  131. package/src/credentials_manager.ts +282 -0
  132. package/src/identity.ts +9 -0
  133. package/src/index.ts +17 -2
  134. package/src/keystore/keystore.ts +32 -46
  135. package/src/keystore/types.ts +2 -1
  136. package/src/rln.ts +67 -258
  137. package/src/types.ts +31 -0
  138. package/src/zerokit.ts +3 -3
@@ -0,0 +1,86 @@
1
+ import { hexToBytes } from "@waku/utils/bytes";
2
+ import { ethers } from "ethers";
3
+ import sinon from "sinon";
4
+
5
+ import { createRLN } from "../create.js";
6
+ import type { IdentityCredential } from "../identity.js";
7
+
8
+ import { DEFAULT_RATE_LIMIT, LINEA_CONTRACT } from "./constants.js";
9
+ import { RLNContract } from "./rln_contract.js";
10
+
11
+ export interface TestRLNInstance {
12
+ rlnInstance: any;
13
+ identity: IdentityCredential;
14
+ insertMemberSpy: sinon.SinonStub;
15
+ }
16
+
17
+ /**
18
+ * Creates a test RLN instance with basic setup
19
+ */
20
+ export async function createTestRLNInstance(): Promise<TestRLNInstance> {
21
+ const rlnInstance = await createRLN();
22
+ const insertMemberSpy = sinon.stub();
23
+ rlnInstance.zerokit.insertMember = insertMemberSpy;
24
+
25
+ const mockSignature =
26
+ "0xdeb8a6b00a8e404deb1f52d3aa72ed7f60a2ff4484c737eedaef18a0aacb2dfb4d5d74ac39bb71fa358cf2eb390565a35b026cc6272f2010d4351e17670311c21c";
27
+ const identity =
28
+ rlnInstance.zerokit.generateSeededIdentityCredential(mockSignature);
29
+
30
+ return {
31
+ rlnInstance,
32
+ identity,
33
+ insertMemberSpy
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Initializes an RLN contract with the given registry contract
39
+ */
40
+ export async function initializeRLNContract(
41
+ rlnInstance: any,
42
+ mockedRegistryContract: ethers.Contract
43
+ ): Promise<RLNContract> {
44
+ const provider = new ethers.providers.JsonRpcProvider();
45
+ const voidSigner = new ethers.VoidSigner(LINEA_CONTRACT.address, provider);
46
+
47
+ const originalRegister = mockedRegistryContract.register;
48
+ (mockedRegistryContract as any).register = function (...args: any[]) {
49
+ const result = originalRegister.apply(this, args);
50
+
51
+ if (args[0] && rlnInstance.zerokit) {
52
+ const idCommitmentBigInt = args[0];
53
+ const idCommitmentHex =
54
+ "0x" + idCommitmentBigInt.toString(16).padStart(64, "0");
55
+ const idCommitment = ethers.utils.zeroPad(
56
+ hexToBytes(idCommitmentHex),
57
+ 32
58
+ );
59
+ rlnInstance.zerokit.insertMember(idCommitment);
60
+ }
61
+
62
+ return result;
63
+ };
64
+
65
+ const contract = await RLNContract.init(rlnInstance, {
66
+ address: LINEA_CONTRACT.address,
67
+ signer: voidSigner,
68
+ rateLimit: DEFAULT_RATE_LIMIT,
69
+ contract: mockedRegistryContract
70
+ });
71
+
72
+ return contract;
73
+ }
74
+
75
+ /**
76
+ * Common test message data
77
+ */
78
+ export const TEST_DATA = {
79
+ contentTopic: "/test/1/waku-message/utf8",
80
+ emptyPubsubTopic: "",
81
+ testMessage: Uint8Array.from(
82
+ "Hello World".split("").map((x) => x.charCodeAt(0))
83
+ ),
84
+ mockSignature:
85
+ "0xdeb8a6b00a8e404deb1f52d3aa72ed7f60a2ff4484c737eedaef18a0aacb2dfb4d5d74ac39bb71fa358cf2eb390565a35b026cc6272f2010d4351e17670311c21c"
86
+ } as const;
@@ -0,0 +1,179 @@
1
+ import { hexToBytes } from "@waku/utils/bytes";
2
+ import { expect } from "chai";
3
+ import * as ethers from "ethers";
4
+ import sinon from "sinon";
5
+
6
+ import type { IdentityCredential } from "../identity.js";
7
+
8
+ import { DEFAULT_RATE_LIMIT, LINEA_CONTRACT } from "./constants.js";
9
+
10
+ export const mockRateLimits = {
11
+ minRate: 20,
12
+ maxRate: 600,
13
+ maxTotalRate: 1200,
14
+ currentTotalRate: 500
15
+ };
16
+
17
+ type MockProvider = {
18
+ getLogs: () => never[];
19
+ getBlockNumber: () => Promise<number>;
20
+ getNetwork: () => Promise<{ chainId: number }>;
21
+ };
22
+
23
+ type MockFilters = {
24
+ MembershipRegistered: () => { address: string };
25
+ MembershipErased: () => { address: string };
26
+ MembershipExpired: () => { address: string };
27
+ };
28
+
29
+ export function createMockProvider(): MockProvider {
30
+ return {
31
+ getLogs: () => [],
32
+ getBlockNumber: () => Promise.resolve(1000),
33
+ getNetwork: () => Promise.resolve({ chainId: 11155111 })
34
+ };
35
+ }
36
+
37
+ export function createMockFilters(): MockFilters {
38
+ return {
39
+ MembershipRegistered: () => ({ address: LINEA_CONTRACT.address }),
40
+ MembershipErased: () => ({ address: LINEA_CONTRACT.address }),
41
+ MembershipExpired: () => ({ address: LINEA_CONTRACT.address })
42
+ };
43
+ }
44
+
45
+ type ContractOverrides = Partial<{
46
+ filters: Record<string, unknown>;
47
+ [key: string]: unknown;
48
+ }>;
49
+
50
+ export function createMockRegistryContract(
51
+ overrides: ContractOverrides = {}
52
+ ): ethers.Contract {
53
+ const filters = {
54
+ MembershipRegistered: () => ({ address: LINEA_CONTRACT.address }),
55
+ MembershipErased: () => ({ address: LINEA_CONTRACT.address }),
56
+ MembershipExpired: () => ({ address: LINEA_CONTRACT.address })
57
+ };
58
+
59
+ const baseContract = {
60
+ minMembershipRateLimit: () =>
61
+ Promise.resolve(ethers.BigNumber.from(mockRateLimits.minRate)),
62
+ maxMembershipRateLimit: () =>
63
+ Promise.resolve(ethers.BigNumber.from(mockRateLimits.maxRate)),
64
+ maxTotalRateLimit: () =>
65
+ Promise.resolve(ethers.BigNumber.from(mockRateLimits.maxTotalRate)),
66
+ currentTotalRateLimit: () =>
67
+ Promise.resolve(ethers.BigNumber.from(mockRateLimits.currentTotalRate)),
68
+ queryFilter: () => [],
69
+ provider: createMockProvider(),
70
+ filters,
71
+ on: () => ({}),
72
+ removeAllListeners: () => ({}),
73
+ register: () => ({
74
+ wait: () =>
75
+ Promise.resolve({
76
+ events: [mockRLNRegisteredEvent()]
77
+ })
78
+ }),
79
+ estimateGas: {
80
+ register: () => Promise.resolve(ethers.BigNumber.from(100000))
81
+ },
82
+ functions: {
83
+ register: () => Promise.resolve()
84
+ },
85
+ getMemberIndex: () => Promise.resolve(null),
86
+ interface: {
87
+ getEvent: (eventName: string) => ({
88
+ name: eventName,
89
+ format: () => {}
90
+ })
91
+ },
92
+ address: LINEA_CONTRACT.address
93
+ };
94
+
95
+ // Merge overrides while preserving filters
96
+ const merged = {
97
+ ...baseContract,
98
+ ...overrides,
99
+ filters: { ...filters, ...(overrides.filters || {}) }
100
+ };
101
+
102
+ return merged as unknown as ethers.Contract;
103
+ }
104
+
105
+ export function mockRLNRegisteredEvent(idCommitment?: string): ethers.Event {
106
+ return {
107
+ args: {
108
+ idCommitment:
109
+ idCommitment ||
110
+ "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
111
+ membershipRateLimit: ethers.BigNumber.from(DEFAULT_RATE_LIMIT),
112
+ index: ethers.BigNumber.from(1)
113
+ },
114
+ event: "MembershipRegistered"
115
+ } as unknown as ethers.Event;
116
+ }
117
+
118
+ export function formatIdCommitment(idCommitmentBigInt: bigint): string {
119
+ return "0x" + idCommitmentBigInt.toString(16).padStart(64, "0");
120
+ }
121
+
122
+ export function createRegisterStub(
123
+ identity: IdentityCredential
124
+ ): sinon.SinonStub {
125
+ return sinon.stub().callsFake(() => ({
126
+ wait: () =>
127
+ Promise.resolve({
128
+ events: [
129
+ {
130
+ event: "MembershipRegistered",
131
+ args: {
132
+ idCommitment: formatIdCommitment(identity.IDCommitmentBigInt),
133
+ membershipRateLimit: ethers.BigNumber.from(DEFAULT_RATE_LIMIT),
134
+ index: ethers.BigNumber.from(1)
135
+ }
136
+ }
137
+ ]
138
+ })
139
+ }));
140
+ }
141
+
142
+ export function verifyRegistration(
143
+ decryptedCredentials: any,
144
+ identity: IdentityCredential,
145
+ registerStub: sinon.SinonStub,
146
+ insertMemberSpy: sinon.SinonStub
147
+ ): void {
148
+ if (!decryptedCredentials) {
149
+ throw new Error("Decrypted credentials should not be undefined");
150
+ }
151
+
152
+ // Verify registration call
153
+ expect(
154
+ registerStub.calledWith(
155
+ sinon.match.same(identity.IDCommitmentBigInt),
156
+ sinon.match.same(DEFAULT_RATE_LIMIT),
157
+ sinon.match.array,
158
+ sinon.match.object
159
+ )
160
+ ).to.be.true;
161
+
162
+ // Verify credential properties
163
+ expect(decryptedCredentials).to.have.property("identity");
164
+ expect(decryptedCredentials).to.have.property("membership");
165
+ expect(decryptedCredentials.membership).to.include({
166
+ address: LINEA_CONTRACT.address,
167
+ treeIndex: 1
168
+ });
169
+
170
+ // Verify member insertion
171
+ const expectedIdCommitment = ethers.utils.zeroPad(
172
+ hexToBytes(formatIdCommitment(identity.IDCommitmentBigInt)),
173
+ 32
174
+ );
175
+ expect(insertMemberSpy.callCount).to.equal(1);
176
+ expect(insertMemberSpy.getCall(0).args[0]).to.deep.equal(
177
+ expectedIdCommitment
178
+ );
179
+ }
@@ -0,0 +1,48 @@
1
+ import { ethers } from "ethers";
2
+
3
+ export interface CustomQueryOptions extends FetchMembersOptions {
4
+ membersFilter: ethers.EventFilter;
5
+ }
6
+
7
+ export type Member = {
8
+ idCommitment: string;
9
+ index: ethers.BigNumber;
10
+ };
11
+
12
+ export interface RLNContractOptions {
13
+ signer: ethers.Signer;
14
+ address: string;
15
+ rateLimit?: number;
16
+ }
17
+
18
+ export interface RLNContractInitOptions extends RLNContractOptions {
19
+ contract?: ethers.Contract;
20
+ }
21
+
22
+ export interface MembershipRegisteredEvent {
23
+ idCommitment: string;
24
+ membershipRateLimit: ethers.BigNumber;
25
+ index: ethers.BigNumber;
26
+ }
27
+
28
+ export type FetchMembersOptions = {
29
+ fromBlock?: number;
30
+ fetchRange?: number;
31
+ fetchChunks?: number;
32
+ };
33
+
34
+ export interface MembershipInfo {
35
+ index: ethers.BigNumber;
36
+ idCommitment: string;
37
+ rateLimit: number;
38
+ startBlock: number;
39
+ endBlock: number;
40
+ state: MembershipState;
41
+ }
42
+
43
+ export enum MembershipState {
44
+ Active = "Active",
45
+ GracePeriod = "GracePeriod",
46
+ Expired = "Expired",
47
+ ErasedAwaitsWithdrawal = "ErasedAwaitsWithdrawal"
48
+ }
package/src/create.ts CHANGED
@@ -5,5 +5,5 @@ export async function createRLN(): Promise<RLNInstance> {
5
5
  // asynchronously. This file does the single async import, so
6
6
  // that no one else needs to worry about it again.
7
7
  const rlnModule = await import("./rln.js");
8
- return rlnModule.create();
8
+ return rlnModule.RLNInstance.create();
9
9
  }
@@ -0,0 +1,282 @@
1
+ import { hmac } from "@noble/hashes/hmac";
2
+ import { sha256 } from "@noble/hashes/sha256";
3
+ import { Logger } from "@waku/utils";
4
+ import { ethers } from "ethers";
5
+
6
+ import { LINEA_CONTRACT } from "./contract/constants.js";
7
+ import { RLNBaseContract } from "./contract/rln_base_contract.js";
8
+ import { IdentityCredential } from "./identity.js";
9
+ import { Keystore } from "./keystore/index.js";
10
+ import type {
11
+ DecryptedCredentials,
12
+ EncryptedCredentials
13
+ } from "./keystore/index.js";
14
+ import { KeystoreEntity, Password } from "./keystore/types.js";
15
+ import { RegisterMembershipOptions, StartRLNOptions } from "./types.js";
16
+ import {
17
+ buildBigIntFromUint8Array,
18
+ extractMetaMaskSigner
19
+ } from "./utils/index.js";
20
+ import { Zerokit } from "./zerokit.js";
21
+
22
+ const log = new Logger("waku:credentials");
23
+
24
+ /**
25
+ * Manages credentials for RLN
26
+ * This is a lightweight implementation of the RLN contract that doesn't require Zerokit
27
+ * It is used to register membership and generate identity credentials
28
+ */
29
+ export class RLNCredentialsManager {
30
+ protected started = false;
31
+ protected starting = false;
32
+
33
+ public contract: undefined | RLNBaseContract;
34
+ public signer: undefined | ethers.Signer;
35
+
36
+ protected keystore = Keystore.create();
37
+ public credentials: undefined | DecryptedCredentials;
38
+
39
+ public zerokit: undefined | Zerokit;
40
+
41
+ public constructor(zerokit?: Zerokit) {
42
+ log.info("RLNCredentialsManager initialized");
43
+ this.zerokit = zerokit;
44
+ }
45
+
46
+ public get provider(): undefined | ethers.providers.Provider {
47
+ return this.contract?.provider;
48
+ }
49
+
50
+ public async start(options: StartRLNOptions = {}): Promise<void> {
51
+ if (this.started || this.starting) {
52
+ log.info("RLNCredentialsManager already started or starting");
53
+ return;
54
+ }
55
+
56
+ log.info("Starting RLNCredentialsManager");
57
+ this.starting = true;
58
+
59
+ try {
60
+ const { credentials, keystore } =
61
+ await RLNCredentialsManager.decryptCredentialsIfNeeded(
62
+ options.credentials
63
+ );
64
+
65
+ if (credentials) {
66
+ log.info("Credentials successfully decrypted");
67
+ }
68
+
69
+ const { signer, address, rateLimit } = await this.determineStartOptions(
70
+ options,
71
+ credentials
72
+ );
73
+
74
+ log.info(`Using contract address: ${address}`);
75
+
76
+ if (keystore) {
77
+ this.keystore = keystore;
78
+ log.info("Using provided keystore");
79
+ }
80
+
81
+ this.credentials = credentials;
82
+ this.signer = signer!;
83
+ this.contract = new RLNBaseContract({
84
+ address: address!,
85
+ signer: signer!,
86
+ rateLimit: rateLimit ?? this.zerokit?.rateLimit
87
+ });
88
+
89
+ log.info("RLNCredentialsManager successfully started");
90
+ this.started = true;
91
+ } catch (error) {
92
+ log.error("Failed to start RLNCredentialsManager", error);
93
+ throw error;
94
+ } finally {
95
+ this.starting = false;
96
+ }
97
+ }
98
+
99
+ public async registerMembership(
100
+ options: RegisterMembershipOptions
101
+ ): Promise<undefined | DecryptedCredentials> {
102
+ if (!this.contract) {
103
+ log.error("RLN Contract is not initialized");
104
+ throw Error("RLN Contract is not initialized.");
105
+ }
106
+
107
+ log.info("Registering membership");
108
+ let identity = "identity" in options && options.identity;
109
+
110
+ if ("signature" in options) {
111
+ log.info("Generating identity from signature");
112
+ if (this.zerokit) {
113
+ log.info("Using Zerokit to generate identity");
114
+ identity = this.zerokit.generateSeededIdentityCredential(
115
+ options.signature
116
+ );
117
+ } else {
118
+ log.info("Using local implementation to generate identity");
119
+ identity = this.generateSeededIdentityCredential(options.signature);
120
+ }
121
+ }
122
+
123
+ if (!identity) {
124
+ log.error("Missing signature or identity to register membership");
125
+ throw Error("Missing signature or identity to register membership.");
126
+ }
127
+
128
+ log.info("Registering identity with contract");
129
+ return this.contract.registerWithIdentity(identity);
130
+ }
131
+
132
+ /**
133
+ * Changes credentials in use by relying on provided Keystore earlier in rln.start
134
+ * @param id: string, hash of credentials to select from Keystore
135
+ * @param password: string or bytes to use to decrypt credentials from Keystore
136
+ */
137
+ public async useCredentials(id: string, password: Password): Promise<void> {
138
+ log.info(`Attempting to use credentials with ID: ${id}`);
139
+ this.credentials = await this.keystore?.readCredential(id, password);
140
+ if (this.credentials) {
141
+ log.info("Successfully loaded credentials");
142
+ } else {
143
+ log.warn("Failed to load credentials");
144
+ }
145
+ }
146
+
147
+ protected async determineStartOptions(
148
+ options: StartRLNOptions,
149
+ credentials: KeystoreEntity | undefined
150
+ ): Promise<StartRLNOptions> {
151
+ let chainId = credentials?.membership.chainId;
152
+ const address =
153
+ credentials?.membership.address ||
154
+ options.address ||
155
+ LINEA_CONTRACT.address;
156
+
157
+ if (address === LINEA_CONTRACT.address) {
158
+ chainId = LINEA_CONTRACT.chainId;
159
+ log.info(`Using Linea contract with chainId: ${chainId}`);
160
+ }
161
+
162
+ const signer = options.signer || (await extractMetaMaskSigner());
163
+ const currentChainId = await signer.getChainId();
164
+ log.info(`Current chain ID: ${currentChainId}`);
165
+
166
+ if (chainId && chainId !== currentChainId.toString()) {
167
+ log.error(
168
+ `Chain ID mismatch: contract=${chainId}, current=${currentChainId}`
169
+ );
170
+ throw Error(
171
+ `Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`
172
+ );
173
+ }
174
+
175
+ return {
176
+ signer,
177
+ address
178
+ };
179
+ }
180
+
181
+ protected static async decryptCredentialsIfNeeded(
182
+ credentials?: EncryptedCredentials | DecryptedCredentials
183
+ ): Promise<{ credentials?: DecryptedCredentials; keystore?: Keystore }> {
184
+ if (!credentials) {
185
+ log.info("No credentials provided");
186
+ return {};
187
+ }
188
+
189
+ if ("identity" in credentials) {
190
+ log.info("Using already decrypted credentials");
191
+ return { credentials };
192
+ }
193
+
194
+ log.info("Attempting to decrypt credentials");
195
+ const keystore = Keystore.fromString(credentials.keystore);
196
+
197
+ if (!keystore) {
198
+ log.warn("Failed to create keystore from string");
199
+ return {};
200
+ }
201
+
202
+ try {
203
+ const decryptedCredentials = await keystore.readCredential(
204
+ credentials.id,
205
+ credentials.password
206
+ );
207
+ log.info(`Successfully decrypted credentials with ID: ${credentials.id}`);
208
+
209
+ return {
210
+ keystore,
211
+ credentials: decryptedCredentials
212
+ };
213
+ } catch (error) {
214
+ log.error("Failed to decrypt credentials", error);
215
+ throw error;
216
+ }
217
+ }
218
+
219
+ protected async verifyCredentialsAgainstContract(
220
+ credentials: KeystoreEntity
221
+ ): Promise<void> {
222
+ if (!this.contract) {
223
+ throw Error(
224
+ "Failed to verify chain coordinates: no contract initialized."
225
+ );
226
+ }
227
+
228
+ const registryAddress = credentials.membership.address;
229
+ const currentRegistryAddress = this.contract.address;
230
+ if (registryAddress !== currentRegistryAddress) {
231
+ throw Error(
232
+ `Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`
233
+ );
234
+ }
235
+
236
+ const chainId = credentials.membership.chainId;
237
+ const network = await this.contract.provider.getNetwork();
238
+ const currentChainId = network.chainId;
239
+ if (chainId !== currentChainId.toString()) {
240
+ throw Error(
241
+ `Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`
242
+ );
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Generates an identity credential from a seed string
248
+ * This is a pure implementation that doesn't rely on Zerokit
249
+ * @param seed A string seed to generate the identity from
250
+ * @returns IdentityCredential
251
+ */
252
+ private generateSeededIdentityCredential(seed: string): IdentityCredential {
253
+ log.info("Generating seeded identity credential");
254
+ // Convert the seed to bytes
255
+ const encoder = new TextEncoder();
256
+ const seedBytes = encoder.encode(seed);
257
+
258
+ // Generate deterministic values using HMAC-SHA256
259
+ // We use different context strings for each component to ensure they're different
260
+ const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
261
+ const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
262
+
263
+ // Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
264
+ const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
265
+ const idSecretHash = sha256(combinedBytes);
266
+
267
+ // Generate IDCommitment as a hash of IDSecretHash
268
+ const idCommitment = sha256(idSecretHash);
269
+
270
+ // Convert IDCommitment to BigInt
271
+ const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
272
+
273
+ log.info("Successfully generated identity credential");
274
+ return new IdentityCredential(
275
+ idTrapdoor,
276
+ idNullifier,
277
+ idSecretHash,
278
+ idCommitment,
279
+ idCommitmentBigInt
280
+ );
281
+ }
282
+ }
package/src/identity.ts CHANGED
@@ -28,4 +28,13 @@ export class IdentityCredential {
28
28
  idCommitmentBigInt
29
29
  );
30
30
  }
31
+
32
+ public toJSON(): Record<string, number[]> {
33
+ return {
34
+ idTrapdoor: Array.from(this.IDTrapdoor),
35
+ idNullifier: Array.from(this.IDNullifier),
36
+ idSecretHash: Array.from(this.IDSecretHash),
37
+ idCommitment: Array.from(this.IDCommitment)
38
+ };
39
+ }
31
40
  }
package/src/index.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { RLNDecoder, RLNEncoder } from "./codec.js";
2
2
  import { RLN_ABI } from "./contract/abi.js";
3
- import { RLNContract, SEPOLIA_CONTRACT } from "./contract/index.js";
3
+ import { LINEA_CONTRACT, RLNContract } from "./contract/index.js";
4
+ import { RLNBaseContract } from "./contract/rln_base_contract.js";
4
5
  import { createRLN } from "./create.js";
6
+ import { RLNCredentialsManager } from "./credentials_manager.js";
5
7
  import { IdentityCredential } from "./identity.js";
6
8
  import { Keystore } from "./keystore/index.js";
7
9
  import { Proof } from "./proof.js";
@@ -10,6 +12,8 @@ import { MerkleRootTracker } from "./root_tracker.js";
10
12
  import { extractMetaMaskSigner } from "./utils/index.js";
11
13
 
12
14
  export {
15
+ RLNCredentialsManager,
16
+ RLNBaseContract,
13
17
  createRLN,
14
18
  Keystore,
15
19
  RLNInstance,
@@ -19,7 +23,18 @@ export {
19
23
  RLNDecoder,
20
24
  MerkleRootTracker,
21
25
  RLNContract,
22
- SEPOLIA_CONTRACT,
26
+ LINEA_CONTRACT,
23
27
  extractMetaMaskSigner,
24
28
  RLN_ABI
25
29
  };
30
+
31
+ export type {
32
+ DecryptedCredentials,
33
+ EncryptedCredentials,
34
+ Keccak256Hash,
35
+ KeystoreEntity,
36
+ MembershipHash,
37
+ MembershipInfo,
38
+ Password,
39
+ Sha256Hash
40
+ } from "./keystore/types.js";