@waku/rln 0.1.1-fa49e29 → 0.1.2-126bce3

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 (93) hide show
  1. package/README.md +26 -2
  2. package/bundle/assets/rln_wasm_bg-a503e304.wasm +0 -0
  3. package/bundle/index.js +69844 -44998
  4. package/dist/codec.d.ts +7 -4
  5. package/dist/codec.js +15 -5
  6. package/dist/codec.js.map +1 -1
  7. package/dist/{constants.js → contract/constants.js} +3 -3
  8. package/dist/contract/constants.js.map +1 -0
  9. package/dist/contract/index.d.ts +2 -0
  10. package/dist/contract/index.js +3 -0
  11. package/dist/contract/index.js.map +1 -0
  12. package/dist/{rln_contract.d.ts → contract/rln_contract.d.ts} +13 -11
  13. package/dist/{rln_contract.js → contract/rln_contract.js} +50 -33
  14. package/dist/contract/rln_contract.js.map +1 -0
  15. package/dist/create.d.ts +2 -0
  16. package/dist/create.js +8 -0
  17. package/dist/create.js.map +1 -0
  18. package/dist/identity.d.ts +9 -0
  19. package/dist/identity.js +24 -0
  20. package/dist/identity.js.map +1 -0
  21. package/dist/index.d.ts +8 -5
  22. package/dist/index.js +8 -12
  23. package/dist/index.js.map +1 -1
  24. package/dist/keystore/cipher.js +1 -1
  25. package/dist/keystore/cipher.js.map +1 -1
  26. package/dist/keystore/credential_validation_generated.js.map +1 -1
  27. package/dist/keystore/index.d.ts +2 -0
  28. package/dist/keystore/index.js.map +1 -1
  29. package/dist/keystore/keystore.d.ts +11 -11
  30. package/dist/keystore/keystore.js +33 -21
  31. package/dist/keystore/keystore.js.map +1 -1
  32. package/dist/keystore/keystore_validation_generated.js.map +1 -1
  33. package/dist/keystore/schema_validator.js.map +1 -1
  34. package/dist/keystore/types.d.ts +25 -5
  35. package/dist/message.d.ts +1 -1
  36. package/dist/message.js +7 -4
  37. package/dist/message.js.map +1 -1
  38. package/dist/proof.d.ts +21 -0
  39. package/dist/proof.js +49 -0
  40. package/dist/proof.js.map +1 -0
  41. package/dist/resources/verification_key.d.ts +9 -9
  42. package/dist/resources/witness_calculator.js.map +1 -0
  43. package/dist/rln.d.ts +55 -46
  44. package/dist/rln.js +135 -174
  45. package/dist/rln.js.map +1 -1
  46. package/dist/root_tracker.js +5 -2
  47. package/dist/root_tracker.js.map +1 -1
  48. package/dist/utils/bytes.d.ts +20 -0
  49. package/dist/utils/bytes.js +64 -0
  50. package/dist/utils/bytes.js.map +1 -0
  51. package/dist/utils/epoch.js.map +1 -0
  52. package/dist/utils/hash.d.ts +2 -0
  53. package/dist/utils/hash.js +13 -0
  54. package/dist/utils/hash.js.map +1 -0
  55. package/dist/utils/index.d.ts +4 -0
  56. package/dist/utils/index.js +5 -0
  57. package/dist/utils/index.js.map +1 -0
  58. package/dist/utils/metamask.d.ts +2 -0
  59. package/dist/utils/metamask.js +12 -0
  60. package/dist/utils/metamask.js.map +1 -0
  61. package/dist/zerokit.d.ts +19 -0
  62. package/dist/zerokit.js +105 -0
  63. package/dist/zerokit.js.map +1 -0
  64. package/package.json +22 -27
  65. package/src/codec.ts +18 -9
  66. package/src/create.ts +9 -0
  67. package/src/identity.ts +27 -0
  68. package/src/index.ts +10 -19
  69. package/src/message.ts +5 -5
  70. package/src/proof.ts +67 -0
  71. package/src/rln.ts +219 -260
  72. package/src/root_tracker.ts +4 -1
  73. package/src/zerokit.ts +181 -0
  74. package/bundle/assets/rln_wasm_bg-6f96f821.wasm +0 -0
  75. package/dist/.tsbuildinfo +0 -1
  76. package/dist/byte_utils.d.ts +0 -7
  77. package/dist/byte_utils.js +0 -33
  78. package/dist/byte_utils.js.map +0 -1
  79. package/dist/constants.js.map +0 -1
  80. package/dist/epoch.js.map +0 -1
  81. package/dist/rln_contract.js.map +0 -1
  82. package/dist/witness_calculator.js.map +0 -1
  83. package/src/byte_utils.ts +0 -49
  84. package/src/constants.ts +0 -68
  85. package/src/epoch.ts +0 -30
  86. package/src/rln_contract.ts +0 -346
  87. package/src/witness_calculator.d.ts +0 -8
  88. package/src/witness_calculator.js +0 -335
  89. /package/dist/{constants.d.ts → contract/constants.d.ts} +0 -0
  90. /package/dist/{witness_calculator.d.ts → resources/witness_calculator.d.ts} +0 -0
  91. /package/dist/{witness_calculator.js → resources/witness_calculator.js} +0 -0
  92. /package/dist/{epoch.d.ts → utils/epoch.d.ts} +0 -0
  93. /package/dist/{epoch.js → utils/epoch.js} +0 -0
package/src/epoch.ts DELETED
@@ -1,30 +0,0 @@
1
- import debug from "debug";
2
-
3
- const DefaultEpochUnitSeconds = 10; // the rln-relay epoch length in seconds
4
-
5
- const log = debug("waku:rln:epoch");
6
-
7
- export function dateToEpoch(
8
- timestamp: Date,
9
- epochUnitSeconds: number = DefaultEpochUnitSeconds
10
- ): number {
11
- const time = timestamp.getTime();
12
- const epoch = Math.floor(time / 1000 / epochUnitSeconds);
13
- log("generated epoch", epoch);
14
- return epoch;
15
- }
16
-
17
- export function epochIntToBytes(epoch: number): Uint8Array {
18
- const bytes = new Uint8Array(32);
19
- const db = new DataView(bytes.buffer);
20
- db.setUint32(0, epoch, true);
21
- log("encoded epoch", epoch, bytes);
22
- return bytes;
23
- }
24
-
25
- export function epochBytesToInt(bytes: Uint8Array): number {
26
- const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
27
- const epoch = dv.getUint32(0, true);
28
- log("decoded epoch", epoch, bytes);
29
- return epoch;
30
- }
@@ -1,346 +0,0 @@
1
- import { ethers } from "ethers";
2
-
3
- import { RLN_REGISTRY_ABI, RLN_STORAGE_ABI } from "./constants.js";
4
- import { IdentityCredential, RLNInstance } from "./rln.js";
5
- import { MerkleRootTracker } from "./root_tracker.js";
6
-
7
- type Member = {
8
- idCommitment: string;
9
- index: ethers.BigNumber;
10
- };
11
-
12
- type Provider = ethers.Signer | ethers.providers.Provider;
13
-
14
- type RLNContractOptions = {
15
- provider: Provider;
16
- registryAddress: string;
17
- };
18
-
19
- type RLNStorageOptions = {
20
- storageIndex?: number;
21
- };
22
-
23
- type RLNContractInitOptions = RLNContractOptions & RLNStorageOptions;
24
-
25
- type FetchMembersOptions = {
26
- fromBlock?: number;
27
- fetchRange?: number;
28
- fetchChunks?: number;
29
- };
30
-
31
- export class RLNContract {
32
- private registryContract: ethers.Contract;
33
- private merkleRootTracker: MerkleRootTracker;
34
-
35
- private deployBlock: undefined | number;
36
- private storageIndex: undefined | number;
37
- private storageContract: undefined | ethers.Contract;
38
- private _membersFilter: undefined | ethers.EventFilter;
39
-
40
- private _members: Map<number, Member> = new Map();
41
-
42
- public static async init(
43
- rlnInstance: RLNInstance,
44
- options: RLNContractInitOptions
45
- ): Promise<RLNContract> {
46
- const rlnContract = new RLNContract(rlnInstance, options);
47
-
48
- await rlnContract.initStorageContract(options.provider);
49
- await rlnContract.fetchMembers(rlnInstance);
50
- rlnContract.subscribeToMembers(rlnInstance);
51
-
52
- return rlnContract;
53
- }
54
-
55
- constructor(
56
- rlnInstance: RLNInstance,
57
- { registryAddress, provider }: RLNContractOptions
58
- ) {
59
- const initialRoot = rlnInstance.getMerkleRoot();
60
-
61
- this.registryContract = new ethers.Contract(
62
- registryAddress,
63
- RLN_REGISTRY_ABI,
64
- provider
65
- );
66
- this.merkleRootTracker = new MerkleRootTracker(5, initialRoot);
67
- }
68
-
69
- private async initStorageContract(
70
- provider: Provider,
71
- options: RLNStorageOptions = {}
72
- ): Promise<void> {
73
- const storageIndex = options?.storageIndex
74
- ? options.storageIndex
75
- : await this.registryContract.usingStorageIndex();
76
- const storageAddress = await this.registryContract.storages(storageIndex);
77
-
78
- if (!storageAddress || storageAddress === ethers.constants.AddressZero) {
79
- throw Error("No RLN Storage initialized on registry contract.");
80
- }
81
-
82
- this.storageIndex = storageIndex;
83
- this.storageContract = new ethers.Contract(
84
- storageAddress,
85
- RLN_STORAGE_ABI,
86
- provider
87
- );
88
- this._membersFilter = this.storageContract.filters.MemberRegistered();
89
-
90
- this.deployBlock = await this.storageContract.deployedBlockNumber();
91
- }
92
-
93
- public get contract(): ethers.Contract {
94
- if (!this.storageContract) {
95
- throw Error("Storage contract was not initialized");
96
- }
97
- return this.storageContract as ethers.Contract;
98
- }
99
-
100
- public get members(): Member[] {
101
- const sortedMembers = Array.from(this._members.values()).sort(
102
- (left, right) => left.index.toNumber() - right.index.toNumber()
103
- );
104
- return sortedMembers;
105
- }
106
-
107
- private get membersFilter(): ethers.EventFilter {
108
- if (!this._membersFilter) {
109
- throw Error("Members filter was not initialized.");
110
- }
111
- return this._membersFilter as ethers.EventFilter;
112
- }
113
-
114
- public async fetchMembers(
115
- rlnInstance: RLNInstance,
116
- options: FetchMembersOptions = {}
117
- ): Promise<void> {
118
- const registeredMemberEvents = await queryFilter(this.contract, {
119
- fromBlock: this.deployBlock,
120
- ...options,
121
- membersFilter: this.membersFilter,
122
- });
123
- this.processEvents(rlnInstance, registeredMemberEvents);
124
- }
125
-
126
- public processEvents(rlnInstance: RLNInstance, events: ethers.Event[]): void {
127
- const toRemoveTable = new Map<number, number[]>();
128
- const toInsertTable = new Map<number, ethers.Event[]>();
129
-
130
- events.forEach((evt) => {
131
- if (!evt.args) {
132
- return;
133
- }
134
-
135
- if (evt.removed) {
136
- const index: ethers.BigNumber = evt.args.index;
137
- const toRemoveVal = toRemoveTable.get(evt.blockNumber);
138
- if (toRemoveVal != undefined) {
139
- toRemoveVal.push(index.toNumber());
140
- toRemoveTable.set(evt.blockNumber, toRemoveVal);
141
- } else {
142
- toRemoveTable.set(evt.blockNumber, [index.toNumber()]);
143
- }
144
- } else {
145
- let eventsPerBlock = toInsertTable.get(evt.blockNumber);
146
- if (eventsPerBlock == undefined) {
147
- eventsPerBlock = [];
148
- }
149
-
150
- eventsPerBlock.push(evt);
151
- toInsertTable.set(evt.blockNumber, eventsPerBlock);
152
- }
153
-
154
- this.removeMembers(rlnInstance, toRemoveTable);
155
- this.insertMembers(rlnInstance, toInsertTable);
156
- });
157
- }
158
-
159
- private insertMembers(
160
- rlnInstance: RLNInstance,
161
- toInsert: Map<number, ethers.Event[]>
162
- ): void {
163
- toInsert.forEach((events: ethers.Event[], blockNumber: number) => {
164
- events.forEach((evt) => {
165
- const _idCommitment = evt?.args?.idCommitment;
166
- const index: ethers.BigNumber = evt?.args?.index;
167
-
168
- if (!_idCommitment || !index) {
169
- return;
170
- }
171
-
172
- const idCommitment = ethers.utils.zeroPad(
173
- ethers.utils.arrayify(_idCommitment),
174
- 32
175
- );
176
- rlnInstance.insertMember(idCommitment);
177
- this._members.set(index.toNumber(), {
178
- index,
179
- idCommitment:
180
- _idCommitment?._hex || ethers.utils.hexlify(idCommitment),
181
- });
182
- });
183
-
184
- const currentRoot = rlnInstance.getMerkleRoot();
185
- this.merkleRootTracker.pushRoot(blockNumber, currentRoot);
186
- });
187
- }
188
-
189
- private removeMembers(
190
- rlnInstance: RLNInstance,
191
- toRemove: Map<number, number[]>
192
- ): void {
193
- const removeDescending = new Map([...toRemove].sort().reverse());
194
- removeDescending.forEach((indexes: number[], blockNumber: number) => {
195
- indexes.forEach((index) => {
196
- if (this._members.has(index)) {
197
- this._members.delete(index);
198
- }
199
- rlnInstance.deleteMember(index);
200
- });
201
-
202
- this.merkleRootTracker.backFill(blockNumber);
203
- });
204
- }
205
-
206
- public subscribeToMembers(rlnInstance: RLNInstance): void {
207
- this.contract.on(this.membersFilter, (_pubkey, _index, event) =>
208
- this.processEvents(rlnInstance, [event])
209
- );
210
- }
211
-
212
- public async registerWithSignature(
213
- rlnInstance: RLNInstance,
214
- signature: string
215
- ): Promise<Member | undefined> {
216
- const identityCredential =
217
- await rlnInstance.generateSeededIdentityCredential(signature);
218
-
219
- return this.registerWithKey(identityCredential);
220
- }
221
-
222
- public async registerWithKey(
223
- credential: IdentityCredential
224
- ): Promise<Member | undefined> {
225
- if (this.storageIndex === undefined) {
226
- throw Error(
227
- "Cannot register credential, no storage contract index found."
228
- );
229
- }
230
- const txRegisterResponse: ethers.ContractTransaction =
231
- await this.registryContract["register(uint16,uint256)"](
232
- this.storageIndex,
233
- credential.IDCommitmentBigInt,
234
- { gasLimit: 100000 }
235
- );
236
- const txRegisterReceipt = await txRegisterResponse.wait();
237
-
238
- // assumption: register(uint16,uint256) emits one event
239
- const memberRegistered = txRegisterReceipt?.events?.[0];
240
-
241
- if (!memberRegistered) {
242
- return undefined;
243
- }
244
-
245
- const decodedData = this.contract.interface.decodeEventLog(
246
- "MemberRegistered",
247
- memberRegistered.data
248
- );
249
-
250
- return {
251
- idCommitment: decodedData.idCommitment,
252
- index: decodedData.index,
253
- };
254
- }
255
-
256
- public roots(): Uint8Array[] {
257
- return this.merkleRootTracker.roots();
258
- }
259
- }
260
-
261
- type CustomQueryOptions = FetchMembersOptions & {
262
- membersFilter: ethers.EventFilter;
263
- };
264
-
265
- // these value should be tested on other networks
266
- const FETCH_CHUNK = 5;
267
- const BLOCK_RANGE = 3000;
268
-
269
- async function queryFilter(
270
- contract: ethers.Contract,
271
- options: CustomQueryOptions
272
- ): Promise<ethers.Event[]> {
273
- const {
274
- fromBlock,
275
- membersFilter,
276
- fetchRange = BLOCK_RANGE,
277
- fetchChunks = FETCH_CHUNK,
278
- } = options;
279
-
280
- if (!fromBlock) {
281
- return contract.queryFilter(membersFilter);
282
- }
283
-
284
- if (!contract.signer.provider) {
285
- throw Error("No provider found on the contract's signer.");
286
- }
287
-
288
- const toBlock = await contract.signer.provider.getBlockNumber();
289
-
290
- if (toBlock - fromBlock < fetchRange) {
291
- return contract.queryFilter(membersFilter);
292
- }
293
-
294
- const events: ethers.Event[][] = [];
295
- const chunks = splitToChunks(fromBlock, toBlock, fetchRange);
296
-
297
- for (const portion of takeN<[number, number]>(chunks, fetchChunks)) {
298
- const promises = portion.map(([left, right]) =>
299
- ignoreErrors(contract.queryFilter(membersFilter, left, right), [])
300
- );
301
- const fetchedEvents = await Promise.all(promises);
302
- events.push(fetchedEvents.flatMap((v) => v));
303
- }
304
-
305
- return events.flatMap((v) => v);
306
- }
307
-
308
- function splitToChunks(
309
- from: number,
310
- to: number,
311
- step: number
312
- ): Array<[number, number]> {
313
- const chunks = [];
314
-
315
- let left = from;
316
- while (left < to) {
317
- const right = left + step < to ? left + step : to;
318
-
319
- chunks.push([left, right] as [number, number]);
320
-
321
- left = right;
322
- }
323
-
324
- return chunks;
325
- }
326
-
327
- function* takeN<T>(array: T[], size: number): Iterable<T[]> {
328
- let start = 0;
329
- let skip = size;
330
-
331
- while (skip < array.length) {
332
- const portion = array.slice(start, skip);
333
-
334
- yield portion;
335
-
336
- start = skip;
337
- skip += size;
338
- }
339
- }
340
-
341
- function ignoreErrors<T>(promise: Promise<T>, defaultValue: T): Promise<T> {
342
- return promise.catch((err) => {
343
- console.error(`Ignoring an error during query: ${err?.message}`);
344
- return defaultValue;
345
- });
346
- }
@@ -1,8 +0,0 @@
1
- export async function builder(
2
- code: Uint8Array,
3
- sanityCheck: bool
4
- ): Promise<WitnessCalculator>;
5
-
6
- export class WitnessCalculator {
7
- calculateWitness(input, sanityCheck): Array<bigint>;
8
- }
@@ -1,335 +0,0 @@
1
- // File generated with https://github.com/iden3/circom
2
- // following the instructions from:
3
- // https://github.com/vacp2p/zerokit/tree/master/rln#compiling-circuits
4
-
5
- export async function builder(code, options) {
6
-
7
- options = options || {};
8
-
9
- let wasmModule;
10
- try {
11
- wasmModule = await WebAssembly.compile(code);
12
- } catch (err) {
13
- console.log(err);
14
- console.log("\nTry to run circom --c in order to generate c++ code instead\n");
15
- throw new Error(err);
16
- }
17
-
18
- let wc;
19
-
20
- let errStr = "";
21
- let msgStr = "";
22
-
23
- const instance = await WebAssembly.instantiate(wasmModule, {
24
- runtime: {
25
- exceptionHandler : function(code) {
26
- let err;
27
- if (code == 1) {
28
- err = "Signal not found.\n";
29
- } else if (code == 2) {
30
- err = "Too many signals set.\n";
31
- } else if (code == 3) {
32
- err = "Signal already set.\n";
33
- } else if (code == 4) {
34
- err = "Assert Failed.\n";
35
- } else if (code == 5) {
36
- err = "Not enough memory.\n";
37
- } else if (code == 6) {
38
- err = "Input signal array access exceeds the size.\n";
39
- } else {
40
- err = "Unknown error.\n";
41
- }
42
- throw new Error(err + errStr);
43
- },
44
- printErrorMessage : function() {
45
- errStr += getMessage() + "\n";
46
- // console.error(getMessage());
47
- },
48
- writeBufferMessage : function() {
49
- const msg = getMessage();
50
- // Any calls to `log()` will always end with a `\n`, so that's when we print and reset
51
- if (msg === "\n") {
52
- console.log(msgStr);
53
- msgStr = "";
54
- } else {
55
- // If we've buffered other content, put a space in between the items
56
- if (msgStr !== "") {
57
- msgStr += " "
58
- }
59
- // Then append the message to the message we are creating
60
- msgStr += msg;
61
- }
62
- },
63
- showSharedRWMemory : function() {
64
- printSharedRWMemory ();
65
- }
66
-
67
- }
68
- });
69
-
70
- const sanityCheck =
71
- options
72
- // options &&
73
- // (
74
- // options.sanityCheck ||
75
- // options.logGetSignal ||
76
- // options.logSetSignal ||
77
- // options.logStartComponent ||
78
- // options.logFinishComponent
79
- // );
80
-
81
-
82
- wc = new WitnessCalculator(instance, sanityCheck);
83
- return wc;
84
-
85
- function getMessage() {
86
- var message = "";
87
- var c = instance.exports.getMessageChar();
88
- while ( c != 0 ) {
89
- message += String.fromCharCode(c);
90
- c = instance.exports.getMessageChar();
91
- }
92
- return message;
93
- }
94
-
95
- function printSharedRWMemory () {
96
- const shared_rw_memory_size = instance.exports.getFieldNumLen32();
97
- const arr = new Uint32Array(shared_rw_memory_size);
98
- for (let j=0; j<shared_rw_memory_size; j++) {
99
- arr[shared_rw_memory_size-1-j] = instance.exports.readSharedRWMemory(j);
100
- }
101
-
102
- // If we've buffered other content, put a space in between the items
103
- if (msgStr !== "") {
104
- msgStr += " "
105
- }
106
- // Then append the value to the message we are creating
107
- msgStr += (fromArray32(arr).toString());
108
- }
109
-
110
- };
111
-
112
- class WitnessCalculator {
113
- constructor(instance, sanityCheck) {
114
- this.instance = instance;
115
-
116
- this.version = this.instance.exports.getVersion();
117
- this.n32 = this.instance.exports.getFieldNumLen32();
118
-
119
- this.instance.exports.getRawPrime();
120
- const arr = new Uint32Array(this.n32);
121
- for (let i=0; i<this.n32; i++) {
122
- arr[this.n32-1-i] = this.instance.exports.readSharedRWMemory(i);
123
- }
124
- this.prime = fromArray32(arr);
125
-
126
- this.witnessSize = this.instance.exports.getWitnessSize();
127
-
128
- this.sanityCheck = sanityCheck;
129
- }
130
-
131
- circom_version() {
132
- return this.instance.exports.getVersion();
133
- }
134
-
135
- async _doCalculateWitness(input, sanityCheck) {
136
- //input is assumed to be a map from signals to arrays of bigints
137
- this.instance.exports.init((this.sanityCheck || sanityCheck) ? 1 : 0);
138
- const keys = Object.keys(input);
139
- var input_counter = 0;
140
- keys.forEach( (k) => {
141
- const h = fnvHash(k);
142
- const hMSB = parseInt(h.slice(0,8), 16);
143
- const hLSB = parseInt(h.slice(8,16), 16);
144
- const fArr = flatArray(input[k]);
145
- let signalSize = this.instance.exports.getInputSignalSize(hMSB, hLSB);
146
- if (signalSize < 0){
147
- throw new Error(`Signal ${k} not found\n`);
148
- }
149
- if (fArr.length < signalSize) {
150
- throw new Error(`Not enough values for input signal ${k}\n`);
151
- }
152
- if (fArr.length > signalSize) {
153
- throw new Error(`Too many values for input signal ${k}\n`);
154
- }
155
- for (let i=0; i<fArr.length; i++) {
156
- const arrFr = toArray32(BigInt(fArr[i])%this.prime,this.n32)
157
- for (let j=0; j<this.n32; j++) {
158
- this.instance.exports.writeSharedRWMemory(j,arrFr[this.n32-1-j]);
159
- }
160
- try {
161
- this.instance.exports.setInputSignal(hMSB, hLSB,i);
162
- input_counter++;
163
- } catch (err) {
164
- // console.log(`After adding signal ${i} of ${k}`)
165
- throw new Error(err);
166
- }
167
- }
168
-
169
- });
170
- if (input_counter < this.instance.exports.getInputSize()) {
171
- throw new Error(`Not all inputs have been set. Only ${input_counter} out of ${this.instance.exports.getInputSize()}`);
172
- }
173
- }
174
-
175
- async calculateWitness(input, sanityCheck) {
176
-
177
- const w = [];
178
-
179
- await this._doCalculateWitness(input, sanityCheck);
180
-
181
- for (let i=0; i<this.witnessSize; i++) {
182
- this.instance.exports.getWitness(i);
183
- const arr = new Uint32Array(this.n32);
184
- for (let j=0; j<this.n32; j++) {
185
- arr[this.n32-1-j] = this.instance.exports.readSharedRWMemory(j);
186
- }
187
- w.push(fromArray32(arr));
188
- }
189
-
190
- return w;
191
- }
192
-
193
-
194
- async calculateBinWitness(input, sanityCheck) {
195
-
196
- const buff32 = new Uint32Array(this.witnessSize*this.n32);
197
- const buff = new Uint8Array( buff32.buffer);
198
- await this._doCalculateWitness(input, sanityCheck);
199
-
200
- for (let i=0; i<this.witnessSize; i++) {
201
- this.instance.exports.getWitness(i);
202
- const pos = i*this.n32;
203
- for (let j=0; j<this.n32; j++) {
204
- buff32[pos+j] = this.instance.exports.readSharedRWMemory(j);
205
- }
206
- }
207
-
208
- return buff;
209
- }
210
-
211
-
212
- async calculateWTNSBin(input, sanityCheck) {
213
-
214
- const buff32 = new Uint32Array(this.witnessSize*this.n32+this.n32+11);
215
- const buff = new Uint8Array( buff32.buffer);
216
- await this._doCalculateWitness(input, sanityCheck);
217
-
218
- //"wtns"
219
- buff[0] = "w".charCodeAt(0)
220
- buff[1] = "t".charCodeAt(0)
221
- buff[2] = "n".charCodeAt(0)
222
- buff[3] = "s".charCodeAt(0)
223
-
224
- //version 2
225
- buff32[1] = 2;
226
-
227
- //number of sections: 2
228
- buff32[2] = 2;
229
-
230
- //id section 1
231
- buff32[3] = 1;
232
-
233
- const n8 = this.n32*4;
234
- //id section 1 length in 64bytes
235
- const idSection1length = 8 + n8;
236
- const idSection1lengthHex = idSection1length.toString(16);
237
- buff32[4] = parseInt(idSection1lengthHex.slice(0,8), 16);
238
- buff32[5] = parseInt(idSection1lengthHex.slice(8,16), 16);
239
-
240
- //this.n32
241
- buff32[6] = n8;
242
-
243
- //prime number
244
- this.instance.exports.getRawPrime();
245
-
246
- var pos = 7;
247
- for (let j=0; j<this.n32; j++) {
248
- buff32[pos+j] = this.instance.exports.readSharedRWMemory(j);
249
- }
250
- pos += this.n32;
251
-
252
- // witness size
253
- buff32[pos] = this.witnessSize;
254
- pos++;
255
-
256
- //id section 2
257
- buff32[pos] = 2;
258
- pos++;
259
-
260
- // section 2 length
261
- const idSection2length = n8*this.witnessSize;
262
- const idSection2lengthHex = idSection2length.toString(16);
263
- buff32[pos] = parseInt(idSection2lengthHex.slice(0,8), 16);
264
- buff32[pos+1] = parseInt(idSection2lengthHex.slice(8,16), 16);
265
-
266
- pos += 2;
267
- for (let i=0; i<this.witnessSize; i++) {
268
- this.instance.exports.getWitness(i);
269
- for (let j=0; j<this.n32; j++) {
270
- buff32[pos+j] = this.instance.exports.readSharedRWMemory(j);
271
- }
272
- pos += this.n32;
273
- }
274
-
275
- return buff;
276
- }
277
-
278
- }
279
-
280
-
281
- function toArray32(rem,size) {
282
- const res = []; //new Uint32Array(size); //has no unshift
283
- const radix = BigInt(0x100000000);
284
- while (rem) {
285
- res.unshift( Number(rem % radix));
286
- rem = rem / radix;
287
- }
288
- if (size) {
289
- var i = size - res.length;
290
- while (i>0) {
291
- res.unshift(0);
292
- i--;
293
- }
294
- }
295
- return res;
296
- }
297
-
298
- function fromArray32(arr) { //returns a BigInt
299
- var res = BigInt(0);
300
- const radix = BigInt(0x100000000);
301
- for (let i = 0; i<arr.length; i++) {
302
- res = res*radix + BigInt(arr[i]);
303
- }
304
- return res;
305
- }
306
-
307
- function flatArray(a) {
308
- var res = [];
309
- fillArray(res, a);
310
- return res;
311
-
312
- function fillArray(res, a) {
313
- if (Array.isArray(a)) {
314
- for (let i=0; i<a.length; i++) {
315
- fillArray(res, a[i]);
316
- }
317
- } else {
318
- res.push(a);
319
- }
320
- }
321
- }
322
-
323
- function fnvHash(str) {
324
- const uint64_max = BigInt(2) ** BigInt(64);
325
- let hash = BigInt("0xCBF29CE484222325");
326
- for (var i = 0; i < str.length; i++) {
327
- hash ^= BigInt(str[i].charCodeAt());
328
- hash *= BigInt(0x100000001B3);
329
- hash %= uint64_max;
330
- }
331
- let shash = hash.toString(16);
332
- let n = 16 - shash.length;
333
- shash = '0'.repeat(n).concat(shash);
334
- return shash;
335
- }