@waku/rln 0.1.5-a8ff776.0 → 0.1.5-aaa7a0c.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/bundle/index.js +2 -0
- package/bundle/packages/rln/dist/contract/rln_base_contract.js +477 -0
- package/bundle/packages/rln/dist/contract/rln_contract.js +9 -419
- package/bundle/packages/rln/dist/contract/types.js +9 -0
- package/bundle/packages/rln/dist/create.js +1 -1
- package/bundle/packages/rln/dist/credentials_manager.js +215 -0
- package/bundle/packages/rln/dist/keystore/keystore.js +7 -4
- package/bundle/packages/rln/dist/rln.js +56 -166
- package/bundle/packages/rln/dist/zerokit.js +5 -5
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/_assert.js +43 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/_sha2.js +116 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/hmac.js +79 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/sha256.js +126 -0
- package/bundle/packages/rln/node_modules/@noble/hashes/esm/utils.js +43 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/contract/rln_base_contract.d.ts +96 -0
- package/dist/contract/rln_base_contract.js +460 -0
- package/dist/contract/rln_base_contract.js.map +1 -0
- package/dist/contract/rln_contract.d.ts +5 -122
- package/dist/contract/rln_contract.js +8 -417
- package/dist/contract/rln_contract.js.map +1 -1
- package/dist/contract/types.d.ts +40 -0
- package/dist/contract/types.js +8 -0
- package/dist/contract/types.js.map +1 -0
- package/dist/create.js +1 -1
- package/dist/create.js.map +1 -1
- package/dist/credentials_manager.d.ts +44 -0
- package/dist/credentials_manager.js +197 -0
- package/dist/credentials_manager.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/keystore/keystore.js +7 -4
- package/dist/keystore/keystore.js.map +1 -1
- package/dist/keystore/types.d.ts +1 -1
- package/dist/rln.d.ts +9 -52
- package/dist/rln.js +54 -163
- package/dist/rln.js.map +1 -1
- package/dist/types.d.ts +27 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/zerokit.d.ts +3 -3
- package/dist/zerokit.js +5 -5
- package/dist/zerokit.js.map +1 -1
- package/package.json +1 -1
- package/src/contract/rln_base_contract.ts +707 -0
- package/src/contract/rln_contract.ts +9 -663
- package/src/contract/types.ts +48 -0
- package/src/create.ts +1 -1
- package/src/credentials_manager.ts +282 -0
- package/src/index.ts +4 -0
- package/src/keystore/keystore.ts +15 -8
- package/src/keystore/types.ts +1 -1
- package/src/rln.ts +67 -258
- package/src/types.ts +31 -0
- package/src/zerokit.ts +3 -3
@@ -0,0 +1,215 @@
|
|
1
|
+
import { hmac } from '../node_modules/@noble/hashes/esm/hmac.js';
|
2
|
+
import { sha256 } from '../node_modules/@noble/hashes/esm/sha256.js';
|
3
|
+
import '../../interfaces/dist/protocols.js';
|
4
|
+
import '../../interfaces/dist/connection_manager.js';
|
5
|
+
import '../../interfaces/dist/health_indicator.js';
|
6
|
+
import '../../../node_modules/multiformats/dist/src/bases/base10.js';
|
7
|
+
import '../../../node_modules/multiformats/dist/src/bases/base16.js';
|
8
|
+
import '../../../node_modules/multiformats/dist/src/bases/base2.js';
|
9
|
+
import '../../../node_modules/multiformats/dist/src/bases/base256emoji.js';
|
10
|
+
import '../../../node_modules/multiformats/dist/src/bases/base32.js';
|
11
|
+
import '../../../node_modules/multiformats/dist/src/bases/base36.js';
|
12
|
+
import '../../../node_modules/multiformats/dist/src/bases/base58.js';
|
13
|
+
import '../../../node_modules/multiformats/dist/src/bases/base64.js';
|
14
|
+
import '../../../node_modules/multiformats/dist/src/bases/base8.js';
|
15
|
+
import '../../../node_modules/multiformats/dist/src/bases/identity.js';
|
16
|
+
import '../../../node_modules/multiformats/dist/src/codecs/json.js';
|
17
|
+
import { Logger } from '../../utils/dist/logger/index.js';
|
18
|
+
import { LINEA_CONTRACT } from './contract/constants.js';
|
19
|
+
import { RLNBaseContract } from './contract/rln_base_contract.js';
|
20
|
+
import { IdentityCredential } from './identity.js';
|
21
|
+
import { Keystore } from './keystore/keystore.js';
|
22
|
+
import { extractMetaMaskSigner } from './utils/metamask.js';
|
23
|
+
import { buildBigIntFromUint8Array } from './utils/bytes.js';
|
24
|
+
import './utils/epoch.js';
|
25
|
+
|
26
|
+
const log = new Logger("waku:credentials");
|
27
|
+
/**
|
28
|
+
* Manages credentials for RLN
|
29
|
+
* This is a lightweight implementation of the RLN contract that doesn't require Zerokit
|
30
|
+
* It is used to register membership and generate identity credentials
|
31
|
+
*/
|
32
|
+
class RLNCredentialsManager {
|
33
|
+
started = false;
|
34
|
+
starting = false;
|
35
|
+
contract;
|
36
|
+
signer;
|
37
|
+
keystore = Keystore.create();
|
38
|
+
credentials;
|
39
|
+
zerokit;
|
40
|
+
constructor(zerokit) {
|
41
|
+
log.info("RLNCredentialsManager initialized");
|
42
|
+
this.zerokit = zerokit;
|
43
|
+
}
|
44
|
+
get provider() {
|
45
|
+
return this.contract?.provider;
|
46
|
+
}
|
47
|
+
async start(options = {}) {
|
48
|
+
if (this.started || this.starting) {
|
49
|
+
log.info("RLNCredentialsManager already started or starting");
|
50
|
+
return;
|
51
|
+
}
|
52
|
+
log.info("Starting RLNCredentialsManager");
|
53
|
+
this.starting = true;
|
54
|
+
try {
|
55
|
+
const { credentials, keystore } = await RLNCredentialsManager.decryptCredentialsIfNeeded(options.credentials);
|
56
|
+
if (credentials) {
|
57
|
+
log.info("Credentials successfully decrypted");
|
58
|
+
}
|
59
|
+
const { signer, address, rateLimit } = await this.determineStartOptions(options, credentials);
|
60
|
+
log.info(`Using contract address: ${address}`);
|
61
|
+
if (keystore) {
|
62
|
+
this.keystore = keystore;
|
63
|
+
log.info("Using provided keystore");
|
64
|
+
}
|
65
|
+
this.credentials = credentials;
|
66
|
+
this.signer = signer;
|
67
|
+
this.contract = new RLNBaseContract({
|
68
|
+
address: address,
|
69
|
+
signer: signer,
|
70
|
+
rateLimit: rateLimit ?? this.zerokit?.rateLimit
|
71
|
+
});
|
72
|
+
log.info("RLNCredentialsManager successfully started");
|
73
|
+
this.started = true;
|
74
|
+
}
|
75
|
+
catch (error) {
|
76
|
+
log.error("Failed to start RLNCredentialsManager", error);
|
77
|
+
throw error;
|
78
|
+
}
|
79
|
+
finally {
|
80
|
+
this.starting = false;
|
81
|
+
}
|
82
|
+
}
|
83
|
+
async registerMembership(options) {
|
84
|
+
if (!this.contract) {
|
85
|
+
log.error("RLN Contract is not initialized");
|
86
|
+
throw Error("RLN Contract is not initialized.");
|
87
|
+
}
|
88
|
+
log.info("Registering membership");
|
89
|
+
let identity = "identity" in options && options.identity;
|
90
|
+
if ("signature" in options) {
|
91
|
+
log.info("Generating identity from signature");
|
92
|
+
if (this.zerokit) {
|
93
|
+
log.info("Using Zerokit to generate identity");
|
94
|
+
identity = this.zerokit.generateSeededIdentityCredential(options.signature);
|
95
|
+
}
|
96
|
+
else {
|
97
|
+
log.info("Using local implementation to generate identity");
|
98
|
+
identity = this.generateSeededIdentityCredential(options.signature);
|
99
|
+
}
|
100
|
+
}
|
101
|
+
if (!identity) {
|
102
|
+
log.error("Missing signature or identity to register membership");
|
103
|
+
throw Error("Missing signature or identity to register membership.");
|
104
|
+
}
|
105
|
+
log.info("Registering identity with contract");
|
106
|
+
return this.contract.registerWithIdentity(identity);
|
107
|
+
}
|
108
|
+
/**
|
109
|
+
* Changes credentials in use by relying on provided Keystore earlier in rln.start
|
110
|
+
* @param id: string, hash of credentials to select from Keystore
|
111
|
+
* @param password: string or bytes to use to decrypt credentials from Keystore
|
112
|
+
*/
|
113
|
+
async useCredentials(id, password) {
|
114
|
+
log.info(`Attempting to use credentials with ID: ${id}`);
|
115
|
+
this.credentials = await this.keystore?.readCredential(id, password);
|
116
|
+
if (this.credentials) {
|
117
|
+
log.info("Successfully loaded credentials");
|
118
|
+
}
|
119
|
+
else {
|
120
|
+
log.warn("Failed to load credentials");
|
121
|
+
}
|
122
|
+
}
|
123
|
+
async determineStartOptions(options, credentials) {
|
124
|
+
let chainId = credentials?.membership.chainId;
|
125
|
+
const address = credentials?.membership.address ||
|
126
|
+
options.address ||
|
127
|
+
LINEA_CONTRACT.address;
|
128
|
+
if (address === LINEA_CONTRACT.address) {
|
129
|
+
chainId = LINEA_CONTRACT.chainId.toString();
|
130
|
+
log.info(`Using Linea contract with chainId: ${chainId}`);
|
131
|
+
}
|
132
|
+
const signer = options.signer || (await extractMetaMaskSigner());
|
133
|
+
const currentChainId = await signer.getChainId();
|
134
|
+
log.info(`Current chain ID: ${currentChainId}`);
|
135
|
+
if (chainId && chainId !== currentChainId.toString()) {
|
136
|
+
log.error(`Chain ID mismatch: contract=${chainId}, current=${currentChainId}`);
|
137
|
+
throw Error(`Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`);
|
138
|
+
}
|
139
|
+
return {
|
140
|
+
signer,
|
141
|
+
address
|
142
|
+
};
|
143
|
+
}
|
144
|
+
static async decryptCredentialsIfNeeded(credentials) {
|
145
|
+
if (!credentials) {
|
146
|
+
log.info("No credentials provided");
|
147
|
+
return {};
|
148
|
+
}
|
149
|
+
if ("identity" in credentials) {
|
150
|
+
log.info("Using already decrypted credentials");
|
151
|
+
return { credentials };
|
152
|
+
}
|
153
|
+
log.info("Attempting to decrypt credentials");
|
154
|
+
const keystore = Keystore.fromString(credentials.keystore);
|
155
|
+
if (!keystore) {
|
156
|
+
log.warn("Failed to create keystore from string");
|
157
|
+
return {};
|
158
|
+
}
|
159
|
+
try {
|
160
|
+
const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
|
161
|
+
log.info(`Successfully decrypted credentials with ID: ${credentials.id}`);
|
162
|
+
return {
|
163
|
+
keystore,
|
164
|
+
credentials: decryptedCredentials
|
165
|
+
};
|
166
|
+
}
|
167
|
+
catch (error) {
|
168
|
+
log.error("Failed to decrypt credentials", error);
|
169
|
+
throw error;
|
170
|
+
}
|
171
|
+
}
|
172
|
+
async verifyCredentialsAgainstContract(credentials) {
|
173
|
+
if (!this.contract) {
|
174
|
+
throw Error("Failed to verify chain coordinates: no contract initialized.");
|
175
|
+
}
|
176
|
+
const registryAddress = credentials.membership.address;
|
177
|
+
const currentRegistryAddress = this.contract.address;
|
178
|
+
if (registryAddress !== currentRegistryAddress) {
|
179
|
+
throw Error(`Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`);
|
180
|
+
}
|
181
|
+
const chainId = credentials.membership.chainId;
|
182
|
+
const network = await this.contract.provider.getNetwork();
|
183
|
+
const currentChainId = network.chainId;
|
184
|
+
if (chainId !== currentChainId.toString()) {
|
185
|
+
throw Error(`Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`);
|
186
|
+
}
|
187
|
+
}
|
188
|
+
/**
|
189
|
+
* Generates an identity credential from a seed string
|
190
|
+
* This is a pure implementation that doesn't rely on Zerokit
|
191
|
+
* @param seed A string seed to generate the identity from
|
192
|
+
* @returns IdentityCredential
|
193
|
+
*/
|
194
|
+
generateSeededIdentityCredential(seed) {
|
195
|
+
log.info("Generating seeded identity credential");
|
196
|
+
// Convert the seed to bytes
|
197
|
+
const encoder = new TextEncoder();
|
198
|
+
const seedBytes = encoder.encode(seed);
|
199
|
+
// Generate deterministic values using HMAC-SHA256
|
200
|
+
// We use different context strings for each component to ensure they're different
|
201
|
+
const idTrapdoor = hmac(sha256, seedBytes, encoder.encode("IDTrapdoor"));
|
202
|
+
const idNullifier = hmac(sha256, seedBytes, encoder.encode("IDNullifier"));
|
203
|
+
// Generate IDSecretHash as a hash of IDTrapdoor and IDNullifier
|
204
|
+
const combinedBytes = new Uint8Array([...idTrapdoor, ...idNullifier]);
|
205
|
+
const idSecretHash = sha256(combinedBytes);
|
206
|
+
// Generate IDCommitment as a hash of IDSecretHash
|
207
|
+
const idCommitment = sha256(idSecretHash);
|
208
|
+
// Convert IDCommitment to BigInt
|
209
|
+
const idCommitmentBigInt = buildBigIntFromUint8Array(idCommitment);
|
210
|
+
log.info("Successfully generated identity credential");
|
211
|
+
return new IdentityCredential(idTrapdoor, idNullifier, idSecretHash, idCommitment, idCommitmentBigInt);
|
212
|
+
}
|
213
|
+
}
|
214
|
+
|
215
|
+
export { RLNCredentialsManager };
|
@@ -187,6 +187,9 @@ class Keystore {
|
|
187
187
|
}
|
188
188
|
}
|
189
189
|
static fromArraylikeToBytes(obj) {
|
190
|
+
if (Array.isArray(obj)) {
|
191
|
+
return new Uint8Array(obj);
|
192
|
+
}
|
190
193
|
const bytes = [];
|
191
194
|
let index = 0;
|
192
195
|
let lastElement = obj[index];
|
@@ -208,10 +211,10 @@ class Keystore {
|
|
208
211
|
return utf8ToBytes(JSON.stringify({
|
209
212
|
treeIndex: options.membership.treeIndex,
|
210
213
|
identityCredential: {
|
211
|
-
idCommitment: options.identity.IDCommitment,
|
212
|
-
idNullifier: options.identity.IDNullifier,
|
213
|
-
idSecretHash: options.identity.IDSecretHash,
|
214
|
-
idTrapdoor: options.identity.IDTrapdoor
|
214
|
+
idCommitment: Array.from(options.identity.IDCommitment),
|
215
|
+
idNullifier: Array.from(options.identity.IDNullifier),
|
216
|
+
idSecretHash: Array.from(options.identity.IDSecretHash),
|
217
|
+
idTrapdoor: Array.from(options.identity.IDTrapdoor)
|
215
218
|
},
|
216
219
|
membershipContract: {
|
217
220
|
chainId: options.membership.chainId,
|
@@ -21,167 +21,45 @@ import { Logger } from '../../utils/dist/logger/index.js';
|
|
21
21
|
import '../../core/dist/lib/metadata/metadata.js';
|
22
22
|
import __wbg_init, { init_panic_hook, newRLN } from '../../../node_modules/@waku/zerokit-rln-wasm/rln_wasm.js';
|
23
23
|
import { createRLNEncoder, createRLNDecoder } from './codec.js';
|
24
|
-
import {
|
25
|
-
import {
|
26
|
-
import { Keystore } from './keystore/keystore.js';
|
24
|
+
import { DEFAULT_RATE_LIMIT } from './contract/constants.js';
|
25
|
+
import { RLNCredentialsManager } from './credentials_manager.js';
|
27
26
|
import verificationKey from './resources/verification_key.js';
|
28
27
|
import { builder } from './resources/witness_calculator.js';
|
29
|
-
import { extractMetaMaskSigner } from './utils/metamask.js';
|
30
|
-
import './utils/epoch.js';
|
31
28
|
import { Zerokit } from './zerokit.js';
|
32
29
|
|
33
30
|
const log = new Logger("waku:rln");
|
34
|
-
|
35
|
-
try {
|
36
|
-
const url = new URL("./resources/rln.wasm", import.meta.url);
|
37
|
-
const response = await fetch(url);
|
38
|
-
if (!response.ok) {
|
39
|
-
throw new Error(`Failed to fetch witness calculator: ${response.status} ${response.statusText}`);
|
40
|
-
}
|
41
|
-
return await builder(new Uint8Array(await response.arrayBuffer()), false);
|
42
|
-
}
|
43
|
-
catch (error) {
|
44
|
-
log.error("Error loading witness calculator:", error);
|
45
|
-
throw new Error(`Failed to load witness calculator: ${error instanceof Error ? error.message : String(error)}`);
|
46
|
-
}
|
47
|
-
}
|
48
|
-
async function loadZkey() {
|
49
|
-
try {
|
50
|
-
const url = new URL("./resources/rln_final.zkey", import.meta.url);
|
51
|
-
const response = await fetch(url);
|
52
|
-
if (!response.ok) {
|
53
|
-
throw new Error(`Failed to fetch zkey: ${response.status} ${response.statusText}`);
|
54
|
-
}
|
55
|
-
return new Uint8Array(await response.arrayBuffer());
|
56
|
-
}
|
57
|
-
catch (error) {
|
58
|
-
log.error("Error loading zkey:", error);
|
59
|
-
throw new Error(`Failed to load zkey: ${error instanceof Error ? error.message : String(error)}`);
|
60
|
-
}
|
61
|
-
}
|
62
|
-
/**
|
63
|
-
* Create an instance of RLN
|
64
|
-
* @returns RLNInstance
|
65
|
-
*/
|
66
|
-
async function create() {
|
67
|
-
try {
|
68
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
69
|
-
await __wbg_init?.();
|
70
|
-
init_panic_hook();
|
71
|
-
const witnessCalculator = await loadWitnessCalculator();
|
72
|
-
const zkey = await loadZkey();
|
73
|
-
const stringEncoder = new TextEncoder();
|
74
|
-
const vkey = stringEncoder.encode(JSON.stringify(verificationKey));
|
75
|
-
const DEPTH = 20;
|
76
|
-
const zkRLN = newRLN(DEPTH, zkey, vkey);
|
77
|
-
const zerokit = new Zerokit(zkRLN, witnessCalculator, DEFAULT_RATE_LIMIT);
|
78
|
-
return new RLNInstance(zerokit);
|
79
|
-
}
|
80
|
-
catch (error) {
|
81
|
-
log.error("Failed to initialize RLN:", error);
|
82
|
-
throw error;
|
83
|
-
}
|
84
|
-
}
|
85
|
-
class RLNInstance {
|
31
|
+
class RLNInstance extends RLNCredentialsManager {
|
86
32
|
zerokit;
|
87
|
-
|
88
|
-
|
89
|
-
|
90
|
-
|
91
|
-
|
92
|
-
_credentials;
|
93
|
-
constructor(zerokit) {
|
94
|
-
this.zerokit = zerokit;
|
95
|
-
}
|
96
|
-
get contract() {
|
97
|
-
return this._contract;
|
98
|
-
}
|
99
|
-
get signer() {
|
100
|
-
return this._signer;
|
101
|
-
}
|
102
|
-
async start(options = {}) {
|
103
|
-
if (this.started || this.starting) {
|
104
|
-
return;
|
105
|
-
}
|
106
|
-
this.starting = true;
|
33
|
+
/**
|
34
|
+
* Create an instance of RLN
|
35
|
+
* @returns RLNInstance
|
36
|
+
*/
|
37
|
+
static async create() {
|
107
38
|
try {
|
108
|
-
|
109
|
-
|
110
|
-
|
111
|
-
|
112
|
-
|
113
|
-
|
114
|
-
|
115
|
-
|
116
|
-
|
117
|
-
|
118
|
-
|
119
|
-
|
120
|
-
|
39
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
40
|
+
await __wbg_init?.();
|
41
|
+
init_panic_hook();
|
42
|
+
const witnessCalculator = await RLNInstance.loadWitnessCalculator();
|
43
|
+
const zkey = await RLNInstance.loadZkey();
|
44
|
+
const stringEncoder = new TextEncoder();
|
45
|
+
const vkey = stringEncoder.encode(JSON.stringify(verificationKey));
|
46
|
+
const DEPTH = 20;
|
47
|
+
const zkRLN = newRLN(DEPTH, zkey, vkey);
|
48
|
+
const zerokit = new Zerokit(zkRLN, witnessCalculator, DEFAULT_RATE_LIMIT);
|
49
|
+
return new RLNInstance(zerokit);
|
50
|
+
}
|
51
|
+
catch (error) {
|
52
|
+
log.error("Failed to initialize RLN:", error);
|
53
|
+
throw error;
|
121
54
|
}
|
122
|
-
finally {
|
123
|
-
this.starting = false;
|
124
|
-
}
|
125
|
-
}
|
126
|
-
async determineStartOptions(options, credentials) {
|
127
|
-
let chainId = credentials?.membership.chainId;
|
128
|
-
const address = credentials?.membership.address ||
|
129
|
-
options.address ||
|
130
|
-
LINEA_CONTRACT.address;
|
131
|
-
if (address === LINEA_CONTRACT.address) {
|
132
|
-
chainId = LINEA_CONTRACT.chainId;
|
133
|
-
}
|
134
|
-
const signer = options.signer || (await extractMetaMaskSigner());
|
135
|
-
const currentChainId = await signer.getChainId();
|
136
|
-
if (chainId && chainId !== currentChainId) {
|
137
|
-
throw Error(`Failed to start RLN contract, chain ID of contract is different from current one: contract-${chainId}, current network-${currentChainId}`);
|
138
|
-
}
|
139
|
-
return {
|
140
|
-
signer,
|
141
|
-
address
|
142
|
-
};
|
143
55
|
}
|
144
|
-
|
145
|
-
|
146
|
-
|
147
|
-
}
|
148
|
-
if ("identity" in credentials) {
|
149
|
-
return { credentials };
|
150
|
-
}
|
151
|
-
const keystore = Keystore.fromString(credentials.keystore);
|
152
|
-
if (!keystore) {
|
153
|
-
return {};
|
154
|
-
}
|
155
|
-
const decryptedCredentials = await keystore.readCredential(credentials.id, credentials.password);
|
156
|
-
return {
|
157
|
-
keystore,
|
158
|
-
credentials: decryptedCredentials
|
159
|
-
};
|
160
|
-
}
|
161
|
-
async registerMembership(options) {
|
162
|
-
if (!this.contract) {
|
163
|
-
throw Error("RLN Contract is not initialized.");
|
164
|
-
}
|
165
|
-
let identity = "identity" in options && options.identity;
|
166
|
-
if ("signature" in options) {
|
167
|
-
identity = this.zerokit.generateSeededIdentityCredential(options.signature);
|
168
|
-
}
|
169
|
-
if (!identity) {
|
170
|
-
throw Error("Missing signature or identity to register membership.");
|
171
|
-
}
|
172
|
-
return this.contract.registerWithIdentity(identity);
|
173
|
-
}
|
174
|
-
/**
|
175
|
-
* Changes credentials in use by relying on provided Keystore earlier in rln.start
|
176
|
-
* @param id: string, hash of credentials to select from Keystore
|
177
|
-
* @param password: string or bytes to use to decrypt credentials from Keystore
|
178
|
-
*/
|
179
|
-
async useCredentials(id, password) {
|
180
|
-
this._credentials = await this.keystore?.readCredential(id, password);
|
56
|
+
constructor(zerokit) {
|
57
|
+
super(zerokit);
|
58
|
+
this.zerokit = zerokit;
|
181
59
|
}
|
182
60
|
async createEncoder(options) {
|
183
61
|
const { credentials: decryptedCredentials } = await RLNInstance.decryptCredentialsIfNeeded(options.credentials);
|
184
|
-
const credentials = decryptedCredentials || this.
|
62
|
+
const credentials = decryptedCredentials || this.credentials;
|
185
63
|
if (!credentials) {
|
186
64
|
throw Error("Failed to create Encoder: missing RLN credentials. Use createRLNEncoder directly.");
|
187
65
|
}
|
@@ -193,28 +71,40 @@ class RLNInstance {
|
|
193
71
|
credential: credentials.identity
|
194
72
|
});
|
195
73
|
}
|
196
|
-
async verifyCredentialsAgainstContract(credentials) {
|
197
|
-
if (!this._contract) {
|
198
|
-
throw Error("Failed to verify chain coordinates: no contract initialized.");
|
199
|
-
}
|
200
|
-
const registryAddress = credentials.membership.address;
|
201
|
-
const currentRegistryAddress = this._contract.address;
|
202
|
-
if (registryAddress !== currentRegistryAddress) {
|
203
|
-
throw Error(`Failed to verify chain coordinates: credentials contract address=${registryAddress} is not equal to registryContract address=${currentRegistryAddress}`);
|
204
|
-
}
|
205
|
-
const chainId = credentials.membership.chainId;
|
206
|
-
const network = await this._contract.provider.getNetwork();
|
207
|
-
const currentChainId = network.chainId;
|
208
|
-
if (chainId !== currentChainId) {
|
209
|
-
throw Error(`Failed to verify chain coordinates: credentials chainID=${chainId} is not equal to registryContract chainID=${currentChainId}`);
|
210
|
-
}
|
211
|
-
}
|
212
74
|
createDecoder(contentTopic) {
|
213
75
|
return createRLNDecoder({
|
214
76
|
rlnInstance: this,
|
215
77
|
decoder: createDecoder(contentTopic)
|
216
78
|
});
|
217
79
|
}
|
80
|
+
static async loadWitnessCalculator() {
|
81
|
+
try {
|
82
|
+
const url = new URL("./resources/rln.wasm", import.meta.url);
|
83
|
+
const response = await fetch(url);
|
84
|
+
if (!response.ok) {
|
85
|
+
throw new Error(`Failed to fetch witness calculator: ${response.status} ${response.statusText}`);
|
86
|
+
}
|
87
|
+
return await builder(new Uint8Array(await response.arrayBuffer()), false);
|
88
|
+
}
|
89
|
+
catch (error) {
|
90
|
+
log.error("Error loading witness calculator:", error);
|
91
|
+
throw new Error(`Failed to load witness calculator: ${error instanceof Error ? error.message : String(error)}`);
|
92
|
+
}
|
93
|
+
}
|
94
|
+
static async loadZkey() {
|
95
|
+
try {
|
96
|
+
const url = new URL("./resources/rln_final.zkey", import.meta.url);
|
97
|
+
const response = await fetch(url);
|
98
|
+
if (!response.ok) {
|
99
|
+
throw new Error(`Failed to fetch zkey: ${response.status} ${response.statusText}`);
|
100
|
+
}
|
101
|
+
return new Uint8Array(await response.arrayBuffer());
|
102
|
+
}
|
103
|
+
catch (error) {
|
104
|
+
log.error("Error loading zkey:", error);
|
105
|
+
throw new Error(`Failed to load zkey: ${error instanceof Error ? error.message : String(error)}`);
|
106
|
+
}
|
107
|
+
}
|
218
108
|
}
|
219
109
|
|
220
|
-
export { RLNInstance
|
110
|
+
export { RLNInstance };
|
@@ -8,11 +8,11 @@ import { epochIntToBytes, dateToEpoch } from './utils/epoch.js';
|
|
8
8
|
class Zerokit {
|
9
9
|
zkRLN;
|
10
10
|
witnessCalculator;
|
11
|
-
|
12
|
-
constructor(zkRLN, witnessCalculator,
|
11
|
+
_rateLimit;
|
12
|
+
constructor(zkRLN, witnessCalculator, _rateLimit = DEFAULT_RATE_LIMIT) {
|
13
13
|
this.zkRLN = zkRLN;
|
14
14
|
this.witnessCalculator = witnessCalculator;
|
15
|
-
this.
|
15
|
+
this._rateLimit = _rateLimit;
|
16
16
|
}
|
17
17
|
get getZkRLN() {
|
18
18
|
return this.zkRLN;
|
@@ -20,8 +20,8 @@ class Zerokit {
|
|
20
20
|
get getWitnessCalculator() {
|
21
21
|
return this.witnessCalculator;
|
22
22
|
}
|
23
|
-
get
|
24
|
-
return this.
|
23
|
+
get rateLimit() {
|
24
|
+
return this._rateLimit;
|
25
25
|
}
|
26
26
|
generateIdentityCredentials() {
|
27
27
|
const memKeys = generateExtendedMembershipKey(this.zkRLN); // TODO: rename this function in zerokit rln-wasm
|
@@ -0,0 +1,43 @@
|
|
1
|
+
function number(n) {
|
2
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
3
|
+
throw new Error(`Wrong positive integer: ${n}`);
|
4
|
+
}
|
5
|
+
function bool(b) {
|
6
|
+
if (typeof b !== 'boolean')
|
7
|
+
throw new Error(`Expected boolean, not ${b}`);
|
8
|
+
}
|
9
|
+
function bytes(b, ...lengths) {
|
10
|
+
if (!(b instanceof Uint8Array))
|
11
|
+
throw new TypeError('Expected Uint8Array');
|
12
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
13
|
+
throw new TypeError(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);
|
14
|
+
}
|
15
|
+
function hash(hash) {
|
16
|
+
if (typeof hash !== 'function' || typeof hash.create !== 'function')
|
17
|
+
throw new Error('Hash should be wrapped by utils.wrapConstructor');
|
18
|
+
number(hash.outputLen);
|
19
|
+
number(hash.blockLen);
|
20
|
+
}
|
21
|
+
function exists(instance, checkFinished = true) {
|
22
|
+
if (instance.destroyed)
|
23
|
+
throw new Error('Hash instance has been destroyed');
|
24
|
+
if (checkFinished && instance.finished)
|
25
|
+
throw new Error('Hash#digest() has already been called');
|
26
|
+
}
|
27
|
+
function output(out, instance) {
|
28
|
+
bytes(out);
|
29
|
+
const min = instance.outputLen;
|
30
|
+
if (out.length < min) {
|
31
|
+
throw new Error(`digestInto() expects output buffer of length at least ${min}`);
|
32
|
+
}
|
33
|
+
}
|
34
|
+
const assert = {
|
35
|
+
number,
|
36
|
+
bool,
|
37
|
+
bytes,
|
38
|
+
hash,
|
39
|
+
exists,
|
40
|
+
output,
|
41
|
+
};
|
42
|
+
|
43
|
+
export { bool, bytes, assert as default, exists, hash, number, output };
|
@@ -0,0 +1,116 @@
|
|
1
|
+
import assert from './_assert.js';
|
2
|
+
import { Hash, createView, toBytes } from './utils.js';
|
3
|
+
|
4
|
+
// Polyfill for Safari 14
|
5
|
+
function setBigUint64(view, byteOffset, value, isLE) {
|
6
|
+
if (typeof view.setBigUint64 === 'function')
|
7
|
+
return view.setBigUint64(byteOffset, value, isLE);
|
8
|
+
const _32n = BigInt(32);
|
9
|
+
const _u32_max = BigInt(0xffffffff);
|
10
|
+
const wh = Number((value >> _32n) & _u32_max);
|
11
|
+
const wl = Number(value & _u32_max);
|
12
|
+
const h = isLE ? 4 : 0;
|
13
|
+
const l = isLE ? 0 : 4;
|
14
|
+
view.setUint32(byteOffset + h, wh, isLE);
|
15
|
+
view.setUint32(byteOffset + l, wl, isLE);
|
16
|
+
}
|
17
|
+
// Base SHA2 class (RFC 6234)
|
18
|
+
class SHA2 extends Hash {
|
19
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
20
|
+
super();
|
21
|
+
this.blockLen = blockLen;
|
22
|
+
this.outputLen = outputLen;
|
23
|
+
this.padOffset = padOffset;
|
24
|
+
this.isLE = isLE;
|
25
|
+
this.finished = false;
|
26
|
+
this.length = 0;
|
27
|
+
this.pos = 0;
|
28
|
+
this.destroyed = false;
|
29
|
+
this.buffer = new Uint8Array(blockLen);
|
30
|
+
this.view = createView(this.buffer);
|
31
|
+
}
|
32
|
+
update(data) {
|
33
|
+
assert.exists(this);
|
34
|
+
const { view, buffer, blockLen } = this;
|
35
|
+
data = toBytes(data);
|
36
|
+
const len = data.length;
|
37
|
+
for (let pos = 0; pos < len;) {
|
38
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
39
|
+
// Fast path: we have at least one block in input, cast it to view and process
|
40
|
+
if (take === blockLen) {
|
41
|
+
const dataView = createView(data);
|
42
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
43
|
+
this.process(dataView, pos);
|
44
|
+
continue;
|
45
|
+
}
|
46
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
47
|
+
this.pos += take;
|
48
|
+
pos += take;
|
49
|
+
if (this.pos === blockLen) {
|
50
|
+
this.process(view, 0);
|
51
|
+
this.pos = 0;
|
52
|
+
}
|
53
|
+
}
|
54
|
+
this.length += data.length;
|
55
|
+
this.roundClean();
|
56
|
+
return this;
|
57
|
+
}
|
58
|
+
digestInto(out) {
|
59
|
+
assert.exists(this);
|
60
|
+
assert.output(out, this);
|
61
|
+
this.finished = true;
|
62
|
+
// Padding
|
63
|
+
// We can avoid allocation of buffer for padding completely if it
|
64
|
+
// was previously not allocated here. But it won't change performance.
|
65
|
+
const { buffer, view, blockLen, isLE } = this;
|
66
|
+
let { pos } = this;
|
67
|
+
// append the bit '1' to the message
|
68
|
+
buffer[pos++] = 0b10000000;
|
69
|
+
this.buffer.subarray(pos).fill(0);
|
70
|
+
// we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again
|
71
|
+
if (this.padOffset > blockLen - pos) {
|
72
|
+
this.process(view, 0);
|
73
|
+
pos = 0;
|
74
|
+
}
|
75
|
+
// Pad until full block byte with zeros
|
76
|
+
for (let i = pos; i < blockLen; i++)
|
77
|
+
buffer[i] = 0;
|
78
|
+
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
|
79
|
+
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
|
80
|
+
// So we just write lowest 64 bits of that value.
|
81
|
+
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
82
|
+
this.process(view, 0);
|
83
|
+
const oview = createView(out);
|
84
|
+
const len = this.outputLen;
|
85
|
+
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
|
86
|
+
if (len % 4)
|
87
|
+
throw new Error('_sha2: outputLen should be aligned to 32bit');
|
88
|
+
const outLen = len / 4;
|
89
|
+
const state = this.get();
|
90
|
+
if (outLen > state.length)
|
91
|
+
throw new Error('_sha2: outputLen bigger than state');
|
92
|
+
for (let i = 0; i < outLen; i++)
|
93
|
+
oview.setUint32(4 * i, state[i], isLE);
|
94
|
+
}
|
95
|
+
digest() {
|
96
|
+
const { buffer, outputLen } = this;
|
97
|
+
this.digestInto(buffer);
|
98
|
+
const res = buffer.slice(0, outputLen);
|
99
|
+
this.destroy();
|
100
|
+
return res;
|
101
|
+
}
|
102
|
+
_cloneInto(to) {
|
103
|
+
to || (to = new this.constructor());
|
104
|
+
to.set(...this.get());
|
105
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
106
|
+
to.length = length;
|
107
|
+
to.pos = pos;
|
108
|
+
to.finished = finished;
|
109
|
+
to.destroyed = destroyed;
|
110
|
+
if (length % blockLen)
|
111
|
+
to.buffer.set(buffer);
|
112
|
+
return to;
|
113
|
+
}
|
114
|
+
}
|
115
|
+
|
116
|
+
export { SHA2 };
|