forked from Dshield-xyz/Dshield
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindexer.ts
More file actions
237 lines (210 loc) · 7.34 KB
/
Copy pathindexer.ts
File metadata and controls
237 lines (210 loc) · 7.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import * as StellarSdk from "@stellar/stellar-sdk";
import { getRpcServer, POOL_CONTRACT_ID, queryContract } from "./stellar";
import { saveDeposit, getDeposits } from "./deposits";
/**
* Fetch the complete, ordered list of commitments directly from the pool
* contract's storage (via the `get_commitments` view). This is the
* authoritative source for rebuilding the Merkle tree — unlike scanning
* deposit events, it does not depend on RPC event retention, so it always
* returns every leaf the contract has inserted.
*
* Returns commitments as 0x-prefixed 32-byte hex strings in leaf-index order,
* or null if the call fails (e.g. an older pool deployment without the view).
*/
export async function fetchCommitmentsFromChain(
poolId?: string,
): Promise<string[] | null> {
const targetPool = poolId || POOL_CONTRACT_ID;
if (!targetPool) return null;
const result = await queryContract(targetPool, "get_commitments");
if (!result) return null;
const native = StellarSdk.scValToNative(result) as unknown;
if (!Array.isArray(native)) return null;
return native.map((buf: unknown) => {
const bytes = Buffer.from(buf as Uint8Array);
return "0x" + bytes.toString("hex").padStart(64, "0");
});
}
export interface NoteTxRefs {
depositTx: { hash: string; at: string } | null;
withdrawTx: { hash: string; at: string } | null;
}
/**
* Best-effort lookup of the on-chain transactions that touched a note, for the
* compliance report: the deposit tx that inserted `commitmentHex`, and the
* withdraw tx that spent `nullifierHashHex` (if any). Both are derived purely
* from public events — anyone holding the note can reproduce them. Returns
* nulls for whatever the RPC's event retention can't reach; the report falls
* back to the authoritative contract views (get_commitments / is_nullifier_used)
* for the confirmed/withdrawn facts, so missing tx links never block a report.
*/
export async function lookupNoteTxs(
poolId: string,
commitmentHex: string,
nullifierHashHex: string,
): Promise<NoteTxRefs> {
const server = getRpcServer();
const wantCommitment = commitmentHex.replace(/^0x/, "").toLowerCase();
const wantNullifier = nullifierHashHex.replace(/^0x/, "").toLowerCase();
const refs: NoteTxRefs = { depositTx: null, withdrawTx: null };
let startLedger = 1;
let cursor: string | undefined;
let triedRetentionFallback = false;
let hasMore = true;
while (hasMore && (!refs.depositTx || !refs.withdrawTx)) {
let response: StellarSdk.rpc.Api.GetEventsResponse;
try {
const filters = [{ type: "contract" as const, contractIds: [poolId] }];
const opts = cursor
? { filters, cursor, limit: 100 }
: { filters, startLedger, limit: 100 };
response = await server.getEvents(opts);
} catch {
if (!cursor && !triedRetentionFallback) {
triedRetentionFallback = true;
try {
const latest = await server.getLatestLedger();
startLedger = Math.max(1, latest.sequence - 17280);
continue;
} catch {
break;
}
}
break;
}
const events = response.events || [];
for (const event of events) {
try {
if (!event.topic || event.topic.length < 1) continue;
const kind = StellarSdk.scValToNative(event.topic[0]) as string;
if (kind === "deposit" && !refs.depositTx) {
const dataMap = StellarSdk.scValToNative(event.value) as Record<
string,
unknown
>;
if (dataMap && typeof dataMap === "object" && "commitment" in dataMap) {
const hex = Buffer.from(dataMap.commitment as Uint8Array)
.toString("hex")
.toLowerCase();
if (hex === wantCommitment) {
refs.depositTx = {
hash: event.txHash,
at: event.ledgerClosedAt,
};
}
}
} else if (kind === "withdraw" && !refs.withdrawTx) {
const val = StellarSdk.scValToNative(event.value);
const hex = Buffer.from(val as Uint8Array)
.toString("hex")
.toLowerCase();
if (hex === wantNullifier) {
refs.withdrawTx = { hash: event.txHash, at: event.ledgerClosedAt };
}
}
} catch {
continue;
}
}
if (events.length < 100) {
hasMore = false;
} else {
cursor = events[events.length - 1].id;
}
}
return refs;
}
export async function syncDepositsFromChain(
poolId?: string,
): Promise<number> {
const targetPool = poolId || POOL_CONTRACT_ID;
if (!targetPool) return 0;
const server = getRpcServer();
const existingDeposits = getDeposits().filter(
(d) => !d.poolId || d.poolId === targetPool,
);
const knownIndices = new Set(existingDeposits.map((d) => d.leafIndex));
let synced = 0;
let cursor: string | undefined;
// Reconstructing the Merkle tree requires EVERY deposit, so scan from the
// start of the chain rather than a recent window. On a network whose event
// retention does not reach ledger 1, the getEvents call below will throw and
// we fall back to the largest window the RPC allows.
let startLedger = 1;
try {
const latest = await server.getLatestLedger();
if (latest.sequence > 0 && startLedger > latest.sequence) {
startLedger = latest.sequence;
}
} catch {
startLedger = 1;
}
let hasMore = true;
let triedRetentionFallback = false;
while (hasMore) {
let response: StellarSdk.rpc.Api.GetEventsResponse;
try {
const filters = [
{
type: "contract" as const,
contractIds: [targetPool],
topics: [["AAAADwAAAAdkZXBvc2l0AA==", "*"]],
},
];
const opts = cursor
? { filters, cursor, limit: 100 }
: { filters, startLedger, limit: 100 };
response = await server.getEvents(opts);
} catch {
// A start ledger older than the RPC's event retention window throws.
// Retry once from the most recent window the RPC is likely to keep.
if (!cursor && !triedRetentionFallback) {
triedRetentionFallback = true;
try {
const latest = await server.getLatestLedger();
startLedger = Math.max(1, latest.sequence - 17280);
continue;
} catch {
break;
}
}
break;
}
const events = response.events || [];
for (const event of events) {
try {
if (!event.topic || event.topic.length < 2) continue;
const idxScVal = event.topic[1];
const leafIndex = StellarSdk.scValToNative(idxScVal) as number;
if (knownIndices.has(leafIndex)) continue;
const dataMap = StellarSdk.scValToNative(event.value) as Record<
string,
unknown
>;
let commitment: string;
if (dataMap && typeof dataMap === "object" && "commitment" in dataMap) {
const buf = dataMap.commitment as Buffer;
commitment = Buffer.from(buf).toString("hex");
} else {
continue;
}
saveDeposit({
commitment,
leafIndex,
timestamp: Date.now(),
poolId: targetPool,
});
knownIndices.add(leafIndex);
synced++;
} catch {
continue;
}
}
if (events.length < 100) {
hasMore = false;
} else {
cursor = events[events.length - 1].id;
}
}
return synced;
}