@aztec/foundation 0.23.0 → 0.26.1

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 (163) hide show
  1. package/dest/abi/abi.d.ts +1 -1
  2. package/dest/abi/abi.d.ts.map +1 -1
  3. package/dest/abi/event_selector.d.ts +45 -0
  4. package/dest/abi/event_selector.d.ts.map +1 -0
  5. package/dest/abi/event_selector.js +60 -0
  6. package/dest/abi/function_selector.d.ts +69 -0
  7. package/dest/abi/function_selector.d.ts.map +1 -0
  8. package/dest/abi/function_selector.js +86 -0
  9. package/dest/abi/index.d.ts +2 -1
  10. package/dest/abi/index.d.ts.map +1 -1
  11. package/dest/abi/index.js +3 -2
  12. package/dest/abi/selector.d.ts +4 -106
  13. package/dest/abi/selector.d.ts.map +1 -1
  14. package/dest/abi/selector.js +8 -143
  15. package/dest/abi/utils.js +3 -3
  16. package/dest/array/array.d.ts +8 -0
  17. package/dest/array/array.d.ts.map +1 -1
  18. package/dest/array/array.js +26 -1
  19. package/dest/aztec-address/index.d.ts +8 -1
  20. package/dest/aztec-address/index.d.ts.map +1 -1
  21. package/dest/aztec-address/index.js +16 -2
  22. package/dest/crypto/index.d.ts +1 -0
  23. package/dest/crypto/index.d.ts.map +1 -1
  24. package/dest/crypto/index.js +2 -1
  25. package/dest/crypto/pedersen/pedersen.wasm.d.ts +2 -1
  26. package/dest/crypto/pedersen/pedersen.wasm.d.ts.map +1 -1
  27. package/dest/crypto/pedersen/pedersen.wasm.js +7 -6
  28. package/dest/crypto/poseidon/index.d.ts +8 -0
  29. package/dest/crypto/poseidon/index.d.ts.map +1 -0
  30. package/dest/crypto/poseidon/index.js +12 -0
  31. package/dest/eth-address/index.d.ts +3 -0
  32. package/dest/eth-address/index.d.ts.map +1 -1
  33. package/dest/eth-address/index.js +5 -2
  34. package/dest/fields/fields.d.ts +19 -0
  35. package/dest/fields/fields.d.ts.map +1 -1
  36. package/dest/fields/fields.js +11 -4
  37. package/dest/json-rpc/client/json_rpc_client.js +2 -2
  38. package/dest/serialize/buffer_reader.d.ts +15 -0
  39. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  40. package/dest/serialize/buffer_reader.js +18 -1
  41. package/dest/serialize/serialize.d.ts +3 -5
  42. package/dest/serialize/serialize.d.ts.map +1 -1
  43. package/dest/serialize/serialize.js +17 -8
  44. package/package.json +2 -2
  45. package/src/abi/abi.ts +337 -0
  46. package/src/abi/buffer.ts +36 -0
  47. package/src/abi/decoder.ts +176 -0
  48. package/src/abi/encoder.ts +143 -0
  49. package/src/abi/event_selector.ts +73 -0
  50. package/src/abi/function_selector.ts +122 -0
  51. package/src/abi/index.ts +7 -0
  52. package/src/abi/selector.ts +63 -0
  53. package/src/abi/utils.ts +50 -0
  54. package/src/array/array.ts +119 -0
  55. package/src/array/index.ts +1 -0
  56. package/src/async-map/index.ts +18 -0
  57. package/src/aztec-address/index.ts +56 -0
  58. package/src/bigint-buffer/index.ts +87 -0
  59. package/src/collection/array.ts +64 -0
  60. package/src/collection/index.ts +1 -0
  61. package/src/committable/committable.ts +46 -0
  62. package/src/committable/index.ts +1 -0
  63. package/src/crypto/index.ts +17 -0
  64. package/src/crypto/keccak/index.ts +33 -0
  65. package/src/crypto/pedersen/index.ts +1 -0
  66. package/src/crypto/pedersen/pedersen.elliptic.ts +584 -0
  67. package/src/crypto/pedersen/pedersen.noble.ts +573 -0
  68. package/src/crypto/pedersen/pedersen.wasm.ts +46 -0
  69. package/src/crypto/poseidon/index.ts +17 -0
  70. package/src/crypto/random/index.ts +42 -0
  71. package/src/crypto/sha256/index.ts +3 -0
  72. package/src/errors/index.ts +6 -0
  73. package/src/eth-address/index.ts +239 -0
  74. package/src/fields/coordinate.ts +104 -0
  75. package/src/fields/fields.ts +338 -0
  76. package/src/fields/index.ts +3 -0
  77. package/src/fields/point.ts +145 -0
  78. package/src/fifo/bounded_serial_queue.ts +100 -0
  79. package/src/fifo/index.ts +4 -0
  80. package/src/fifo/memory_fifo.ts +118 -0
  81. package/src/fifo/semaphore.ts +33 -0
  82. package/src/fifo/serial_queue.ts +81 -0
  83. package/src/index.ts +29 -0
  84. package/src/json-rpc/README.md +55 -0
  85. package/src/json-rpc/class_converter.ts +213 -0
  86. package/src/json-rpc/client/index.ts +1 -0
  87. package/src/json-rpc/client/json_rpc_client.ts +147 -0
  88. package/src/json-rpc/convert.ts +163 -0
  89. package/src/json-rpc/fixtures/class_a.ts +15 -0
  90. package/src/json-rpc/fixtures/class_b.ts +15 -0
  91. package/src/json-rpc/fixtures/test_state.ts +59 -0
  92. package/src/json-rpc/index.ts +8 -0
  93. package/src/json-rpc/js_utils.ts +20 -0
  94. package/src/json-rpc/server/index.ts +2 -0
  95. package/src/json-rpc/server/json_proxy.ts +60 -0
  96. package/src/json-rpc/server/json_rpc_server.ts +269 -0
  97. package/src/log/console.ts +39 -0
  98. package/src/log/debug.ts +83 -0
  99. package/src/log/index.ts +5 -0
  100. package/src/log/log_fn.ts +5 -0
  101. package/src/log/log_history.ts +44 -0
  102. package/src/log/logger.ts +137 -0
  103. package/src/mutex/index.ts +83 -0
  104. package/src/mutex/mutex_database.ts +12 -0
  105. package/src/noir/index.ts +1 -0
  106. package/src/noir/noir_package_config.ts +54 -0
  107. package/src/retry/index.ts +99 -0
  108. package/src/running-promise/index.ts +60 -0
  109. package/src/serialize/buffer_reader.ts +309 -0
  110. package/src/serialize/field_reader.ts +143 -0
  111. package/src/serialize/free_funcs.ts +147 -0
  112. package/src/serialize/index.ts +5 -0
  113. package/src/serialize/serialize.ts +310 -0
  114. package/src/serialize/types.ts +40 -0
  115. package/src/sleep/index.ts +71 -0
  116. package/src/testing/index.ts +1 -0
  117. package/src/testing/test_data.ts +36 -0
  118. package/src/timer/elapsed.ts +23 -0
  119. package/src/timer/index.ts +3 -0
  120. package/src/timer/timeout.ts +64 -0
  121. package/src/timer/timer.ts +48 -0
  122. package/src/transport/browser/index.ts +4 -0
  123. package/src/transport/browser/message_port_socket.ts +48 -0
  124. package/src/transport/browser/shared_worker_connector.ts +21 -0
  125. package/src/transport/browser/shared_worker_listener.ts +53 -0
  126. package/src/transport/browser/worker_connector.ts +30 -0
  127. package/src/transport/browser/worker_listener.ts +54 -0
  128. package/src/transport/dispatch/create_dispatch_fn.ts +35 -0
  129. package/src/transport/dispatch/create_dispatch_proxy.ts +141 -0
  130. package/src/transport/dispatch/messages.ts +58 -0
  131. package/src/transport/index.ts +11 -0
  132. package/src/transport/interface/connector.ts +9 -0
  133. package/src/transport/interface/listener.ts +16 -0
  134. package/src/transport/interface/socket.ts +15 -0
  135. package/src/transport/interface/transferable.ts +125 -0
  136. package/src/transport/node/index.ts +2 -0
  137. package/src/transport/node/node_connector.ts +30 -0
  138. package/src/transport/node/node_connector_socket.ts +52 -0
  139. package/src/transport/node/node_listener.ts +34 -0
  140. package/src/transport/node/node_listener_socket.ts +48 -0
  141. package/src/transport/transport_client.ts +131 -0
  142. package/src/transport/transport_server.ts +108 -0
  143. package/src/trees/index.ts +54 -0
  144. package/src/types/index.ts +8 -0
  145. package/src/url/index.ts +73 -0
  146. package/src/wasm/README.md +6 -0
  147. package/src/wasm/empty_wasi_sdk.ts +166 -0
  148. package/src/wasm/fixtures/gcd.wasm +0 -0
  149. package/src/wasm/fixtures/gcd.wat +27 -0
  150. package/src/wasm/index.ts +1 -0
  151. package/src/wasm/wasm_module.ts +260 -0
  152. package/src/worker/browser/index.ts +2 -0
  153. package/src/worker/browser/start_web_module.ts +23 -0
  154. package/src/worker/browser/web_data_store.ts +38 -0
  155. package/src/worker/browser/web_worker.ts +24 -0
  156. package/src/worker/data_store.ts +19 -0
  157. package/src/worker/index.ts +2 -0
  158. package/src/worker/node/index.ts +2 -0
  159. package/src/worker/node/node_data_store.ts +27 -0
  160. package/src/worker/node/node_worker.ts +22 -0
  161. package/src/worker/node/start_node_module.ts +29 -0
  162. package/src/worker/wasm_worker.ts +7 -0
  163. package/src/worker/worker_pool.ts +73 -0
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A leaf of an indexed merkle tree.
3
+ */
4
+ export interface IndexedTreeLeaf {
5
+ /**
6
+ * Returns key of the leaf. It's used for indexing.
7
+ */
8
+ getKey(): bigint;
9
+ /**
10
+ * Serializes the leaf into a buffer.
11
+ */
12
+ toBuffer(): Buffer;
13
+ /**
14
+ * Returns true if the leaf is empty.
15
+ */
16
+ isEmpty(): boolean;
17
+ /**
18
+ * Updates the leaf with the data of another leaf.
19
+ * @param another - The leaf to update to.
20
+ * @returns The updated leaf.
21
+ */
22
+ updateTo(another: IndexedTreeLeaf): IndexedTreeLeaf;
23
+ }
24
+
25
+ /**
26
+ * Preimage of an indexed merkle tree leaf.
27
+ */
28
+ export interface IndexedTreeLeafPreimage {
29
+ /**
30
+ * Returns key of the leaf corresponding to this preimage.
31
+ */
32
+ getKey(): bigint;
33
+ /**
34
+ * Returns the key of the next leaf.
35
+ */
36
+ getNextKey(): bigint;
37
+ /**
38
+ * Returns the index of the next leaf.
39
+ */
40
+ getNextIndex(): bigint;
41
+
42
+ /**
43
+ * Returns the preimage as a leaf.
44
+ */
45
+ asLeaf(): IndexedTreeLeaf;
46
+ /**
47
+ * Serializes the preimage into a buffer.
48
+ */
49
+ toBuffer(): Buffer;
50
+ /**
51
+ * Serializes the preimage to an array of buffers for hashing.
52
+ */
53
+ toHashInputs(): Buffer[];
54
+ }
@@ -0,0 +1,8 @@
1
+ /** Strips methods of a type. */
2
+ export type FieldsOf<T> = {
3
+ // eslint-disable-next-line @typescript-eslint/ban-types
4
+ [P in keyof T as T[P] extends Function ? never : P]: T[P];
5
+ };
6
+
7
+ /** Marks a set of properties of a type as optional. */
8
+ export type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
@@ -0,0 +1,73 @@
1
+ /* eslint-disable */
2
+ // Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
3
+ // Permission is hereby granted, free of charge, to any person obtaining
4
+ // a copy of this software and associated documentation files (the
5
+ // 'Software'), to deal in the Software without restriction, including
6
+ // without limitation the rights to use, copy, modify, merge, publish,
7
+ // distribute, sublicense, and/or sell copies of the Software, and to
8
+ // permit persons to whom the Software is furnished to do so, subject to
9
+ // the following conditions:
10
+ // The above copyright notice and this permission notice shall be
11
+ // included in all copies or substantial portions of the Software.
12
+ // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
13
+ // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14
+ // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
15
+ // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
16
+ // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
17
+ // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
18
+ // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+ import { sep } from 'path';
20
+
21
+ /**
22
+ * File URI to Path function.
23
+ *
24
+ * @param {String} uri
25
+ * @return {String} path
26
+ * @api public
27
+ */
28
+
29
+ export function fileURLToPath(uri: string): string {
30
+ if (typeof uri !== 'string' || uri.length <= 7 || uri.substring(0, 7) !== 'file://') {
31
+ throw new TypeError('must pass in a file:// URI to convert to a file path');
32
+ }
33
+
34
+ const rest = decodeURI(uri.substring(7));
35
+ const firstSlash = rest.indexOf('/');
36
+ let host = rest.substring(0, firstSlash);
37
+ let path = rest.substring(firstSlash + 1);
38
+
39
+ // 2. Scheme Definition
40
+ // As a special case, <host> can be the string "localhost" or the empty
41
+ // string; this is interpreted as "the machine from which the URL is
42
+ // being interpreted".
43
+ if (host === 'localhost') {
44
+ host = '';
45
+ }
46
+
47
+ if (host) {
48
+ host = sep + sep + host;
49
+ }
50
+
51
+ // 3.2 Drives, drive letters, mount points, file system root
52
+ // Drive letters are mapped into the top of a file URI in various ways,
53
+ // depending on the implementation; some applications substitute
54
+ // vertical bar ("|") for the colon after the drive letter, yielding
55
+ // "file:///c|/tmp/test.txt". In some cases, the colon is left
56
+ // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the
57
+ // colon is simply omitted, as in "file:///c/tmp/test.txt".
58
+ path = path.replace(/^(.+)\|/, '$1:');
59
+
60
+ // for Windows, we need to invert the path separators from what a URI uses
61
+ if (sep === '\\') {
62
+ path = path.replace(/\//g, '\\');
63
+ }
64
+
65
+ if (/^.+:/.test(path)) {
66
+ // has Windows drive at beginning of path
67
+ } else {
68
+ // unix path…
69
+ path = sep + path;
70
+ }
71
+
72
+ return host + path;
73
+ }
@@ -0,0 +1,6 @@
1
+ # wasm
2
+
3
+ Functionality to:
4
+
5
+ 1. Call WebAssembly functions
6
+ 2. Create asynchronous workers that host webassembly.
@@ -0,0 +1,166 @@
1
+ import { createDebugOnlyLogger } from '../log/index.js';
2
+
3
+ /**
4
+ * Dummy implementation of a necessary part of the wasi api:
5
+ * https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md
6
+ * We don't use these functions, but the environment expects them.
7
+ * TODO find a way to update off of wasi 12.
8
+ */
9
+ /* eslint-disable camelcase */
10
+ export const getEmptyWasiSdk = (debug = createDebugOnlyLogger('wasm:empty_wasi_sdk')) => ({
11
+ /**
12
+ * Retrieves the current time from the system clock.
13
+ * This function is a dummy implementation of the WASI API's `clock_time_get` method,
14
+ * which is expected by the environment but not used in this context.
15
+ *
16
+ * No input parameters or return values are required, as the purpose of this function
17
+ * is solely to satisfy the environment expectations and provide debugging information.
18
+ */
19
+ clock_time_get() {
20
+ debug('clock_time_get');
21
+ },
22
+ /**
23
+ * Dummy implementation of WASI's environ_get function.
24
+ * This function is used to obtain a snapshot of the current environment variables.
25
+ * In this dummy implementation, no actual actions are performed, but the debug logger logs 'environ_get' when called.
26
+ * Environment variables are not used in this context, so the real implementation is not required.
27
+ *
28
+ * @see https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md#environ_get
29
+ */
30
+ environ_get() {
31
+ debug('environ_get');
32
+ },
33
+ /**
34
+ * Retrieves the environment variable sizes from the WebAssembly environment.
35
+ * This function is part of the WASI API and provides a dummy implementation to fulfill the expected APIs.
36
+ * It does not have any actual functionality, but serves as a placeholder in the environment.
37
+ */
38
+ environ_sizes_get() {
39
+ debug('environ_sizes_get');
40
+ },
41
+ /**
42
+ * Closes a file descriptor, releasing any resources associated with it.
43
+ * This function does not perform any actual closing operation, but exists to
44
+ * satisfy the requirements of the WebAssembly System Interface (WASI) API,
45
+ * which expects certain functions to be present for compatibility purposes.
46
+ *
47
+ * @see https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md
48
+ */
49
+ fd_close() {
50
+ debug('fd_close');
51
+ },
52
+ /**
53
+ * A dummy implementation of the 'fd_read' function from the WASI API.
54
+ * This function is required by the environment, but not used in this context.
55
+ * It would normally read data from a file descriptor into an array buffer,
56
+ * but here it simply logs the invocation for debugging purposes.
57
+ */
58
+ fd_read() {
59
+ debug('fd_read');
60
+ },
61
+ /**
62
+ * Handles the file descriptor write operation.
63
+ * This dummy implementation of the WASI 'fd_write' function is part of the wasi API:
64
+ * https://github.com/WebAssembly/WASI/blob/main/phases/snapshot/docs.md
65
+ * The environment expects this function, but it is not used in the current implementation.
66
+ * It is used to write data from WebAssembly memory to a file descriptor.
67
+ */
68
+ fd_write() {
69
+ debug('fd_write');
70
+ },
71
+ /**
72
+ * Perform a file seek operation on the given file descriptor to change its current position.
73
+ * The new position is calculated using the provided offset and whence values.
74
+ * Throws an error if the file descriptor is invalid or the operation cannot be performed.
75
+ *
76
+ * @param fd - The file descriptor of the file to perform the seek operation on.
77
+ * @param offset - The relative offset to apply, based on the whence value.
78
+ * @param whence - The reference point from which the offset should be calculated. One of SEEK_SET (start), SEEK_CUR (current), or SEEK_END (end).
79
+ * @returns The new position in the file after the seek operation has been performed.
80
+ */
81
+ fd_seek() {
82
+ debug('fd_seek');
83
+ },
84
+ /**
85
+ * This function is a dummy implementation of the 'fd_fdstat_get' function in the WebAssembly System Interface (WASI) API.
86
+ * Although not actually used in this context, it is present due to the environment's expectation of its existence.
87
+ * The 'fd_fdstat_get' function is typically responsible for obtaining file descriptor status information.
88
+ */
89
+ fd_fdstat_get() {
90
+ debug('fd_fdstat_get');
91
+ },
92
+ /**
93
+ * Sets the file descriptor flags for a given file descriptor.
94
+ * This function is a dummy implementation of the WASI API function 'fd_fdstat_set_flags'.
95
+ * It currently does not perform any operation but logs the function call with a debug instance.
96
+ * This is provided since the environment expects this function to be present.
97
+ */
98
+ fd_fdstat_set_flags() {
99
+ debug('fd_fdstat_set_flags');
100
+ },
101
+ /**
102
+ * Handles the `fd_prestat_get` function call for the dummy WebAssembly System Interface (WASI) implementation.
103
+ * This function is expected by the WASI environment, although it is not used in this implementation.
104
+ * The `fd_prestat_get` function retrieves pre-opened file descriptor properties.
105
+ *
106
+ * @returns A constant integer value indicating successful completion of the function call.
107
+ */
108
+ fd_prestat_get() {
109
+ debug('fd_prestat_get');
110
+ return 8;
111
+ },
112
+ /**
113
+ * Provides a dummy implementation for the `fd_prestat_dir_name` function, which is expected to be called by the WASI environment.
114
+ * This function is intended to retrieve the pre-opened directory's path associated with the given file descriptor. However, since it's a dummy implementation,
115
+ * it doesn't perform any actual operation and only logs the function call with the provided debug logger.
116
+ *
117
+ * @returns A constant number representing a dummy return value for the function call.
118
+ */
119
+ fd_prestat_dir_name() {
120
+ debug('fd_prestat_dir_name');
121
+ return 28;
122
+ },
123
+ /**
124
+ * Handles the opening of a file path within the WASI environment.
125
+ * This function is a dummy implementation required for compatibility with
126
+ * the WebAssembly System Interface (WASI) API, but it does not perform any
127
+ * actual file opening operation. It is mainly used for debugging purposes.
128
+ */
129
+ path_open() {
130
+ debug('path_open');
131
+ },
132
+ /**
133
+ * Retrieve file system information of the specified path.
134
+ * This function retrieves statistics, such as size and permissions, associated with the file or directory
135
+ * identified by the given path. In case of an error or non-existing path, appropriate debug logs will be generated.
136
+ *
137
+ * @returns An object containing file statistics like size, permissions, etc.
138
+ */
139
+ path_filestat_get() {
140
+ debug('path_filestat_get');
141
+ },
142
+ /**
143
+ * Terminate the process normally, performing the regular cleanup for terminating programs.
144
+ * The input 'status' represents the exit code and is used to indicate success or failure
145
+ * of the program execution. A zero value typically indicates successful execution,
146
+ * while non-zero values are treated as errors by the operating system.
147
+ *
148
+ * @param status - The exit code representing the success or failure of the program execution.
149
+ * @returns The exit status code.
150
+ */
151
+ proc_exit() {
152
+ debug('proc_exit');
153
+ return 52;
154
+ },
155
+ /**
156
+ * Generates a random number and returns it.
157
+ * This dummy implementation of 'random_get' method in the wasi API is expected by the environment.
158
+ * In this case, the function always returns 1 to maintain consistency with the environment's expectations.
159
+ *
160
+ * @returns A random number. In this implementation, always returns 1.
161
+ */
162
+ random_get() {
163
+ debug('random_get');
164
+ return 1;
165
+ },
166
+ });
Binary file
@@ -0,0 +1,27 @@
1
+ (module
2
+ (func $gcd (param i32 i32) (result i32)
3
+ (local i32)
4
+ block ;; label = @1
5
+ block ;; label = @2
6
+ local.get 0
7
+ br_if 0 (;@2;)
8
+ local.get 1
9
+ local.set 2
10
+ br 1 (;@1;)
11
+ end
12
+ loop ;; label = @2
13
+ local.get 1
14
+ local.get 0
15
+ local.tee 2
16
+ i32.rem_u
17
+ local.set 0
18
+ local.get 2
19
+ local.set 1
20
+ local.get 0
21
+ br_if 0 (;@2;)
22
+ end
23
+ end
24
+ local.get 2
25
+ )
26
+ (export "gcd" (func $gcd))
27
+ )
@@ -0,0 +1 @@
1
+ export { WasmModule, IWasmModule } from './wasm_module.js';
@@ -0,0 +1,260 @@
1
+ import { Buffer } from 'buffer';
2
+
3
+ import { randomBytes } from '../crypto/index.js';
4
+ import { MemoryFifo } from '../fifo/index.js';
5
+ import { LogFn, createDebugOnlyLogger } from '../log/index.js';
6
+ import { getEmptyWasiSdk } from './empty_wasi_sdk.js';
7
+
8
+ /**
9
+ * The base shape of a WASM module providing low level memory and synchronous call access.
10
+ * Note that the Aztec codebase used to support asyncify but has fully moved away,
11
+ * using web workers if needed.
12
+ */
13
+ export interface IWasmModule {
14
+ /**
15
+ * Low level call function, returns result as number.
16
+ * @param name - The function name.
17
+ * @param args - The function args.
18
+ * @returns The value as an integer (could be pointer).
19
+ */
20
+ call(name: string, ...args: any): number;
21
+
22
+ /**
23
+ * Get a slice of memory between two addresses.
24
+ * @param start - The start address.
25
+ * @param end - The end address.
26
+ * @returns A Uint8Array view of memory.
27
+ */
28
+ getMemorySlice(start: number, end: number): Uint8Array;
29
+
30
+ /**
31
+ * Write data into the heap.
32
+ * @param offset - The address to write data at.
33
+ * @param arr - The data to write.
34
+ */
35
+ writeMemory(offset: number, arr: Uint8Array): void;
36
+ }
37
+
38
+ /**
39
+ * WasmModule:
40
+ * Helper over a webassembly module.
41
+ * Assumes a few quirks.
42
+ * 1) the module expects wasi_snapshot_preview1 with the methods from getEmptyWasiSdk
43
+ * 2) of which the webassembly
44
+ * we instantiate only uses random_get (update this if more WASI sdk methods are needed).
45
+ */
46
+ export class WasmModule implements IWasmModule {
47
+ private memory!: WebAssembly.Memory;
48
+ private heap!: Uint8Array;
49
+ private instance?: WebAssembly.Instance;
50
+ private mutexQ = new MemoryFifo<boolean>();
51
+ private debug: LogFn;
52
+
53
+ /**
54
+ * Create a wasm module. Should be followed by await init();.
55
+ * @param module - The module as a WebAssembly.Module or a Buffer.
56
+ * @param importFn - Imports expected by the WASM.
57
+ * @param loggerName - Optional, for debug logging.
58
+ */
59
+ constructor(
60
+ private module: WebAssembly.Module | Buffer,
61
+ private importFn: (module: WasmModule) => any,
62
+ loggerName = 'aztec:wasm',
63
+ ) {
64
+ this.debug = createDebugOnlyLogger(loggerName);
65
+ this.mutexQ.put(true);
66
+ }
67
+
68
+ /**
69
+ * Return the wasm source.
70
+ * @returns The source.
71
+ */
72
+ public getModule(): WebAssembly.Module | Buffer {
73
+ return this.module;
74
+ }
75
+ /**
76
+ * Initialize this wasm module.
77
+ * @param wasmImportEnv - Linked to a module called "env". Functions implementations referenced from e.g. C++.
78
+ * @param initial - 30 pages by default. 30*2**16 \> 1mb stack size plus other overheads.
79
+ * @param initMethod - Defaults to calling '_initialize'.
80
+ * @param maximum - 8192 maximum by default. 512mb.
81
+ */
82
+ public async init(initial = 30, maximum = 8192, initMethod: string | null = '_initialize') {
83
+ this.debug(
84
+ `initial mem: ${initial} pages, ${(initial * 2 ** 16) / (1024 * 1024)}mb. max mem: ${maximum} pages, ${
85
+ (maximum * 2 ** 16) / (1024 * 1024)
86
+ }mb`,
87
+ );
88
+ this.memory = new WebAssembly.Memory({ initial, maximum });
89
+ // Create a view over the memory buffer.
90
+ // We do this once here, as webkit *seems* bugged out and actually shows this as new memory,
91
+ // thus displaying double. It's only worse if we create views on demand. I haven't established yet if
92
+ // the bug is also exasperating the termination on mobile due to "excessive memory usage". It could be
93
+ // that the OS is actually getting an incorrect reading in the same way the memory profiler does...
94
+ // The view will have to be recreated if the memory is grown. See getMemory().
95
+ this.heap = new Uint8Array(this.memory.buffer);
96
+
97
+ // We support the wasi 12 SDK, but only implement random_get
98
+ /* eslint-disable camelcase */
99
+ const importObj = {
100
+ wasi_snapshot_preview1: {
101
+ ...getEmptyWasiSdk(this.debug),
102
+ random_get: (arr: number, length: number) => {
103
+ arr = arr >>> 0;
104
+ const heap = this.getMemory();
105
+ const randomData = randomBytes(length);
106
+ for (let i = arr; i < arr + length; ++i) {
107
+ heap[i] = randomData[i - arr];
108
+ }
109
+ },
110
+ },
111
+ env: this.importFn(this),
112
+ };
113
+
114
+ if (this.module instanceof WebAssembly.Module) {
115
+ this.instance = await WebAssembly.instantiate(this.module, importObj);
116
+ } else {
117
+ const { instance } = await WebAssembly.instantiate(this.module, importObj);
118
+ this.instance = instance;
119
+ }
120
+
121
+ // Init all global/static data.
122
+ if (initMethod) {
123
+ this.call(initMethod);
124
+ }
125
+ }
126
+
127
+ /**
128
+ * The methods or objects exported by the WASM module.
129
+ * @returns An indexable object.
130
+ */
131
+ public exports(): any {
132
+ if (!this.instance) {
133
+ throw new Error('WasmModule: not initialized!');
134
+ }
135
+ return this.instance.exports;
136
+ }
137
+
138
+ /**
139
+ * Get the current logger.
140
+ * @returns Logging function.
141
+ */
142
+ public getLogger() {
143
+ return this.debug;
144
+ }
145
+
146
+ /**
147
+ * Add a logger.
148
+ * @param logger - Function to call when logging.
149
+ */
150
+ public addLogger(logger: LogFn) {
151
+ const oldDebug = this.debug;
152
+ this.debug = (msg: string) => {
153
+ logger(msg);
154
+ oldDebug(msg);
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Calls into the WebAssembly.
160
+ * @param name - The method name.
161
+ * @param args - The arguments to the method.
162
+ * @returns The numeric method result.
163
+ */
164
+ public call(name: string, ...args: any): number {
165
+ if (!this.exports()[name]) {
166
+ throw new Error(`WASM function ${name} not found.`);
167
+ }
168
+ try {
169
+ // When returning values from the WASM, use >>> operator to convert
170
+ // signed representation to unsigned representation.
171
+ return this.exports()[name](...args) >>> 0;
172
+ } catch (err: any) {
173
+ const message = `WASM function ${name} aborted, error: ${err}\n${err.stack}`;
174
+ throw new Error(message);
175
+ }
176
+ }
177
+ /**
178
+ * Get the memory used by the WASM module.
179
+ * @returns A WebAssembly memory object.
180
+ */
181
+ public getRawMemory(): WebAssembly.Memory {
182
+ return this.memory;
183
+ }
184
+ /**
185
+ * Get the memory used by the WASM module, as a byte array.
186
+ * @returns A Uint8Array view of the WASM module memory.
187
+ */
188
+ public getMemory(): Uint8Array {
189
+ // If the memory is grown, our view over it will be lost. Recreate the view.
190
+ if (this.heap.length === 0) {
191
+ this.heap = new Uint8Array(this.memory.buffer);
192
+ }
193
+ return this.heap;
194
+ }
195
+
196
+ /**
197
+ * The memory size in bytes.
198
+ * @returns Number of bytes.
199
+ */
200
+ public memSize(): number {
201
+ return this.getMemory().length;
202
+ }
203
+
204
+ /**
205
+ * Get a slice of memory between two addresses.
206
+ * @param start - The start address.
207
+ * @param end - The end address.
208
+ * @returns A Uint8Array view of memory.
209
+ */
210
+ public getMemorySlice(start: number, end: number): Uint8Array {
211
+ return this.getMemory().slice(start, end);
212
+ }
213
+
214
+ /**
215
+ * Write data into the heap.
216
+ * @param offset - The address to write data at.
217
+ * @param arr - The data to write.
218
+ */
219
+ public writeMemory(offset: number, arr: Uint8Array) {
220
+ const mem = this.getMemory();
221
+ for (let i = 0; i < arr.length; i++) {
222
+ mem[i + offset] = arr[i];
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Read WASM memory as a JS string.
228
+ * @param addr - The memory address.
229
+ * @returns A JS string.
230
+ */
231
+ public getMemoryAsString(addr: number) {
232
+ addr = addr >>> 0;
233
+ const m = this.getMemory();
234
+ let i = addr;
235
+ while (m[i] !== 0) {
236
+ ++i;
237
+ }
238
+ return Buffer.from(m.slice(addr, i)).toString('ascii');
239
+ }
240
+
241
+ /**
242
+ * When calling the wasm, sometimes a caller will require exclusive access over a series of calls.
243
+ * E.g. When a result is written to address 0, one cannot have another caller writing to the same address via
244
+ * writeMemory before the result is read via sliceMemory.
245
+ * Acquire() gets a single token from a fifo. The caller must call release() to add the token back.
246
+ */
247
+ public async acquire() {
248
+ await this.mutexQ.get();
249
+ }
250
+
251
+ /**
252
+ * Release the mutex, letting another promise call acquire().
253
+ */
254
+ public release() {
255
+ if (this.mutexQ.length() !== 0) {
256
+ throw new Error('Release called but not acquired.');
257
+ }
258
+ this.mutexQ.put(true);
259
+ }
260
+ }
@@ -0,0 +1,2 @@
1
+ export * from './web_worker.js';
2
+ export * from './web_data_store.js';
@@ -0,0 +1,23 @@
1
+ import { DispatchMsg, TransportServer, WorkerListener } from '../../transport/index.js';
2
+ import { WasmModule } from '../../wasm/index.js';
3
+
4
+ /**
5
+ * Start the transport server corresponding to this module.
6
+ * @param module - The WasmModule to host.
7
+ */
8
+ export function startWebModule(module: WasmModule) {
9
+ const dispatch = async ({ fn, args }: DispatchMsg) => {
10
+ if (fn === '__destroyWorker__') {
11
+ transportServer.stop();
12
+ return;
13
+ }
14
+ if (!(module as any)[fn]) {
15
+ throw new Error(`dispatch error, function not found: ${fn}`);
16
+ }
17
+ return await (module as any)[fn](...args);
18
+ };
19
+ const transportListener = new WorkerListener(self);
20
+ const transportServer = new TransportServer<DispatchMsg>(transportListener, dispatch);
21
+ module.addLogger((...args: any[]) => transportServer.broadcast({ fn: 'emit', args: ['log', ...args] }));
22
+ transportServer.start();
23
+ }
@@ -0,0 +1,38 @@
1
+ import levelup, { LevelUp } from 'levelup';
2
+ import memdown from 'memdown';
3
+
4
+ import { DataStore } from '../data_store.js';
5
+
6
+ /**
7
+ * Cache for data used by wasm module.
8
+ * Stores in a LevelUp database.
9
+ */
10
+ export class WebDataStore implements DataStore {
11
+ private db: LevelUp;
12
+
13
+ constructor() {
14
+ // TODO: The whole point of this is to reduce memory load in the browser.
15
+ // Replace with leveljs so the data is stored in indexeddb and not in memory.
16
+ // Hack: Cast as any to work around package "broken" with node16 resolution
17
+ // See https://github.com/microsoft/TypeScript/issues/49160
18
+ this.db = levelup((memdown as any)());
19
+ }
20
+
21
+ /**
22
+ * Lookup a key.
23
+ * @param key - Key to lookup.
24
+ * @returns The buffer.
25
+ */
26
+ async get(key: string): Promise<Buffer | undefined> {
27
+ return await this.db.get(key).catch(() => {});
28
+ }
29
+
30
+ /**
31
+ * Alter a key.
32
+ * @param key - Key to alter.
33
+ * @param value - Buffer to store.
34
+ */
35
+ async set(key: string, value: Buffer): Promise<void> {
36
+ await this.db.put(key, value);
37
+ }
38
+ }