@aztec/pxe 0.0.1-commit.3469e52 → 0.0.1-commit.59e663cd

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 (127) hide show
  1. package/dest/bin/check_oracle_version.js +1 -1
  2. package/dest/block_synchronizer/block_synchronizer.d.ts +6 -4
  3. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  4. package/dest/block_synchronizer/block_synchronizer.js +53 -13
  5. package/dest/config/index.d.ts +3 -1
  6. package/dest/config/index.d.ts.map +1 -1
  7. package/dest/config/index.js +17 -0
  8. package/dest/contract_function_simulator/contract_function_simulator.d.ts +1 -1
  9. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  10. package/dest/contract_function_simulator/contract_function_simulator.js +1 -4
  11. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +1 -1
  12. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +1 -1
  13. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +1 -1
  14. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +1 -1
  15. package/dest/contract_function_simulator/oracle/interfaces.d.ts +13 -10
  16. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  17. package/dest/contract_function_simulator/oracle/oracle.d.ts +5 -3
  18. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  19. package/dest/contract_function_simulator/oracle/oracle.js +27 -17
  20. package/dest/contract_function_simulator/oracle/private_execution.d.ts +2 -22
  21. package/dest/contract_function_simulator/oracle/private_execution.d.ts.map +1 -1
  22. package/dest/contract_function_simulator/oracle/private_execution.js +0 -37
  23. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +9 -1
  24. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  25. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +16 -5
  26. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +20 -12
  27. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  28. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +34 -36
  29. package/dest/contract_sync/index.d.ts +23 -0
  30. package/dest/contract_sync/index.d.ts.map +1 -0
  31. package/dest/contract_sync/index.js +54 -0
  32. package/dest/debug/pxe_debug_utils.d.ts +16 -6
  33. package/dest/debug/pxe_debug_utils.d.ts.map +1 -1
  34. package/dest/debug/pxe_debug_utils.js +20 -10
  35. package/dest/entrypoints/server/index.d.ts +2 -1
  36. package/dest/entrypoints/server/index.d.ts.map +1 -1
  37. package/dest/entrypoints/server/index.js +1 -0
  38. package/dest/events/event_service.d.ts +2 -2
  39. package/dest/events/event_service.d.ts.map +1 -1
  40. package/dest/events/event_service.js +1 -1
  41. package/dest/logs/log_service.d.ts +1 -1
  42. package/dest/logs/log_service.d.ts.map +1 -1
  43. package/dest/logs/log_service.js +17 -11
  44. package/dest/notes/note_service.d.ts +4 -3
  45. package/dest/notes/note_service.d.ts.map +1 -1
  46. package/dest/notes/note_service.js +11 -10
  47. package/dest/oracle_version.d.ts +3 -3
  48. package/dest/oracle_version.d.ts.map +1 -1
  49. package/dest/oracle_version.js +4 -3
  50. package/dest/private_kernel/private_kernel_oracle.d.ts +3 -3
  51. package/dest/private_kernel/private_kernel_oracle.d.ts.map +1 -1
  52. package/dest/pxe.d.ts +1 -1
  53. package/dest/pxe.d.ts.map +1 -1
  54. package/dest/pxe.js +13 -11
  55. package/dest/storage/contract_store/contract_store.d.ts +1 -2
  56. package/dest/storage/contract_store/contract_store.d.ts.map +1 -1
  57. package/dest/storage/contract_store/contract_store.js +0 -12
  58. package/dest/storage/note_store/note_store.d.ts +43 -55
  59. package/dest/storage/note_store/note_store.d.ts.map +1 -1
  60. package/dest/storage/note_store/note_store.js +238 -252
  61. package/dest/storage/note_store/stored_note.d.ts +16 -0
  62. package/dest/storage/note_store/stored_note.d.ts.map +1 -0
  63. package/dest/storage/note_store/stored_note.js +43 -0
  64. package/dest/storage/private_event_store/private_event_store.d.ts +17 -4
  65. package/dest/storage/private_event_store/private_event_store.d.ts.map +1 -1
  66. package/dest/storage/private_event_store/private_event_store.js +163 -135
  67. package/dest/storage/private_event_store/stored_private_event.d.ts +23 -0
  68. package/dest/storage/private_event_store/stored_private_event.d.ts.map +1 -0
  69. package/dest/storage/private_event_store/stored_private_event.js +56 -0
  70. package/dest/tagging/get_all_logs_by_tags.d.ts +24 -0
  71. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -0
  72. package/dest/tagging/get_all_logs_by_tags.js +46 -0
  73. package/dest/tagging/index.d.ts +2 -1
  74. package/dest/tagging/index.d.ts.map +1 -1
  75. package/dest/tagging/index.js +1 -0
  76. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts +3 -2
  77. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts.map +1 -1
  78. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.js +2 -2
  79. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts +3 -2
  80. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts.map +1 -1
  81. package/dest/tagging/recipient_sync/utils/load_logs_for_range.js +5 -2
  82. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +3 -2
  83. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  84. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +2 -2
  85. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +1 -1
  86. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  87. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +5 -8
  88. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +3 -2
  89. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  90. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +7 -4
  91. package/package.json +16 -16
  92. package/src/bin/check_oracle_version.ts +1 -0
  93. package/src/block_synchronizer/block_synchronizer.ts +55 -21
  94. package/src/config/index.ts +14 -0
  95. package/src/contract_function_simulator/contract_function_simulator.ts +1 -9
  96. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +1 -1
  97. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +1 -1
  98. package/src/contract_function_simulator/oracle/interfaces.ts +18 -9
  99. package/src/contract_function_simulator/oracle/oracle.ts +34 -21
  100. package/src/contract_function_simulator/oracle/private_execution.ts +1 -60
  101. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +32 -6
  102. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +53 -45
  103. package/src/contract_sync/index.ts +98 -0
  104. package/src/debug/pxe_debug_utils.ts +26 -11
  105. package/src/entrypoints/server/index.ts +1 -0
  106. package/src/events/event_service.ts +1 -1
  107. package/src/logs/log_service.ts +24 -8
  108. package/src/notes/note_service.ts +18 -15
  109. package/src/oracle_version.ts +4 -3
  110. package/src/private_kernel/private_kernel_oracle.ts +2 -2
  111. package/src/pxe.ts +35 -12
  112. package/src/storage/contract_store/contract_store.ts +0 -20
  113. package/src/storage/note_store/note_store.ts +279 -313
  114. package/src/storage/note_store/stored_note.ts +48 -0
  115. package/src/storage/private_event_store/private_event_store.ts +214 -175
  116. package/src/storage/private_event_store/stored_private_event.ts +73 -0
  117. package/src/tagging/get_all_logs_by_tags.ts +68 -0
  118. package/src/tagging/index.ts +1 -0
  119. package/src/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.ts +11 -1
  120. package/src/tagging/recipient_sync/utils/load_logs_for_range.ts +7 -1
  121. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +3 -1
  122. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +5 -17
  123. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +12 -3
  124. package/dest/tree_membership/tree_membership_service.d.ts +0 -50
  125. package/dest/tree_membership/tree_membership_service.d.ts.map +0 -1
  126. package/dest/tree_membership/tree_membership_service.js +0 -75
  127. package/src/tree_membership/tree_membership_service.ts +0 -97
@@ -1,134 +1,232 @@
1
- import type { Fr } from '@aztec/foundation/curves/bn254';
2
1
  import { toArray } from '@aztec/foundation/iterable';
2
+ import { Semaphore } from '@aztec/foundation/queue';
3
+ import type { Fr } from '@aztec/foundation/schemas';
3
4
  import type { AztecAsyncKVStore, AztecAsyncMap, AztecAsyncMultiMap } from '@aztec/kv-store';
4
- import { AztecAddress } from '@aztec/stdlib/aztec-address';
5
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
5
6
  import type { DataInBlock } from '@aztec/stdlib/block';
6
- import { NoteStatus, type NotesFilter } from '@aztec/stdlib/note';
7
- import { NoteDao } from '@aztec/stdlib/note';
7
+ import { NoteDao, NoteStatus, type NotesFilter } from '@aztec/stdlib/note';
8
+
9
+ import type { StagedStore } from '../../job_coordinator/job_coordinator.js';
10
+ import { StoredNote } from './stored_note.js';
8
11
 
9
12
  /**
10
13
  * NoteStore manages the storage and retrieval of notes.
11
14
  *
12
- * Notes can be active or nullified. This class processes new notes, nullifications,
13
- * and performs rollback handling in the case of a reorg.
15
+ * Notes can be active or nullified. This class processes new notes, nullifications, and performs rollback handling in
16
+ * the case of a reorg.
14
17
  **/
15
- export class NoteStore {
18
+ export class NoteStore implements StagedStore {
19
+ readonly storeName: string = 'note';
20
+
16
21
  #store: AztecAsyncKVStore;
17
22
 
18
23
  // Note that we use the siloedNullifier as the note id in the store as it's guaranteed to be unique.
19
24
 
20
- /** noteId (siloedNullifier) -> NoteDao (serialized) */
25
+ // Main storage for notes. Avoid performing full scans on it as it contains all notes PXE knows, use
26
+ // #nullifiersByContractAddress or #nullifiersByNullificationBlockNumber to find relevant note nullifiers that can be
27
+ // used to read into this map instead.
28
+ // nullifier => StoredNote (serialized)
21
29
  #notes: AztecAsyncMap<string, Buffer>;
22
- /** noteId (siloedNullifier) -> NoteDao (serialized) */
23
- #nullifiedNotes: AztecAsyncMap<string, Buffer>;
24
- /** blockNumber -> siloedNullifier */
25
- #nullifiersByBlockNumber: AztecAsyncMultiMap<number, string>;
26
-
27
- /** noteId (siloedNullifier) -> scope */
28
- #nullifiedNotesToScope: AztecAsyncMultiMap<string, string>;
29
- /** contractAddress -> noteId (siloedNullifier) */
30
- #nullifiedNotesByContract: AztecAsyncMultiMap<string, string>;
31
- /** storageSlot -> noteId (siloedNullifier) */
32
- #nullifiedNotesByStorageSlot: AztecAsyncMultiMap<string, string>;
33
-
34
- /** scope (AztecAddress) -> true */
35
- #scopes: AztecAsyncMap<string, true>;
36
- /** noteId (siloedNullifier) -> scope */
37
- #notesToScope: AztecAsyncMultiMap<string, string>;
38
- /** scope -> MultiMap(contractAddress -> noteId) */
39
- #notesByContractAndScope: Map<string, AztecAsyncMultiMap<string, string>>;
40
- /** scope -> MultiMap(storageSlot -> noteId) */
41
- #notesByStorageSlotAndScope: Map<string, AztecAsyncMultiMap<string, string>>;
42
-
43
- private constructor(store: AztecAsyncKVStore) {
30
+
31
+ // Indexes which notes (via their nullifiers) belong to a contract. Used in `getNotes` to reduce the amount of notes
32
+ // checked.
33
+ // contract address => nullifier
34
+ #nullifiersByContractAddress: AztecAsyncMultiMap<string, string>;
35
+
36
+ // Groups note nullifiers by the block number they were added to the nullifier tree. Used in `rollback` to handle
37
+ // re-orgs.
38
+ // block number => nullifier (block number in which nullifier is included)
39
+ #nullifiersByNullificationBlockNumber: AztecAsyncMultiMap<number, string>;
40
+
41
+ // In-memory changes performed during a not-yet committed job. When `commit` is called with said job's id, these
42
+ // changes are persisted in the DB maps specified above and cleared.
43
+ // jobId => nullifier => StoredNote (serialized)
44
+ #notesForJob: Map<string, Map<string, StoredNote>>;
45
+
46
+ // Per job locks to prevent multiple concurrent writes to affect each other.
47
+ // jobId => lock
48
+ #jobLocks: Map<string, Semaphore>;
49
+
50
+ constructor(store: AztecAsyncKVStore) {
44
51
  this.#store = store;
45
52
  this.#notes = store.openMap('notes');
46
- this.#nullifiedNotes = store.openMap('nullified_notes');
47
- this.#nullifiersByBlockNumber = store.openMultiMap('nullifier_to_block_number');
48
-
49
- this.#nullifiedNotesToScope = store.openMultiMap('nullified_notes_to_scope');
50
- this.#nullifiedNotesByContract = store.openMultiMap('nullified_notes_by_contract');
51
- this.#nullifiedNotesByStorageSlot = store.openMultiMap('nullified_notes_by_storage_slot');
53
+ this.#nullifiersByContractAddress = store.openMultiMap('note_nullifiers_by_contract');
54
+ this.#nullifiersByNullificationBlockNumber = store.openMultiMap('note_block_number_to_nullifier');
52
55
 
53
- this.#scopes = store.openMap('scopes');
54
- this.#notesToScope = store.openMultiMap('notes_to_scope');
55
- this.#notesByContractAndScope = new Map<string, AztecAsyncMultiMap<string, string>>();
56
- this.#notesByStorageSlotAndScope = new Map<string, AztecAsyncMultiMap<string, string>>();
56
+ this.#jobLocks = new Map();
57
+ this.#notesForJob = new Map();
57
58
  }
58
59
 
59
60
  /**
60
- * Creates and initializes a new NoteStore instance.
61
+ * Adds multiple notes to the notes store under the specified scope.
61
62
  *
62
- * This factory method creates a NoteStore and restores any existing
63
- * scope-specific indexes from the database.
63
+ * Notes are stored using their siloedNullifier as the key, which provides uniqueness. Each note is indexed by
64
+ * multiple criteria for efficient retrieval.
64
65
  *
65
- * @param store - The key-value store to use for persistence
66
- * @returns Promise resolving to a fully initialized NoteStore instance
66
+ * @param notes - Notes to store
67
+ * @param scope - The scope (user/account) under which to store the notes
68
+ * @param jobId - The job context for staged writes
67
69
  */
68
- public static async create(store: AztecAsyncKVStore): Promise<NoteStore> {
69
- const pxeDB = new NoteStore(store);
70
- for await (const scope of pxeDB.#scopes.keysAsync()) {
71
- pxeDB.#notesByContractAndScope.set(scope, store.openMultiMap(`${scope}:notes_by_contract`));
72
- pxeDB.#notesByStorageSlotAndScope.set(scope, store.openMultiMap(`${scope}:notes_by_storage_slot`));
70
+ public addNotes(notes: NoteDao[], scope: AztecAddress, jobId: string): Promise<void[]> {
71
+ return this.#withJobLock(jobId, () => Promise.all(notes.map(noteDao => this.#addNote(noteDao, scope, jobId))));
72
+ }
73
+
74
+ async #addNote(note: NoteDao, scope: AztecAddress, jobId: string) {
75
+ const noteForJob =
76
+ (await this.#readNote(note.siloedNullifier.toString(), jobId)) ?? new StoredNote(note, new Set());
77
+
78
+ // Make sure the note is linked to the scope and staged for this job
79
+ noteForJob.addScope(scope.toString());
80
+ this.#writeNote(noteForJob, jobId);
81
+ }
82
+
83
+ async #readNote(nullifier: string, jobId: string): Promise<StoredNote | undefined> {
84
+ // First check staged notes for this job
85
+ const noteForJob = this.#getNotesForJob(jobId).get(nullifier);
86
+ if (noteForJob) {
87
+ return noteForJob;
73
88
  }
74
- return pxeDB;
89
+
90
+ // Then check persistent storage
91
+ const noteBuffer = await this.#notes.getAsync(nullifier);
92
+ if (noteBuffer) {
93
+ return StoredNote.fromBuffer(noteBuffer);
94
+ }
95
+
96
+ return undefined;
97
+ }
98
+
99
+ #writeNote(note: StoredNote, jobId: string) {
100
+ this.#getNotesForJob(jobId).set(note.noteDao.siloedNullifier.toString(), note);
75
101
  }
76
102
 
77
103
  /**
78
- * Adds a new scope to the note data provider.
104
+ * Retrieves notes based on the provided filter criteria.
79
105
  *
80
- * Scopes provide privacy isolation by creating separate indexes for each user.
81
- * Each scope gets its own set of indexes for efficient note retrieval by various criteria.
106
+ * This method queries both active and optionally nullified notes based on the filter parameters.
82
107
  *
83
- * @param scope - The AztecAddress representing the scope/user to add
84
- * @returns Promise resolving to true if scope was added, false if it already existed
108
+ * @param filter - Filter criteria including contractAddress (required), and optional owner,
109
+ * storageSlot, status, scopes, and siloedNullifier.
110
+ * @params jobId - the job context to read from.
111
+ * @returns Filtered and deduplicated notes (a note might be present in multiple scopes - we ensure it is only
112
+ * returned once if this is the case)
113
+ * @throws If filtering by an empty scopes array. Scopes have to be set to undefined or to a non-empty array.
85
114
  */
86
- public async addScope(scope: AztecAddress): Promise<boolean> {
87
- const scopeString = scope.toString();
88
-
89
- if (await this.#scopes.hasAsync(scopeString)) {
90
- return false;
115
+ async getNotes(filter: NotesFilter, jobId: string): Promise<NoteDao[]> {
116
+ if (filter.scopes !== undefined && filter.scopes.length === 0) {
117
+ throw new Error('Trying to get notes with an empty scopes array');
91
118
  }
92
119
 
93
- await this.#scopes.set(scopeString, true);
94
- this.#notesByContractAndScope.set(scopeString, this.#store.openMultiMap(`${scopeString}:notes_by_contract`));
95
- this.#notesByStorageSlotAndScope.set(scopeString, this.#store.openMultiMap(`${scopeString}:notes_by_storage_slot`));
120
+ const targetStatus = filter.status ?? NoteStatus.ACTIVE;
121
+
122
+ const foundNotes: Map<string, NoteDao> = new Map();
123
+
124
+ const nullifiersOfContract = await this.#nullifiersOfContract(filter.contractAddress, jobId);
125
+ for (const nullifier of nullifiersOfContract) {
126
+ const note = await this.#readNote(nullifier, jobId);
127
+
128
+ // Defensive: hitting this case means we're mishandling contract indices or in-memory job data
129
+ if (!note) {
130
+ throw new Error('PXE note database is corrupted.');
131
+ }
132
+
133
+ // Apply filters
134
+ if (targetStatus === NoteStatus.ACTIVE && note.isNullified()) {
135
+ continue;
136
+ }
137
+
138
+ if (filter.owner && !note.noteDao.owner.equals(filter.owner)) {
139
+ continue;
140
+ }
141
+
142
+ if (filter.storageSlot && !note.noteDao.storageSlot.equals(filter.storageSlot)) {
143
+ continue;
144
+ }
145
+
146
+ if (filter.siloedNullifier && !note.noteDao.siloedNullifier.equals(filter.siloedNullifier)) {
147
+ continue;
148
+ }
149
+
150
+ if (filter.scopes && note.scopes.intersection(new Set(filter.scopes.map(s => s.toString()))).size === 0) {
151
+ continue;
152
+ }
96
153
 
97
- return true;
154
+ foundNotes.set(note.noteDao.siloedNullifier.toString(), note.noteDao);
155
+ }
156
+
157
+ // Sort by block number, then by tx index within block, then by note index within tx
158
+ return [...foundNotes.values()].sort((a, b) => {
159
+ if (a.l2BlockNumber !== b.l2BlockNumber) {
160
+ return a.l2BlockNumber - b.l2BlockNumber;
161
+ }
162
+ if (a.txIndexInBlock !== b.txIndexInBlock) {
163
+ return a.txIndexInBlock - b.txIndexInBlock;
164
+ }
165
+ return a.noteIndexInTx - b.noteIndexInTx;
166
+ });
98
167
  }
99
168
 
100
169
  /**
101
- * Adds multiple notes to the data provider under the specified scope.
170
+ * Transitions notes from "active" to "nullified" state.
102
171
  *
103
- * Notes are stored using their siloedNullifier as the key, which provides uniqueness. Each note is indexed
104
- * by multiple criteria for efficient retrieval.
172
+ * This operation processes a batch of nullifiers to mark the corresponding notes as spent/nullified.
173
+ * The operation is atomic - if any nullifier is not found, the entire operation fails and no notes are modified.
105
174
  *
106
- * @param notes - Notes to store
107
- * @param scope - The scope (user/account) under which to store the notes
175
+ * applyNullifiers is idempotent: the same nullifier can be applied multiple times without error.
176
+ * This relaxes constraints on usage of NoteService#validateAndStoreNote, which can then be run concurrently in a Promise.all
177
+ * context without risking unnecessarily defensive checks failing.
178
+ *
179
+ * @param nullifiers - Array of nullifiers with their block numbers to process
180
+ * @param jobId - The job context for staged writes
181
+ * @returns Array of NoteDao objects that were nullified
182
+ * @throws Error if any nullifier is not found in this notes store
108
183
  */
109
- addNotes(notes: NoteDao[], scope: AztecAddress): Promise<void> {
110
- return this.#store.transactionAsync(async () => {
111
- if (!(await this.#scopes.hasAsync(scope.toString()))) {
112
- await this.addScope(scope);
113
- }
184
+ applyNullifiers(nullifiers: DataInBlock<Fr>[], jobId: string): Promise<NoteDao[]> {
185
+ return this.#withJobLock(jobId, () =>
186
+ this.#store.transactionAsync(async () => {
187
+ if (nullifiers.length === 0) {
188
+ return [];
189
+ }
114
190
 
115
- for (const dao of notes) {
116
- const noteId = dao.siloedNullifier.toString();
117
- await this.#notes.set(noteId, dao.toBuffer());
118
- await this.#notesToScope.set(noteId, scope.toString());
191
+ const notesToNullify = await Promise.all(
192
+ nullifiers.map(async nullifierInBlock => {
193
+ const nullifier = nullifierInBlock.data.toString();
119
194
 
120
- await this.#notesByContractAndScope.get(scope.toString())!.set(dao.contractAddress.toString(), noteId);
121
- await this.#notesByStorageSlotAndScope.get(scope.toString())!.set(dao.storageSlot.toString(), noteId);
122
- }
123
- });
195
+ const storedNote = await this.#readNote(nullifier, jobId);
196
+ if (!storedNote) {
197
+ throw new Error(`Attempted to mark a note as nullified which does not exist in PXE DB`);
198
+ }
199
+
200
+ return { storedNote: await this.#readNote(nullifier, jobId), blockNumber: nullifierInBlock.l2BlockNumber };
201
+ }),
202
+ );
203
+
204
+ const notesNullifiedInThisCall: Map<string, NoteDao> = new Map();
205
+ for (const noteToNullify of notesToNullify) {
206
+ // Safe to coerce (!) because we throw if we find any undefined above
207
+ const note = noteToNullify.storedNote!;
208
+
209
+ // Skip already nullified notes
210
+ if (note.isNullified()) {
211
+ continue;
212
+ }
213
+
214
+ note.markAsNullified(noteToNullify.blockNumber);
215
+ this.#writeNote(note, jobId);
216
+ notesNullifiedInThisCall.set(note.noteDao.siloedNullifier.toString(), note.noteDao);
217
+ }
218
+
219
+ return [...notesNullifiedInThisCall.values()];
220
+ }),
221
+ );
124
222
  }
125
223
 
126
224
  /**
127
225
  * Synchronizes notes and nullifiers to a specific block number.
128
226
  *
129
- * This method ensures that the state of notes and nullifiers is consistent with the
130
- * specified block number. It restores any notes that were nullified after the given block
131
- * and deletes any active notes created after that block.
227
+ * This method ensures that the state of notes and nullifiers is consistent with the specified block number.
228
+ * It restores any notes that were nullified after the given block and deletes any active notes created after that
229
+ * block.
132
230
  *
133
231
  * IMPORTANT: This method must be called within a transaction to ensure atomicity.
134
232
  *
@@ -136,31 +234,31 @@ export class NoteStore {
136
234
  * @param synchedBlockNumber - The block number up to which PXE managed to sync before the reorg happened.
137
235
  */
138
236
  public async rollback(blockNumber: number, synchedBlockNumber: number): Promise<void> {
139
- await this.#rewindNullifiersAfterBlock(blockNumber, synchedBlockNumber);
237
+ if (this.#notesForJob.size > 0) {
238
+ throw new Error('PXE note store rollback is not allowed while jobs are running');
239
+ }
240
+ await this.#rewindNullifiedNotesAfterBlock(blockNumber, synchedBlockNumber);
140
241
  await this.#deleteActiveNotesAfterBlock(blockNumber);
141
242
  }
142
243
 
143
244
  /**
144
- * Deletes (removes) all active notes created after the specified block number.
245
+ * Deletes (removes) all notes created after the specified block number.
145
246
  *
146
- * Permanently delete notes from the active notes store, e.g. during a reorg.
147
- * Note: This only affects #notes (active notes), not #nullifiedNotes.
247
+ * Permanently delete notes from the notes store, e.g. during a reorg.
148
248
  *
149
249
  * @param blockNumber - Notes created after this block number will be deleted
150
250
  */
151
251
  async #deleteActiveNotesAfterBlock(blockNumber: number): Promise<void> {
152
252
  const notes = await toArray(this.#notes.valuesAsync());
153
- for (const note of notes) {
154
- const noteDao = NoteDao.fromBuffer(note);
155
- if (noteDao.l2BlockNumber > blockNumber) {
156
- const noteId = noteDao.siloedNullifier.toString();
157
- await this.#notes.delete(noteId);
158
- await this.#notesToScope.delete(noteId);
159
- const scopes = await toArray(this.#scopes.keysAsync());
160
- for (const scope of scopes) {
161
- await this.#notesByContractAndScope.get(scope)!.deleteValue(noteDao.contractAddress.toString(), noteId);
162
- await this.#notesByStorageSlotAndScope.get(scope)!.deleteValue(noteDao.storageSlot.toString(), noteId);
163
- }
253
+ for (const noteBuffer of notes) {
254
+ const storedNote = StoredNote.fromBuffer(noteBuffer);
255
+ if (storedNote.noteDao.l2BlockNumber > blockNumber) {
256
+ const noteNullifier = storedNote.noteDao.siloedNullifier.toString();
257
+ await this.#notes.delete(noteNullifier);
258
+ await this.#nullifiersByContractAddress.deleteValue(
259
+ storedNote.noteDao.contractAddress.toString(),
260
+ noteNullifier,
261
+ );
164
262
  }
165
263
  }
166
264
  }
@@ -168,248 +266,116 @@ export class NoteStore {
168
266
  /**
169
267
  * Rewinds nullifications after a given block number.
170
268
  *
171
- * This operation "unnullifies" notes, rolling back nullifications that occurred
172
- * in orphaned blocks, e.g. during a reorg. The notes are restored to the
173
- * active notes store and removed from the nullified store.
269
+ * This operation "un-nullifies" notes, rolling back nullifications that occurred in orphaned blocks, e.g. during a
270
+ * reorg.
174
271
  *
175
272
  * @param blockNumber - Revert nullifications that occurred after this block
176
- * @param synchedBlockNumber - Upper bound for the block range to process
273
+ * @param anchorBlockNumber - Upper bound for the block range to process
177
274
  */
178
- async #rewindNullifiersAfterBlock(blockNumber: number, synchedBlockNumber: number): Promise<void> {
179
- const noteIdsToReinsert: string[] = [];
275
+ async #rewindNullifiedNotesAfterBlock(blockNumber: number, anchorBlockNumber: number): Promise<void> {
180
276
  const currentBlockNumber = blockNumber + 1;
181
- for (let i = currentBlockNumber; i <= synchedBlockNumber; i++) {
182
- // noteId === siloedNullifier.toString(), so we can use nullifiers directly as noteIds
183
- noteIdsToReinsert.push(...(await toArray(this.#nullifiersByBlockNumber.getValuesAsync(i))));
184
- }
185
- const nullifiedNoteBuffers = await Promise.all(
186
- noteIdsToReinsert.map(noteId => this.#nullifiedNotes.getAsync(noteId)),
187
- );
188
- const noteDaos = nullifiedNoteBuffers
189
- .filter(buffer => buffer != undefined)
190
- .map(buffer => NoteDao.fromBuffer(buffer!));
191
-
192
- for (const dao of noteDaos) {
193
- const noteId = dao.siloedNullifier.toString();
194
-
195
- const scopes = await toArray(this.#nullifiedNotesToScope.getValuesAsync(noteId));
196
-
197
- if (scopes.length === 0) {
198
- // We should never run into this error because notes always have a scope assigned to them - either on initial
199
- // insertion via `addNotes` or when removing their nullifiers.
200
- throw new Error(`No scopes found for nullified note with nullifier ${noteId}`);
201
- }
202
-
203
- for (const scope of scopes) {
204
- await Promise.all([
205
- this.#notesByContractAndScope.get(scope.toString())!.set(dao.contractAddress.toString(), noteId),
206
- this.#notesByStorageSlotAndScope.get(scope.toString())!.set(dao.storageSlot.toString(), noteId),
207
- this.#notesToScope.set(noteId, scope),
208
- ]);
209
- }
210
-
211
- await Promise.all([
212
- this.#notes.set(noteId, dao.toBuffer()),
213
- this.#nullifiedNotes.delete(noteId),
214
- this.#nullifiedNotesToScope.delete(noteId),
215
- this.#nullifiersByBlockNumber.deleteValue(dao.l2BlockNumber, dao.siloedNullifier.toString()),
216
- this.#nullifiedNotesByContract.deleteValue(dao.contractAddress.toString(), noteId),
217
- this.#nullifiedNotesByStorageSlot.deleteValue(dao.storageSlot.toString(), noteId),
218
- ]);
219
- }
220
- }
221
-
222
- /**
223
- * Retrieves notes based on the provided filter criteria.
224
- *
225
- * This method queries both active and optionally nullified notes based on the filter
226
- * parameters.
227
- *
228
- * @param filter - Filter criteria including contractAddress (required), and optional
229
- * owner, storageSlot, status, scopes, and siloedNullifier.
230
- * @returns Filtered and deduplicated notes (a note might be present in multiple scopes - we ensure it is only
231
- * returned once if this is the case)
232
- * @throws If filtering by an empty scopes array. Scopes have to be set to undefined or to a non-empty array.
233
- */
234
- async getNotes(filter: NotesFilter): Promise<NoteDao[]> {
235
- filter.status = filter.status ?? NoteStatus.ACTIVE;
236
-
237
- // throw early if scopes is an empty array
238
- if (filter.scopes !== undefined && filter.scopes.length === 0) {
239
- throw new Error(
240
- 'Trying to get notes with an empty scopes array. Scopes have to be set to undefined if intending on not filtering by scopes.',
277
+ for (let i = currentBlockNumber; i <= anchorBlockNumber; i++) {
278
+ const noteNullifiersToReinsert: string[] = await toArray(
279
+ this.#nullifiersByNullificationBlockNumber.getValuesAsync(i),
241
280
  );
242
- }
243
-
244
- const candidateNoteSources = [];
245
281
 
246
- filter.scopes ??= (await toArray(this.#scopes.keysAsync())).map(addressString =>
247
- AztecAddress.fromString(addressString),
248
- );
282
+ const nullifiedNoteBuffers = await Promise.all(
283
+ noteNullifiersToReinsert.map(async noteNullifier => {
284
+ const note = await this.#notes.getAsync(noteNullifier);
249
285
 
250
- const activeNoteIdsPerScope: string[][] = [];
251
-
252
- for (const scope of new Set(filter.scopes)) {
253
- const formattedScopeString = scope.toString();
254
- if (!(await this.#scopes.hasAsync(formattedScopeString))) {
255
- throw new Error('Trying to get incoming notes of a scope that is not in the PXE database');
256
- }
286
+ if (!note) {
287
+ throw new Error(`PXE DB integrity error: no note found with nullifier ${noteNullifier}`);
288
+ }
257
289
 
258
- activeNoteIdsPerScope.push(
259
- filter.storageSlot
260
- ? await toArray(
261
- this.#notesByStorageSlotAndScope.get(formattedScopeString)!.getValuesAsync(filter.storageSlot.toString()),
262
- )
263
- : await toArray(
264
- this.#notesByContractAndScope
265
- .get(formattedScopeString)!
266
- .getValuesAsync(filter.contractAddress.toString()),
267
- ),
290
+ return note;
291
+ }),
268
292
  );
269
- }
270
-
271
- candidateNoteSources.push({
272
- ids: new Set(activeNoteIdsPerScope.flat()),
273
- notes: this.#notes,
274
- });
275
-
276
- // If status is ACTIVE_OR_NULLIFIED we add nullified notes as candidates on top of the default active ones.
277
- if (filter.status === NoteStatus.ACTIVE_OR_NULLIFIED) {
278
- const nullifiedIds = filter.storageSlot
279
- ? await toArray(this.#nullifiedNotesByStorageSlot.getValuesAsync(filter.storageSlot.toString()))
280
- : await toArray(this.#nullifiedNotesByContract.getValuesAsync(filter.contractAddress.toString()));
281
-
282
- const setOfScopes = new Set(filter.scopes.map(s => s.toString() as string));
283
- const filteredNullifiedIds = new Set<string>();
284
-
285
- for (const noteId of nullifiedIds) {
286
- const scopeList = await toArray(this.#nullifiedNotesToScope.getValuesAsync(noteId));
287
- if (scopeList.some(scope => setOfScopes.has(scope))) {
288
- filteredNullifiedIds.add(noteId);
289
- }
290
- }
291
-
292
- if (filteredNullifiedIds.size > 0) {
293
- candidateNoteSources.push({
294
- ids: filteredNullifiedIds,
295
- notes: this.#nullifiedNotes,
296
- });
297
- }
298
- }
299
293
 
300
- const result: NoteDao[] = [];
301
- for (const { ids, notes } of candidateNoteSources) {
302
- for (const id of ids) {
303
- const serializedNote = await notes.getAsync(id);
304
- if (!serializedNote) {
305
- continue;
306
- }
307
-
308
- const note = NoteDao.fromBuffer(serializedNote);
309
- if (!note.contractAddress.equals(filter.contractAddress)) {
310
- continue;
311
- }
294
+ const storedNotes = nullifiedNoteBuffers.map(buffer => StoredNote.fromBuffer(buffer));
312
295
 
313
- if (filter.owner && !note.owner.equals(filter.owner)) {
314
- continue;
315
- }
296
+ for (const storedNote of storedNotes) {
297
+ const noteNullifier = storedNote.noteDao.siloedNullifier.toString();
298
+ const scopes = storedNote.scopes;
316
299
 
317
- if (filter.storageSlot && !note.storageSlot.equals(filter.storageSlot!)) {
318
- continue;
300
+ if (scopes.size === 0) {
301
+ // We should never run into this error because notes always have a scope assigned to them - either on initial
302
+ // insertion via `addNotes` or when removing their nullifiers.
303
+ throw new Error(`No scopes found for nullified note with nullifier ${noteNullifier}`);
319
304
  }
320
305
 
321
- if (filter.siloedNullifier && !note.siloedNullifier.equals(filter.siloedNullifier)) {
322
- continue;
323
- }
306
+ storedNote.markAsActive();
324
307
 
325
- result.push(note);
308
+ await Promise.all([
309
+ this.#notes.set(noteNullifier, storedNote.toBuffer()),
310
+ this.#nullifiersByNullificationBlockNumber.deleteValue(i, noteNullifier),
311
+ ]);
326
312
  }
327
313
  }
314
+ }
328
315
 
329
- // A note might be present in multiple scopes - we ensure it is only returned once
330
- const deduplicated: NoteDao[] = [];
331
- for (const note of result) {
332
- if (!deduplicated.some(existing => existing.equals(note))) {
333
- deduplicated.push(note);
316
+ commit(jobId: string): Promise<void> {
317
+ return this.#withJobLock(jobId, async () => {
318
+ for (const [nullifier, storedNote] of this.#getNotesForJob(jobId)) {
319
+ await this.#notes.set(nullifier, storedNote.toBuffer());
320
+ await this.#nullifiersByContractAddress.set(storedNote.noteDao.contractAddress.toString(), nullifier);
321
+ if (storedNote.nullifiedAt !== undefined) {
322
+ await this.#nullifiersByNullificationBlockNumber.set(storedNote.nullifiedAt, nullifier);
323
+ }
334
324
  }
335
- }
336
325
 
337
- // Sort by block number, then by tx index within block, then by note index within tx
338
- deduplicated.sort((a, b) => {
339
- if (a.l2BlockNumber !== b.l2BlockNumber) {
340
- return a.l2BlockNumber - b.l2BlockNumber;
341
- }
342
- if (a.txIndexInBlock !== b.txIndexInBlock) {
343
- return a.txIndexInBlock - b.txIndexInBlock;
344
- }
345
- return a.noteIndexInTx - b.noteIndexInTx;
326
+ this.#clearJobData(jobId);
346
327
  });
328
+ }
329
+
330
+ discardStaged(jobId: string): Promise<void> {
331
+ return this.#withJobLock(jobId, () => Promise.resolve(this.#clearJobData(jobId)));
332
+ }
347
333
 
348
- return deduplicated;
334
+ #clearJobData(jobId: string) {
335
+ this.#notesForJob.delete(jobId);
336
+ this.#jobLocks.delete(jobId);
349
337
  }
350
338
 
351
339
  /**
352
- * Transitions notes from "active" to "nullified" state.
353
- *
354
- * This operation processes a batch of nullifiers to mark the corresponding notes
355
- * as spent/nullified. The operation is atomic - if any nullifier is not found,
356
- * the entire operation fails and no notes are modified.
357
- *
358
- * @param nullifiers - Array of nullifiers with their block numbers to process
359
- * @returns Promise resolving to array of nullified NoteDao objects
360
- * @throws Error if any nullifier is not found in the active notes
340
+ * Functions run withJobLock are forced to wait for each other, i.e. if they share a `jobId`, they run serially
341
+ * instead of concurrently. This is needed because staged data is stored in memory, and concurrent async operations
342
+ * (e.g., Promise.all in `validateAndStoreNote`) could otherwise interleave and corrupt state.
361
343
  */
362
- applyNullifiers(nullifiers: DataInBlock<Fr>[]): Promise<NoteDao[]> {
363
- if (nullifiers.length === 0) {
364
- return Promise.resolve([]);
344
+ async #withJobLock<T>(jobId: string, fn: () => Promise<T>): Promise<T> {
345
+ let lock = this.#jobLocks.get(jobId);
346
+ if (!lock) {
347
+ lock = new Semaphore(1);
348
+ this.#jobLocks.set(jobId, lock);
365
349
  }
350
+ await lock.acquire();
351
+ try {
352
+ return await fn();
353
+ } finally {
354
+ lock.release();
355
+ }
356
+ }
366
357
 
367
- return this.#store.transactionAsync(async () => {
368
- const nullifiedNotes: NoteDao[] = [];
369
-
370
- for (const blockScopedNullifier of nullifiers) {
371
- const { data: nullifier, l2BlockNumber: blockNumber } = blockScopedNullifier;
372
- const noteId = nullifier.toString();
373
-
374
- const noteBuffer = await this.#notes.getAsync(noteId);
375
- if (!noteBuffer) {
376
- // Check if already nullified (noteId === siloedNullifier, so we can check #nullifiedNotes directly)
377
- if (await this.#nullifiedNotes.hasAsync(noteId)) {
378
- throw new Error(`Nullifier already applied in applyNullifiers`);
379
- }
380
- throw new Error('Nullifier not found in applyNullifiers');
381
- }
382
-
383
- const noteScopes = await toArray(this.#notesToScope.getValuesAsync(noteId));
384
- if (noteScopes.length === 0) {
385
- // We should never run into this error because notes always have a scope assigned to them - either on initial
386
- // insertion via `addNotes` or when removing their nullifiers.
387
- throw new Error('Note scopes are missing in applyNullifiers');
388
- }
389
-
390
- const note = NoteDao.fromBuffer(noteBuffer);
391
-
392
- nullifiedNotes.push(note);
393
-
394
- await this.#notes.delete(noteId);
395
- await this.#notesToScope.delete(noteId);
358
+ #getNotesForJob(jobId: string): Map<string, StoredNote> {
359
+ let notesForJob = this.#notesForJob.get(jobId);
360
+ if (!notesForJob) {
361
+ notesForJob = new Map();
362
+ this.#notesForJob.set(jobId, notesForJob);
363
+ }
364
+ return notesForJob;
365
+ }
396
366
 
397
- const scopes = await toArray(this.#scopes.keysAsync());
367
+ async #nullifiersOfContract(contractAddress: AztecAddress, jobId: string): Promise<Set<string>> {
368
+ // Collect persisted nullifiers for this contract
369
+ const persistedNullifiers: string[] = await toArray(
370
+ this.#nullifiersByContractAddress.getValuesAsync(contractAddress.toString()),
371
+ );
398
372
 
399
- for (const scope of scopes) {
400
- await this.#notesByContractAndScope.get(scope)!.deleteValue(note.contractAddress.toString(), noteId);
401
- await this.#notesByStorageSlotAndScope.get(scope)!.deleteValue(note.storageSlot.toString(), noteId);
402
- }
373
+ // Collect staged nullifiers from the job where the note's contract matches
374
+ const stagedNullifiers = this.#getNotesForJob(jobId)
375
+ .values()
376
+ .filter(storedNote => storedNote.noteDao.contractAddress.equals(contractAddress))
377
+ .map(storedNote => storedNote.noteDao.siloedNullifier.toString());
403
378
 
404
- for (const scope of noteScopes) {
405
- await this.#nullifiedNotesToScope.set(noteId, scope);
406
- }
407
- await this.#nullifiedNotes.set(noteId, note.toBuffer());
408
- await this.#nullifiersByBlockNumber.set(blockNumber, noteId);
409
- await this.#nullifiedNotesByContract.set(note.contractAddress.toString(), noteId);
410
- await this.#nullifiedNotesByStorageSlot.set(note.storageSlot.toString(), noteId);
411
- }
412
- return nullifiedNotes;
413
- });
379
+ return new Set([...persistedNullifiers, ...stagedNullifiers]);
414
380
  }
415
381
  }