-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsend-loop.ts
More file actions
439 lines (408 loc) · 13 KB
/
Copy pathsend-loop.ts
File metadata and controls
439 lines (408 loc) · 13 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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
/**
* Local Dev — All-countries send loop
*
* One invocation walks every country registered in .local-dev-state. For
* each country the loop runs a full cycle: deposit → COUNT sends → one
* FAILED bundle (invalid spend signature, fails at execution) → one EXPIRED
* bundle (already-expired spend signature, expires at admission) → withdraw.
*
* Prereqs: ./up.sh → ./setup-c.sh → ./setup-pp.sh
*
* Env overrides:
* COUNT default 5 normal sends per country
* INTERVAL_MS default 1000 pause between sends within a country
* SEND_AMOUNT default 1 XLM per send
* FAIL default true inject one FAILED bundle per country
* EXPIRE default true inject one EXPIRED bundle per country
* STATE_FILE default ./.local-dev-state
*/
import { Keypair } from "stellar-sdk";
import { authenticate } from "./lib/client/auth.ts";
import { waitForBundleStatus } from "./lib/client/bundle.ts";
import { loadConfig } from "./lib/client/config.ts";
import { deposit } from "./lib/client/deposit.ts";
import { prepareReceive } from "./lib/client/receive.ts";
import { send } from "./lib/client/send.ts";
import { injectExpiringBundle } from "./lib/client/expire-inject.ts";
import { injectFailingBundle } from "./lib/client/fail-inject.ts";
import { withdraw } from "./lib/client/withdraw.ts";
import { registerEntity } from "./lib/client/register-entity.ts";
const STATE_FILE = Deno.env.get("STATE_FILE") ??
new URL("./.local-dev-state", import.meta.url).pathname;
const COUNT = Number(Deno.env.get("COUNT") ?? "5");
const INTERVAL_MS = Number(Deno.env.get("INTERVAL_MS") ?? "1000");
const SEND_AMOUNT = Number(Deno.env.get("SEND_AMOUNT") ?? "1");
const WITHDRAW_AMOUNT = 0.5;
const DEPOSIT_BUFFER = 2;
// Each cycle injects one failing and one expiring bundle in addition to the
// normal sends, so dashboards always see a mix of stages. Opt out with
// FAIL=false / EXPIRE=false.
const INJECT_FAIL = (Deno.env.get("FAIL") ?? "true").toLowerCase() !== "false";
const INJECT_EXPIRE =
(Deno.env.get("EXPIRE") ?? "true").toLowerCase() !== "false";
// First-name pools per country. send-loop picks two random distinct names per
// cycle so dashboards see entity variety beyond "Alicia / Roberto".
const ENTITY_NAMES_BY_COUNTRY: Record<string, string[]> = {
// Mercosur (Spanish / Portuguese)
AR: [
"Alicia",
"Roberto",
"Carmen",
"Diego",
"Sofía",
"Mateo",
"Lucía",
"Joaquín",
],
BR: [
"Mariana",
"Pedro",
"Beatriz",
"Lucas",
"Camila",
"Felipe",
"Larissa",
"Gustavo",
],
UY: ["Valentina", "Sebastián", "Florencia", "Tomás", "Catalina", "Nicolás"],
PY: ["Carolina", "Andrés", "Daniela", "Pablo", "Verónica", "Hugo"],
// Europe
GB: [
"Emma",
"Oliver",
"Sophia",
"Harry",
"Lily",
"James",
"Charlotte",
"Henry",
],
FR: [
"Camille",
"Antoine",
"Léa",
"Hugo",
"Manon",
"Lucas",
"Clara",
"Nathan",
],
DE: ["Sophie", "Maximilian", "Anna", "Felix", "Mia", "Leon", "Emma", "Paul"],
ES: [
"Sara",
"Javier",
"Paula",
"Alejandro",
"Lucía",
"Mario",
"Marta",
"David",
],
IT: [
"Giulia",
"Lorenzo",
"Sofia",
"Matteo",
"Aurora",
"Andrea",
"Martina",
"Riccardo",
],
// North America
US: ["Emily", "Michael", "Olivia", "David", "Ava", "James", "Mia", "John"],
MX: [
"Sofía",
"Diego",
"Valentina",
"Santiago",
"Ximena",
"Mateo",
"Renata",
"Sebastián",
],
CA: ["Emma", "Liam", "Olivia", "Noah", "Ava", "Ethan", "Isabella", "Mason"],
NL: ["Daan", "Sanne", "Lars", "Fleur", "Bram", "Lotte", "Sem", "Julia"],
VE: [
"María",
"José",
"Luisa",
"Carlos",
"Gabriela",
"Andrés",
"Valentina",
"Miguel",
],
};
interface CouncilEntry {
id: string;
name: string;
channel: string;
jurisdictions: string[];
}
interface PpEntry {
index: number;
pk: string;
sk: string;
name: string;
councilIndex: number; // 1-based as stored
jurisdiction: string;
}
interface State {
COUNCIL_URL: string;
PROVIDER_URL: string;
NETWORK_PASSPHRASE?: string;
RPC_URL?: string;
FRIENDBOT_URL?: string;
ASSET_ID: string;
OPERATOR_PK?: string;
OPERATOR_SK?: string;
councils: CouncilEntry[];
pps: PpEntry[];
}
function parseStateFile(content: string): Record<string, string> {
const map: Record<string, string> = {};
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
const eq = trimmed.indexOf("=");
if (eq === -1) continue;
map[trimmed.slice(0, eq).trim()] = trimmed.slice(eq + 1).trim();
}
return map;
}
function loadState(): State {
const content = Deno.readTextFileSync(STATE_FILE);
const map = parseStateFile(content);
const councilCount = Number(map.COUNCIL_COUNT ?? "0");
if (!councilCount) {
throw new Error(
`State file ${STATE_FILE} has COUNCIL_COUNT=0. Re-run setup-c.sh.`,
);
}
const councils: CouncilEntry[] = [];
for (let i = 1; i <= councilCount; i++) {
councils.push({
id: map[`COUNCIL_${i}_ID`],
name: map[`COUNCIL_${i}_NAME`],
channel: map[`COUNCIL_${i}_CHANNEL`],
jurisdictions: (map[`COUNCIL_${i}_JURISDICTIONS`] ?? "").split(",")
.filter((j) => j),
});
}
const ppCount = Number(map.PP_COUNT ?? "0");
if (!ppCount) {
throw new Error(
`State file ${STATE_FILE} has PP_COUNT=0. Re-run setup-pp.sh.`,
);
}
const pps: PpEntry[] = [];
for (let i = 1; i <= ppCount; i++) {
pps.push({
index: i,
pk: map[`PP_${i}_PK`],
sk: map[`PP_${i}_SK`],
name: map[`PP_${i}_NAME`],
councilIndex: Number(map[`PP_${i}_COUNCIL_INDEX`]),
jurisdiction: map[`PP_${i}_JURISDICTION`],
});
}
return {
COUNCIL_URL: map.COUNCIL_URL,
PROVIDER_URL: map.PROVIDER_URL ?? "http://localhost:3010",
NETWORK_PASSPHRASE: map.NETWORK_PASSPHRASE,
RPC_URL: map.RPC_URL,
FRIENDBOT_URL: map.FRIENDBOT_URL,
ASSET_ID: map.ASSET_ID,
OPERATOR_PK: map.OPERATOR_PK,
OPERATOR_SK: map.OPERATOR_SK,
councils,
pps,
};
}
async function fund(friendbotUrl: string, publicKey: string): Promise<void> {
const res = await fetch(`${friendbotUrl}?addr=${publicKey}`);
if (!res.ok && res.status !== 400) {
throw new Error(
`Friendbot failed for ${publicKey}: ${res.status} ${await res.text()}`,
);
}
}
async function runCycleForPp(
state: State,
pp: PpEntry,
): Promise<void> {
const country = pp.jurisdiction.toUpperCase();
const council = state.councils[pp.councilIndex - 1];
if (!council) {
throw new Error(
`PP ${pp.name} references council index ${pp.councilIndex} but state only has ${state.councils.length} councils.`,
);
}
// Wire env vars that lib/client/config.ts consumes. These are mutated per
// country since each PP/council pair uses a different channel.
Deno.env.set("E2E_CHANNEL_CONTRACT_ID", council.channel);
Deno.env.set("E2E_CHANNEL_AUTH_ID", council.id);
Deno.env.set("E2E_CHANNEL_ASSET_CONTRACT_ID", state.ASSET_ID);
Deno.env.set("PROVIDER_URL", state.PROVIDER_URL);
Deno.env.set("E2E_PP_PUBLIC_KEY", pp.pk);
if (state.NETWORK_PASSPHRASE) {
Deno.env.set("STELLAR_NETWORK_PASSPHRASE", state.NETWORK_PASSPHRASE);
}
if (state.RPC_URL) Deno.env.set("STELLAR_RPC_URL", state.RPC_URL);
if (state.FRIENDBOT_URL) Deno.env.set("FRIENDBOT_URL", state.FRIENDBOT_URL);
const config = loadConfig();
console.log("\n=== local-dev — Alicia → Roberto send loop ===\n");
console.log(` Country: ${country}`);
console.log(` PP: ${pp.name}`);
console.log(` PP pubkey: ${pp.pk}`);
console.log(` Council: ${council.name}`);
console.log(` Channel: ${council.channel}`);
console.log(` Provider URL: ${state.PROVIDER_URL}`);
console.log(` Cycle: ${COUNT} sends × ${SEND_AMOUNT} XLM`);
console.log("");
// Pick two distinct random names from the country's pool.
const namePool = ENTITY_NAMES_BY_COUNTRY[country] ?? ["Alicia", "Roberto"];
const shuffled = [...namePool].sort(() => Math.random() - 0.5);
const senderFirstName = shuffled[0];
const receiverFirstName = shuffled[1] ?? shuffled[0];
const senderName = `${senderFirstName} ${country}`;
const receiverName = `${receiverFirstName} ${country}`;
const alicia = Keypair.random();
const roberto = Keypair.random();
console.log(` ${senderName}: ${alicia.publicKey()}`);
console.log(` ${receiverName}: ${roberto.publicKey()}\n`);
console.log("[1/5] Funding via Friendbot");
await fund(config.friendbotUrl, alicia.publicKey());
await fund(config.friendbotUrl, roberto.publicKey());
console.log("[2/5] Authenticating to provider");
const aliciaJwt = await authenticate(alicia, config);
const robertoJwt = await authenticate(roberto, config);
console.log("[2b/5] Registering KYC/KYB entities");
await registerEntity(
state.PROVIDER_URL,
pp.pk,
alicia,
senderName,
[country],
);
await registerEntity(
state.PROVIDER_URL,
pp.pk,
roberto,
receiverName,
[country],
);
// Deposit covers the normal sends. Both injections deposit their own
// small amounts and never draw on this balance.
const depositAmount = SEND_AMOUNT * COUNT + DEPOSIT_BUFFER;
console.log(`[3/6] ${senderName} depositing ${depositAmount} XLM`);
await deposit(alicia.secret(), depositAmount, aliciaJwt, config);
console.log(`[4/6] Sending ${COUNT} bundles, ${INTERVAL_MS}ms apart\n`);
for (let i = 1; i <= COUNT; i++) {
const startedAt = Date.now();
const receiverOps = await prepareReceive(
roberto.secret(),
SEND_AMOUNT,
config,
);
await send(
alicia.secret(),
receiverOps,
SEND_AMOUNT,
aliciaJwt,
config,
);
console.log(
` ${i}/${COUNT} sent ${SEND_AMOUNT} XLM ${Date.now() - startedAt}ms`,
);
if (i < COUNT) {
await new Promise((r) => setTimeout(r, INTERVAL_MS));
}
}
if (INJECT_FAIL) {
// Deposit a small amount, then submit a balanced SPEND signed with the
// wrong UTXO keypair. Admission accepts it (sums are fine, signature is
// present); the on-chain contract rejects the signature at execution.
// Wait for the FAILED landing before moving on — while this bundle is
// pending, anything sharing its slot would fail with it.
console.log("\n[5/6] Injecting one FAILED bundle (invalid signature)");
try {
const bundleId = await injectFailingBundle(
alicia.secret(),
aliciaJwt,
config,
);
console.log(` submitted ${bundleId}, waiting for FAILED…`);
await waitForBundleStatus(aliciaJwt, bundleId, config, "FAILED");
console.log(` landed FAILED as expected`);
} catch (err) {
console.log(` fail injection raised: ${(err as Error).message}`);
}
}
if (INJECT_EXPIRE) {
// Submit a balanced bundle whose spend signature has already expired.
// The platform derives bundle TTL from signature expirations, so it is
// expired at admission through the platform's ordinary TTL path — no
// database access from this script.
console.log("\n[5/6] Injecting one EXPIRED bundle (expired signature)");
try {
const bundleId = await injectExpiringBundle(
alicia.secret(),
aliciaJwt,
config,
);
console.log(` submitted ${bundleId}, waiting for EXPIRED…`);
await waitForBundleStatus(aliciaJwt, bundleId, config, "EXPIRED", 15_000);
console.log(` landed EXPIRED as expected`);
} catch (err) {
console.log(` expire injection raised: ${(err as Error).message}`);
}
}
console.log(`\n[6/6] ${receiverName} withdrawing ${WITHDRAW_AMOUNT} XLM`);
await withdraw(
roberto.secret(),
roberto.publicKey(),
WITHDRAW_AMOUNT,
robertoJwt,
config,
);
console.log("\n=== Done ===");
}
async function main(): Promise<void> {
const state = loadState();
const totalStart = Date.now();
const failures: { country: string; error: string }[] = [];
console.log(
`\n=== local-dev — all-countries send loop (${state.pps.length} countries) ===\n`,
);
for (let i = 0; i < state.pps.length; i++) {
const pp = state.pps[i];
const country = pp.jurisdiction.toUpperCase();
console.log(`\n──── [${i + 1}/${state.pps.length}] ${country} ────`);
try {
await runCycleForPp(state, pp);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.error(` Cycle failed for ${country}: ${message}`);
failures.push({ country, error: message });
}
}
const elapsedS = ((Date.now() - totalStart) / 1000).toFixed(1);
console.log(
`\n=== Complete in ${elapsedS}s — ${
state.pps.length - failures.length
}/${state.pps.length} countries OK ===`,
);
if (failures.length > 0) {
console.error("Failures:");
for (const f of failures) {
console.error(` ${f.country}: ${f.error}`);
}
Deno.exit(1);
}
}
main().catch((err) => {
console.error("\n=== Send loop FAILED ===");
console.error(err);
Deno.exit(1);
});