@ghostlytools/sdk 1.13.1 → 1.13.3

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 (30) hide show
  1. package/dist/{bitcoinAddress-BbPG0DF7.js → bitcoinAddress-DifDz48H.js} +254 -34
  2. package/dist/bitcoinAddress-DifDz48H.js.map +1 -0
  3. package/dist/core.js +534 -95
  4. package/dist/core.js.map +1 -1
  5. package/dist/index.js +3 -3
  6. package/dist/index.js.map +1 -1
  7. package/dist/{pairedTransports-C0I24YFz.js → pairedTransports-D8ZSZJBi.js} +22 -16
  8. package/dist/pairedTransports-D8ZSZJBi.js.map +1 -0
  9. package/dist/testing.js +2 -2
  10. package/dist/types/browser/src/proofs/contract.d.ts +2 -1
  11. package/dist/types/core/src/appStatements.d.ts +16 -0
  12. package/dist/types/core/src/canonicalJson.d.ts +9 -0
  13. package/dist/types/core/src/chatFiles.d.ts +36 -4
  14. package/dist/types/core/src/deviceInvite.d.ts +16 -2
  15. package/dist/types/core/src/didDht.d.ts +2 -1
  16. package/dist/types/core/src/engineErrors.d.ts +6 -0
  17. package/dist/types/core/src/groupCommunity.d.ts +10 -0
  18. package/dist/types/core/src/groupSession.d.ts +40 -3
  19. package/dist/types/core/src/identityProofs.d.ts +44 -2
  20. package/dist/types/core/src/link.d.ts +1 -1
  21. package/dist/types/core/src/linkPreview.d.ts +13 -1
  22. package/dist/types/core/src/linkTrace.d.ts +2 -0
  23. package/dist/types/core/src/localNames.d.ts +7 -0
  24. package/dist/types/core/src/relay.d.ts +27 -1
  25. package/dist/types/core/src/transportSwitch.d.ts +7 -3
  26. package/dist/{verify-BoVhjvc_.js → verify-DpuVYnNs.js} +2 -2
  27. package/dist/{verify-BoVhjvc_.js.map → verify-DpuVYnNs.js.map} +1 -1
  28. package/package.json +1 -1
  29. package/dist/bitcoinAddress-BbPG0DF7.js.map +0 -1
  30. package/dist/pairedTransports-C0I24YFz.js.map +0 -1
@@ -764,6 +764,10 @@ var sink = null;
764
764
  function setLinkTraceSink(next) {
765
765
  sink = next;
766
766
  }
767
+ /** Whether the lines go anywhere: costly detail is gathered only then. */
768
+ function linkTraceOn() {
769
+ return !!globalThis.__ghostlyLinkTrace || !!sink;
770
+ }
767
771
  function traceLink(me, step, detail) {
768
772
  const console_ = globalThis.__ghostlyLinkTrace;
769
773
  if (!console_ && !sink) return;
@@ -846,6 +850,26 @@ var isGroupRead = (who) => who.group && !who.write && !who.background;
846
850
  var isTurnRead = (who) => !who.write && !who.door && (who.background || !who.group);
847
851
  /** A write that goes first once the budget frees a request (see `WRITE_FIRST_MS`): a chat's or a group's, never a background one. */
848
852
  var firstWriter = (who) => !who.write || who.background ? null : who.group ? "group" : "chat";
853
+ /** A community door's read (`door`): its knock bell, its beacon and lobby while someone comes in (`DOOR_FIRST_MS`). */
854
+ var isDoorRead = (who) => who.door && !who.write;
855
+ /** Who asked, in words, for the link trace's tally of a relay's minute (`read.held`). */
856
+ var ASKER_FLAGS = [
857
+ "door",
858
+ "urgent",
859
+ "signal",
860
+ "watch",
861
+ "watchWrite",
862
+ "departed",
863
+ "awaited",
864
+ "resume",
865
+ "back",
866
+ "catchUp"
867
+ ];
868
+ var askerLabel = (who) => [
869
+ who.write ? "write" : "read",
870
+ who.background ? "background" : isChat(who) ? "chat" : "group",
871
+ ...ASKER_FLAGS.filter((flag) => who[flag])
872
+ ].join(" ");
849
873
  /** A key's turn neither asked nor read in the last minute: it is dropped, and asking again starts a new one (`TURNS_PRUNE_MS`). */
850
874
  var staleTurn = (turn, now) => now - Math.max(turn.askedAt, turn.servedAt) >= 6e4;
851
875
  /**
@@ -973,6 +997,19 @@ var BACKGROUND_WRITES_SHARE = 1 / 2;
973
997
  */
974
998
  var WRITE_FIRST_MS = 5e3;
975
999
  /**
1000
+ * A community door's read (`door`: its knock bell, and its beacon and lobby while someone comes in) the budget refused
1001
+ * on a relay goes first there when the minute frees a request: the group edges' reads of members that went away
1002
+ * (`watch`), the groups' reads at a slow pace and the background reads wait this long after the refusal, while it is not
1003
+ * read. Nor does it wait behind the packets queued for that relay (`catchUpLater`). Writes, the chats' reads and the
1004
+ * reads of a link that signals (`urgent`: an edge's, the session that lets the joiner in) do not wait for it, and it
1005
+ * takes nothing past the minute: only the order changes. A door whose edges watched the members that had just left
1006
+ * (`WATCH_SHARE`) and offered to them spent each relay's minute on them (about three quarters of it), and took a freed
1007
+ * request only when its own read came first: its bell, read every 4 to 6 s, answered the packet from before the knock
1008
+ * 3 to 6 times in a row, and a joiner waited 18 to 23 s to be let in, 5 link joins in 24, against 3 to 8 s for the
1009
+ * others (CLI lab, 2026-11-17).
1010
+ */
1011
+ var DOOR_FIRST_MS = 5e3;
1012
+ /**
976
1013
  * Once a 1:1 chat needs the relays (the budget refused one of its requests there, or it read urgently anywhere: it polls
977
1014
  * fast for a signal due any moment), group requests and background ones leave it the last this many of each minute (more
978
1015
  * for several chats, `CHAT_RESERVE_PER_CHAT`), for a minute. Groups that spend the whole budget spend it over the minute, so the chat then takes the next request that frees, within
@@ -1439,6 +1476,8 @@ var RelayTransport = class {
1439
1476
  groupsFullAt = /* @__PURE__ */ new Map();
1440
1477
  /** When a link's write was last refused on each relay (`chat <relay>`, `group <relay>`), while it waits for the budget. */
1441
1478
  writeWaiting = /* @__PURE__ */ new Map();
1479
+ /** When a community door's read was last refused on each relay, while it waits for the budget (`DOOR_FIRST_MS`). */
1480
+ doorWaiting = /* @__PURE__ */ new Map();
1442
1481
  /** Per relay, the keys whose edges' reads for an answer it last refused, and when, until one is read (`ANSWER_READ_FIRST_MS`). */
1443
1482
  answerReadWaiting = /* @__PURE__ */ new Map();
1444
1483
  /**
@@ -1463,6 +1502,11 @@ var RelayTransport = class {
1463
1502
  * (`readHeldBackFor`), how many times in a row, and since when (`READ_STARVED_MS`).
1464
1503
  */
1465
1504
  heldBack = /* @__PURE__ */ new Map();
1505
+ /**
1506
+ * Per relay, the requests of the last minute and who asked for each: kept only while the link trace is on, for the
1507
+ * tally a held-back read traces (`read.held`), which says what spent the minute it waits for.
1508
+ */
1509
+ spentBy = /* @__PURE__ */ new Map();
1466
1510
  /** When the relays last answered a read of each key, for `FRESH_READ_MS`. */
1467
1511
  readAt = /* @__PURE__ */ new Map();
1468
1512
  freshReadMs;
@@ -2060,6 +2104,7 @@ var RelayTransport = class {
2060
2104
  const resting = this.relays.every((r) => this.isCoolingDown(r, "GET") || this.breaker.blockedFor(r) > 0 || this.heldFor(r, who, Date.now(), pubKeyZ32) > 0);
2061
2105
  const known = down ? this.newest.get(pubKeyZ32) : newerPacket(this.newest.get(pubKeyZ32), this.written.get(pubKeyZ32));
2062
2106
  if (!down && budgetWait < Infinity) budgetWait = Math.max(budgetWait, this.backgroundTurnIn(pubKeyZ32, who, Date.now()));
2107
+ if (!down && budgetWait < Infinity && linkTraceOn()) this.traceHeld(pubKeyZ32, who, budgetWait, !!(resting && known));
2063
2108
  if (resting && known) {
2064
2109
  if (down && !keptOnFailure) throw new RelaysFailedError(known);
2065
2110
  if (!down && budgetWait < Infinity) this.heldBackUntil(pubKeyZ32, Date.now() + budgetWait);
@@ -2165,6 +2210,37 @@ var RelayTransport = class {
2165
2210
  const left = held === void 0 ? 0 : held.until - Date.now();
2166
2211
  return left > 0 ? left : void 0;
2167
2212
  }
2213
+ /**
2214
+ * The link trace's line for a read the budget held back (`read.held`): who asked, for how long, whether it answered
2215
+ * the packet already known, and per relay what spent the last minute (who asked, how many; the keys asked most).
2216
+ */
2217
+ traceHeld(pubKeyZ32, who, waitMs, known) {
2218
+ const now = Date.now();
2219
+ const spent = this.relays.map((relay) => {
2220
+ const list = (this.spentBy.get(relay) ?? []).filter((s) => now - s.at < 6e4);
2221
+ const by = {}, keys = {};
2222
+ for (const s of list) {
2223
+ by[s.as] = (by[s.as] ?? 0) + 1;
2224
+ keys[`${s.key} ${s.as}`] = (keys[`${s.key} ${s.as}`] ?? 0) + 1;
2225
+ }
2226
+ const background = within(this.spentBackground.get(relay) ?? [], now, 6e4).length, catchUp = this.catchUpWaiting.get(relay) ?? 0;
2227
+ return {
2228
+ n: list.length,
2229
+ background,
2230
+ catchUp,
2231
+ signaling: this.urgentAt + SIGNALING_WINDOW_MS > now,
2232
+ wait: this.heldFor(relay, who, now, pubKeyZ32, false),
2233
+ by,
2234
+ top: Object.entries(keys).sort((a, b) => b[1] - a[1]).slice(0, 6)
2235
+ };
2236
+ });
2237
+ traceLink(pubKeyZ32, "read.held", {
2238
+ as: askerLabel(who),
2239
+ waitMs,
2240
+ known,
2241
+ spent
2242
+ });
2243
+ }
2168
2244
  heldBackUntil(pubKeyZ32, until) {
2169
2245
  const held = this.heldBack.get(pubKeyZ32), times = (held?.times ?? 0) + 1;
2170
2246
  this.heldBack.delete(pubKeyZ32);
@@ -2315,6 +2391,7 @@ var RelayTransport = class {
2315
2391
  if (isGroupRead(who) && (this.spent.get(relay)?.length ?? 0) >= this.limitOf(relay)) this.groupsFullAt.set(relay, now);
2316
2392
  if (isChat(who)) this.chatNeed(key, now, relay);
2317
2393
  if (writer) this.writeWaiting.set(`${writer} ${relay}`, now);
2394
+ if (isDoorRead(who) && this.heldFor(relay, who, now, key, true, true, true) <= 0) this.doorWaiting.set(relay, now);
2318
2395
  if (isGroupAnswerRead(who)) {
2319
2396
  const waiting = this.answerReadWaiting.get(relay) ?? /* @__PURE__ */ new Map();
2320
2397
  this.answerReadWaiting.set(relay, waiting.set(key, now));
@@ -2322,6 +2399,7 @@ var RelayTransport = class {
2322
2399
  return false;
2323
2400
  }
2324
2401
  if (writer) this.writeWaiting.delete(`${writer} ${relay}`);
2402
+ if (isDoorRead(who)) this.doorWaiting.delete(relay);
2325
2403
  if (isGroupAnswerRead(who)) this.answerReadWaiting.get(relay)?.delete(key);
2326
2404
  if (isWayBack(who) && this.heldFor(relay, {
2327
2405
  ...who,
@@ -2355,6 +2433,11 @@ var RelayTransport = class {
2355
2433
  if (departedOver) this.overAdd(this.departedOver, key, now);
2356
2434
  if (isAwaitedRead(who) && this.spent.get(relay).length >= this.limitOf(relay)) this.awaitedOver = [...within(this.awaitedOver, now, 6e4), now];
2357
2435
  this.spent.get(relay).push(now);
2436
+ if (linkTraceOn()) this.spentBy.set(relay, [...(this.spentBy.get(relay) ?? []).filter((s) => now - s.at < 6e4), {
2437
+ at: now,
2438
+ as: askerLabel(who),
2439
+ key: key.slice(0, 6)
2440
+ }]);
2358
2441
  if (who.background) this.spentBackground.get(relay).push(now);
2359
2442
  if (who.background && who.write) this.spentBackgroundWrites.get(relay).push(now);
2360
2443
  if (isGroupUrgentRead(who) && isGroupAnswerRead(who)) this.spentAnswerUrgent.set(relay, [...this.spentAnswerUrgent.get(relay) ?? [], now]);
@@ -2385,9 +2468,10 @@ var RelayTransport = class {
2385
2468
  * group reads and background requests, never a chat's. Background requests yield to a link that signals. A chat's
2386
2469
  * signaling goes over the limit by its allowance (`SIGNALING_ALLOWANCE_SHARE`), and so do a few of its reads of a
2387
2470
  * contact that just went away (`DEPARTED_READS`) or of an invite awaited (`AWAITED_READS`). `ownAllowance` false: what holds an edge's read for its answer
2388
- * without its own allowance (`ANSWER_READ_ALLOWANCE`).
2471
+ * without its own allowance (`ANSWER_READ_ALLOWANCE`). `limitFree` true: all but the minute's limit and the writes
2472
+ * waiting (they go first), what still holds it once the minute frees requests (`DOOR_FIRST_MS`).
2389
2473
  */
2390
- heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true) {
2474
+ heldFor(relay, who, now = Date.now(), key, turns = true, ownAllowance = true, limitFree = false) {
2391
2475
  const recent = within(this.spent.get(relay) ?? [], now, 6e4);
2392
2476
  const recentBackground = within(this.spentBackground.get(relay) ?? [], now, 6e4);
2393
2477
  this.spent.set(relay, recent);
@@ -2405,7 +2489,7 @@ var RelayTransport = class {
2405
2489
  const groupSignaled = within(this.spentGroupSignal.get(relay) ?? [], now, 6e4);
2406
2490
  this.spentGroupSignal.set(relay, groupSignaled);
2407
2491
  const groupFloor = isGroupSignal(who) && groupSignaled.length < allowance;
2408
- let wait = groupFloor ? 0 : over(recent, limit + allowance);
2492
+ let wait = groupFloor || limitFree ? 0 : over(recent, limit + allowance);
2409
2493
  const starved = key !== void 0 && this.starved(key, who, now);
2410
2494
  const groupOver = within(this.spentGroupOver.get(relay) ?? [], now, GROUP_OVER_PACE_MS);
2411
2495
  this.spentGroupOver.set(relay, groupOver);
@@ -2413,7 +2497,7 @@ var RelayTransport = class {
2413
2497
  const backgroundShare = Math.min(this.backgroundPerMinute, Math.ceil(limit * 2 / 3));
2414
2498
  const writesShare = Math.max(1, Math.floor(backgroundShare * BACKGROUND_WRITES_SHARE));
2415
2499
  const caughtUp = this.catchUpWaiting.get(relay) ?? 0;
2416
- if (who.background && !who.write && caughtUp) {
2500
+ if (who.background && !who.write && caughtUp && !who.door) {
2417
2501
  const writesLeft = writesShare - recentBackgroundWrites.length;
2418
2502
  if (writesLeft > 0) wait = Math.max(wait, over(recent, Math.max(1, limit - writesLeft)), over(recentBackground, Math.max(1, backgroundShare - writesLeft)));
2419
2503
  }
@@ -2466,8 +2550,10 @@ var RelayTransport = class {
2466
2550
  return at !== void 0 && now - at < 5e3 ? at + WRITE_FIRST_MS - now : 0;
2467
2551
  };
2468
2552
  const signalOver = isChatSignal(who) && !who.write && recent.length >= limit;
2469
- if (writer !== "chat" && !departed && !awaited && !signalOver && !starved) wait = Math.max(wait, waiting("chat"));
2470
- if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved) wait = Math.max(wait, waiting("group"));
2553
+ if (writer !== "chat" && !departed && !awaited && !signalOver && !starved && !limitFree) wait = Math.max(wait, waiting("chat"));
2554
+ if ((writer === null && who.group && !pastLimit && !isGroupAnswerRead(who) || who.background) && !starved && !limitFree) wait = Math.max(wait, waiting("group"));
2555
+ const doorAt = this.doorWaiting.get(relay);
2556
+ if (doorAt !== void 0 && now - doorAt < 5e3 && !who.write && !who.door && (who.background || isWatch(who) || isGroupRead(who) && !who.urgent) && !starved && recentBackground.length < backgroundShare) wait = Math.max(wait, doorAt + DOOR_FIRST_MS - now);
2471
2557
  if (isGroupSignal(who) && !isGroupAnswerRead(who)) {
2472
2558
  const ahead = this.answerReadAhead(relay, now);
2473
2559
  if (ahead && this.heldFor(relay, ANSWER_READER, now, ahead.key, false, false) <= 0) wait = Math.max(wait, ahead.ms);
@@ -3081,6 +3167,19 @@ var IDENTITY_MAX_RECEIVED = 16;
3081
3167
  var IDENTITY_FRAME_LIMIT = 40;
3082
3168
  var IDENTITY_FRAME_WINDOW_MS = 6e4;
3083
3169
  /**
3170
+ * `idp-*` frames this side sends a contact per `IDENTITY_SEND_WINDOW_MS`, so that the person's own shares and stops fit
3171
+ * the contact's per-chat limits above and none is dropped unread there. Lower than the contact's count over a longer
3172
+ * window: frames can arrive closer together than they left.
3173
+ */
3174
+ var IDENTITY_SEND_LIMIT = 36;
3175
+ var IDENTITY_SEND_WINDOW_MS = 7e4;
3176
+ /**
3177
+ * A request or withdraw the contact did not answer is sent again after this (ms), twice as long each time, at most
3178
+ * `IDENTITY_RESENDS` times a connection; past that it waits for the next one, as before.
3179
+ */
3180
+ var IDENTITY_RESEND_MS = 6e4;
3181
+ var IDENTITY_RESENDS = 4;
3182
+ /**
3084
3183
  * A proof this side holds verified, presented again with the same evidence between the same keys, is answered from that
3085
3184
  * check while it is younger than this (seconds): the contact chooses how often it presents, and each check costs this
3086
3185
  * device a provider lookup (a forge's per-IP quota, a DNS query, a contact's server) and a Pkarr read. An hour keeps an
@@ -3300,14 +3399,30 @@ var identityRefusal = (error) => typeof error === "string" && (CONTACT_REFUSALS.
3300
3399
  * idp-result {id, ok, error?} verifier, after saving the outcome
3301
3400
  * idp-withdraw {id} / idp-withdrawn {id}
3302
3401
  */
3303
- var IdentityExchange = class {
3402
+ var IdentityExchange = class IdentityExchange {
3304
3403
  options;
3305
3404
  peerProviders;
3306
3405
  requested = /* @__PURE__ */ new Set();
3307
3406
  /** The nonces of the presentations in their provider's check now. */
3308
3407
  checking = /* @__PURE__ */ new Set();
3408
+ /**
3409
+ * The nonces of the challenges sent on this connection. A presentation is signed for its session, so a challenge
3410
+ * from a closed link that is not in its check now can no longer be answered.
3411
+ */
3412
+ issued = /* @__PURE__ */ new Set();
3309
3413
  /** When the contact's presentations were checked with their provider (seconds), for `IDENTITY_MAX_CHECKS_PER_HOUR`. */
3310
3414
  checks = [];
3415
+ /** When this side sent its recent frames (ms), for `IDENTITY_SEND_LIMIT`. Kept across connections, as the contact's count is. */
3416
+ sentAt = [];
3417
+ /** Hello, answers and presentations waiting for room in that window, in order (`proof`: a presentation's). */
3418
+ outbox = [];
3419
+ /**
3420
+ * This connection's request or withdraw per proof: when it (or its presentation) last went, how often, and whether its
3421
+ * presentation went. Requests and withdraws are built from the ledger when their turn comes, so one stopped or
3422
+ * answered meanwhile never goes.
3423
+ */
3424
+ attempts = /* @__PURE__ */ new Map();
3425
+ timer;
3311
3426
  constructor(options) {
3312
3427
  this.options = options;
3313
3428
  }
@@ -3329,9 +3444,111 @@ var IdentityExchange = class {
3329
3444
  audience: s.subject
3330
3445
  };
3331
3446
  }
3332
- send(frame) {
3447
+ send(frame, proof) {
3333
3448
  if (JSON.stringify(frame).length > 32768) throw new Error("Identity proof too large");
3334
- this.options.send(frame);
3449
+ if (this.outbox.length >= 40) return;
3450
+ this.outbox.push({
3451
+ frame,
3452
+ proof
3453
+ });
3454
+ this.pump();
3455
+ }
3456
+ /** Sends one frame and counts it; false when the channel is gone (what waits is sent on the next connection). */
3457
+ transmit(frame, at) {
3458
+ try {
3459
+ this.options.send(frame);
3460
+ } catch {
3461
+ this.outbox = [];
3462
+ return false;
3463
+ }
3464
+ this.sentAt.push(at);
3465
+ return true;
3466
+ }
3467
+ static resendAfter(tries) {
3468
+ return IDENTITY_RESEND_MS * 2 ** (tries - 1);
3469
+ }
3470
+ /**
3471
+ * Sends what fits the contact's limits now and sets a timer for the rest: the waiting answers first, then requests
3472
+ * (at most `MAX_CHALLENGES` open, each keeping room in the window for its presentation) and withdraws, then the
3473
+ * unanswered ones again once their time is up.
3474
+ */
3475
+ pump() {
3476
+ if (this.timer !== void 0) clearTimeout(this.timer);
3477
+ this.timer = void 0;
3478
+ const paced = this.options.paced !== false;
3479
+ const [limit, maxOpen] = paced ? [36, MAX_CHALLENGES] : [Infinity, Infinity];
3480
+ const at = Date.now();
3481
+ this.sentAt = paced ? this.sentAt.filter((t) => t > at - 7e4 && t <= at) : [];
3482
+ /** When the window has room for one more frame under `n`. */
3483
+ const roomAt = (n) => this.sentAt[this.sentAt.length - n] + IDENTITY_SEND_WINDOW_MS;
3484
+ let wake = Infinity;
3485
+ while (this.outbox.length && this.sentAt.length < limit) {
3486
+ const { frame, proof } = this.outbox.shift();
3487
+ if (!this.transmit(frame, at)) return;
3488
+ const a = proof ? this.attempts.get(proof) : void 0;
3489
+ if (a) {
3490
+ a.at = at;
3491
+ a.presented = true;
3492
+ }
3493
+ }
3494
+ if (this.outbox.length) wake = roomAt(limit);
3495
+ const shared = this.options.storage.read().shared;
3496
+ const kindOf = (s) => s.status === "queued" || s.status === "pending" ? "request" : s.status === "withdrawal-pending" ? "withdraw" : void 0;
3497
+ for (const [id, a] of this.attempts) {
3498
+ const s = shared.find((x) => x.id === id);
3499
+ if (!s || kindOf(s) !== a.kind) this.attempts.delete(id);
3500
+ }
3501
+ const dueAt = (a) => !paced || a.tries > 4 ? Infinity : a.at + IdentityExchange.resendAfter(a.tries);
3502
+ const opened = [...this.attempts.values()].filter((a) => a.kind === "request" && a.tries <= 4 && dueAt(a) > at);
3503
+ let open = opened.length;
3504
+ /** Presentations still to come for the open requests: room kept for them. */
3505
+ let owed = opened.filter((a) => !a.presented).length;
3506
+ for (const s of shared) {
3507
+ const kind = kindOf(s);
3508
+ if (!kind) continue;
3509
+ const a = this.attempts.get(s.id);
3510
+ if (a && dueAt(a) > at) {
3511
+ wake = Math.min(wake, dueAt(a));
3512
+ continue;
3513
+ }
3514
+ if (a && (!paced || a.tries > 4)) continue;
3515
+ if (kind === "request" && open >= maxOpen) continue;
3516
+ const need = kind === "request" ? 2 : 1;
3517
+ if (this.sentAt.length + owed + need > limit) {
3518
+ wake = Math.min(wake, roomAt(limit - owed - need + 1));
3519
+ break;
3520
+ }
3521
+ const frame = kind === "request" ? {
3522
+ t: "idp-request",
3523
+ id: s.id,
3524
+ provider: s.provider
3525
+ } : {
3526
+ t: "idp-withdraw",
3527
+ id: s.id
3528
+ };
3529
+ if (!this.transmit(frame, at)) return;
3530
+ if (kind === "request") {
3531
+ this.requested.add(s.id);
3532
+ open++;
3533
+ owed++;
3534
+ }
3535
+ const tries = (a?.tries ?? 0) + 1;
3536
+ this.attempts.set(s.id, {
3537
+ kind,
3538
+ at,
3539
+ tries
3540
+ });
3541
+ wake = Math.min(wake, dueAt({
3542
+ at,
3543
+ tries
3544
+ }));
3545
+ }
3546
+ if (!paced) this.sentAt = [];
3547
+ if (wake === Infinity) return;
3548
+ const timer = this.timer = setTimeout(() => {
3549
+ if (this.timer === timer) this.pump();
3550
+ }, Math.max(0, wake - at) + 1);
3551
+ timer.unref?.();
3335
3552
  }
3336
3553
  shared(id) {
3337
3554
  return this.options.storage.read().shared.find((s) => s.id === id);
@@ -3349,22 +3566,23 @@ var IdentityExchange = class {
3349
3566
  get contactProviders() {
3350
3567
  return this.peerProviders;
3351
3568
  }
3352
- /** The channel is ready: say what we verify, then send what the person queued while offline. */
3569
+ /** The channel is ready: say what we verify, then send what the person queued while offline, paced (`pump`). */
3353
3570
  ready() {
3354
3571
  this.options.scope();
3572
+ this.attempts.clear();
3355
3573
  this.send({
3356
3574
  t: "idp-hello",
3357
3575
  providers: [...this.options.providers()]
3358
3576
  });
3359
- for (const s of this.options.storage.read().shared) if (s.status === "queued" || s.status === "pending") this.request(s);
3360
- else if (s.status === "withdrawal-pending") this.send({
3361
- t: "idp-withdraw",
3362
- id: s.id
3363
- });
3364
3577
  }
3365
3578
  stop() {
3366
3579
  this.requested.clear();
3367
3580
  this.peerProviders = void 0;
3581
+ this.issued.clear();
3582
+ this.outbox = [];
3583
+ this.attempts.clear();
3584
+ if (this.timer !== void 0) clearTimeout(this.timer);
3585
+ this.timer = void 0;
3368
3586
  }
3369
3587
  /**
3370
3588
  * The challenges whose window ended unanswered go, and with them their requests' lines still verifying: a contact
@@ -3408,15 +3626,8 @@ var IdentityExchange = class {
3408
3626
  provider,
3409
3627
  subject
3410
3628
  });
3411
- if (connected) this.request(entry);
3412
- }
3413
- request(s) {
3414
- this.requested.add(s.id);
3415
- this.send({
3416
- t: "idp-request",
3417
- id: s.id,
3418
- provider: s.provider
3419
- });
3629
+ this.attempts.delete(id);
3630
+ if (connected) this.pump();
3420
3631
  }
3421
3632
  /** Stop sharing here. The contact is told (now or on reconnect); a copy it kept cannot be erased. */
3422
3633
  async withdraw(id, connected) {
@@ -3452,12 +3663,7 @@ var IdentityExchange = class {
3452
3663
  subject: s.subject,
3453
3664
  reason: "withdrawn"
3454
3665
  });
3455
- if (connected) try {
3456
- this.send({
3457
- t: "idp-withdraw",
3458
- id
3459
- });
3460
- } catch {}
3666
+ if (connected) this.pump();
3461
3667
  }
3462
3668
  /**
3463
3669
  * Run the checks again on a received proof: its revocation record, then (unless `revocationOnly`) the
@@ -3547,7 +3753,12 @@ var IdentityExchange = class {
3547
3753
  }
3548
3754
  case "idp-result": {
3549
3755
  const s = id ? this.shared(id) : void 0;
3550
- if (!s || s.status !== "pending") return;
3756
+ const asked = id ? this.attempts.get(id) : void 0;
3757
+ if (asked?.kind === "request" && s?.status === "queued") asked.tries = 5;
3758
+ if (!s || s.status !== "pending") {
3759
+ this.pump();
3760
+ return;
3761
+ }
3551
3762
  const ok = frame.ok === true;
3552
3763
  const error = ok ? void 0 : typeof frame.error === "string" && CONTACT_REFUSALS.has(frame.error) ? frame.error : CONTACT_REFUSED;
3553
3764
  const entry = {
@@ -3578,6 +3789,7 @@ var IdentityExchange = class {
3578
3789
  ok,
3579
3790
  error
3580
3791
  })));
3792
+ this.pump();
3581
3793
  return;
3582
3794
  }
3583
3795
  case "idp-withdraw": {
@@ -3645,6 +3857,11 @@ var IdentityExchange = class {
3645
3857
  id
3646
3858
  };
3647
3859
  await this.options.storage.update((l) => {
3860
+ const stale = (c) => c.id === id && !this.issued.has(c.nonce) && !this.checking.has(c.nonce);
3861
+ if (l.challenges.some(stale)) l = {
3862
+ ...l,
3863
+ challenges: l.challenges.filter((c) => !stale(c))
3864
+ };
3648
3865
  if (l.challenges.filter((c) => liveAt(c, now)).length >= MAX_CHALLENGES) throw new Error("Too many identity challenges");
3649
3866
  return this.withoutExpired(this.log({
3650
3867
  ...l,
@@ -3656,6 +3873,9 @@ var IdentityExchange = class {
3656
3873
  provider
3657
3874
  }), now);
3658
3875
  });
3876
+ const held = new Set(this.options.storage.read().challenges.map((c) => c.nonce));
3877
+ for (const n of this.issued) if (!held.has(n)) this.issued.delete(n);
3878
+ this.issued.add(challenge.nonce);
3659
3879
  this.send({
3660
3880
  t: "idp-challenge",
3661
3881
  id,
@@ -3712,7 +3932,7 @@ var IdentityExchange = class {
3712
3932
  binding: local.statement.binding,
3713
3933
  evidence: local.evidence,
3714
3934
  sig
3715
- });
3935
+ }, id);
3716
3936
  }
3717
3937
  async onPresent(frame) {
3718
3938
  const { nonce, issuedAt, binding, evidence, sig } = frame;
@@ -3922,6 +4142,6 @@ function isBitcoinAddress(address, network) {
3922
4142
  }
3923
4143
  return payload.length === 21 && BASE58_VERSIONS[network].includes(payload[0]);
3924
4144
  }
3925
- export { GROUP_BURST_ONE_LINK as $, IDENTITY_MEMO_SIZE as $t, newIdentityBinding as A, PublishFailedError as At, ANSWER_READ_SPACING_MS as B, createRelayPayload as Bt, emptyIdentityLedger as C, traceLink as Ct, identityStatement as D, BREAKER_THRESHOLD as Dt, identityRevocationValue as E, BREAKER_MAX_MS as Et, IDENTITY_TIMELINE_MAX as F, withRequestOptions as Ft, CHAT_RESERVE as G, readOwnRelayPayload as Gt, BACKGROUND_REQUESTS_PER_MINUTE as H, newerPacket as Ht, applyIdentityEvent as I, MAX_DNS_PACKET_BYTES as It, CHAT_WATCH_SHARE as J, decodeTxtPacket as Jt, CHAT_RESERVE_MOST_SHARE as K, signRelayPayload as Kt, lastSharedWithMe as L, PKARR_FUTURE_SKEW_MS as Lt, revokesIdentity as M, heldBackError as Mt, signIdentityPresentation as N, isDiscoveryBudgetError as Nt, identityStatementText as O, RelayBreaker as Ot, verifyIdentityPresentation as P, publishedNowhere as Pt, GROUP_BURST_MS as Q, IDENTITY_MEMO_MAX as Qt, ANSWER_READ_ALLOWANCE as R, PacketTooLargeError as Rt, boundVerifiedIdentity as S, setLinkTraceSink as St, identityRefusal as T, BREAKER_BASE_MS as Tt, BACKGROUND_WHILE_SIGNALING as U, openRelayPayload as Ut, AWAITED_READS as V, measureRecords as Vt, BACKGROUND_WRITES_SHARE as W, parseRelayPayload as Wt, DEPARTED_READS as X, readDnsName as Xt, DEFAULT_RELAYS as Y, encodeTxtPacket as Yt, FRESH_READ_MS as Z, IDENTITY_MEMO_IDLE_MS as Zt, IDENTITY_STATEMENT_PREFIX as _, WRITE_FIRST_MS as _t, IDENTITY_CLOCK_SKEW as a, sign as an, PREVIOUS_DEFAULT_RELAYS as at, IdentityExchange as b, readRelayBody as bt, IDENTITY_MAX_CHECKS_PER_HOUR as c, dropLoneJoiners as cn, RelayTransport as ct, IDENTITY_MAX_RECEIVED as d, sanitizeNick as dn, SIGNALING_WINDOW_MS as dt, createIdentity as en, GROUP_OVER_PACE_MS as et, IDENTITY_MAX_VALIDITY as f, stripHidden as fn, SLOW_DEMOTE_MS as ft, IDENTITY_REVOCATION_LABEL as g, WAY_BACK_SHARE as gt, IDENTITY_REUSE_CHECK_S as h, WATCH_SHARE as ht, IDENTITY_CHECK_UNAVAILABLE as i, setPublicKeyFastPath as in, HEDGE_MS as it, receivedIdentityStatus as j, budgetRetryMs as jt, isIdentityBinding as k, DiscoveryBudgetError as kt, IDENTITY_MAX_EVIDENCE as l, hasVisible as ln, RelaysFailedError as lt, IDENTITY_PROVIDER_ID as m, unwrapPasted as mn, TURN_SOURCE_TIMEOUT_MS as mt, isBitcoinAddress as n, identityFromSeedB64 as nn, GROUP_SIGNALING_ALLOWANCE_SHARE as nt, IDENTITY_FRAME_LIMIT as o, verify as on, RELAY_REQUESTS_PER_MINUTE as ot, IDENTITY_PROOF_CAPABILITY as p, trimEndOf as pn, SLOW_MS as pt, CHAT_RESERVE_PER_CHAT as q, decodeDnsAnswers as qt, IDENTITY_CHALLENGE_WINDOW as r, publicKeyFromZ32 as rn, HEDGE_MISSING_MS as rt, IDENTITY_FRAME_WINDOW_MS as s, MAX_NICK_LENGTH as sn, REQUESTS_PER_MINUTE as st, BITCOIN_NETWORKS as t, identityFromSeed as tn, GROUP_RATION_WINDOW_MS as tt, IDENTITY_MAX_FRAME as u, sanitizeDisplayText as un, SIGNALING_ALLOWANCE_SHARE as ut, IDENTITY_SUBJECT as v, currentRelays as vt, identityPresentationBytes as w, BREAKER_ALL_DOWN_PROBE_MS as wt, boundIdentityDisplay as x, relayUrlProblem as xt, IdentityCheckUnavailable as y, normalizeRelayUrl as yt, ANSWER_READ_FIRST_MS as z, RELAY_PAYLOAD_MAX_BYTES as zt };
4145
+ export { DEFAULT_RELAYS as $, decodeTxtPacket as $t, identityRevocationValue as A, BREAKER_BASE_MS as At, applyIdentityEvent as B, withRequestOptions as Bt, IdentityCheckUnavailable as C, currentRelays as Ct, emptyIdentityLedger as D, setLinkTraceSink as Dt, boundVerifiedIdentity as E, relayUrlProblem as Et, receivedIdentityStatus as F, PublishFailedError as Ft, AWAITED_READS as G, createRelayPayload as Gt, ANSWER_READ_ALLOWANCE as H, PKARR_FUTURE_SKEW_MS as Ht, revokesIdentity as I, budgetRetryMs as It, BACKGROUND_WRITES_SHARE as J, openRelayPayload as Jt, BACKGROUND_REQUESTS_PER_MINUTE as K, measureRecords as Kt, signIdentityPresentation as L, heldBackError as Lt, identityStatementText as M, BREAKER_THRESHOLD as Mt, isIdentityBinding as N, RelayBreaker as Nt, identityPresentationBytes as O, traceLink as Ot, newIdentityBinding as P, DiscoveryBudgetError as Pt, CHAT_WATCH_SHARE as Q, decodeDnsAnswers as Qt, verifyIdentityPresentation as R, isDiscoveryBudgetError as Rt, IDENTITY_SUBJECT as S, WRITE_FIRST_MS as St, boundIdentityDisplay as T, readRelayBody as Tt, ANSWER_READ_FIRST_MS as U, PacketTooLargeError as Ut, lastSharedWithMe as V, MAX_DNS_PACKET_BYTES as Vt, ANSWER_READ_SPACING_MS as W, RELAY_PAYLOAD_MAX_BYTES as Wt, CHAT_RESERVE_MOST_SHARE as X, readOwnRelayPayload as Xt, CHAT_RESERVE as Y, parseRelayPayload as Yt, CHAT_RESERVE_PER_CHAT as Z, signRelayPayload as Zt, IDENTITY_REUSE_CHECK_S as _, stripHidden as _n, SLOW_DEMOTE_MS as _t, IDENTITY_CLOCK_SKEW as a, createIdentity as an, GROUP_OVER_PACE_MS as at, IDENTITY_SEND_WINDOW_MS as b, WATCH_SHARE as bt, IDENTITY_MAX_CHECKS_PER_HOUR as c, publicKeyFromZ32 as cn, HEDGE_MISSING_MS as ct, IDENTITY_MAX_RECEIVED as d, verify as dn, RELAY_REQUESTS_PER_MINUTE as dt, encodeTxtPacket as en, DEPARTED_READS as et, IDENTITY_MAX_VALIDITY as f, MAX_NICK_LENGTH as fn, REQUESTS_PER_MINUTE as ft, IDENTITY_RESEND_MS as g, sanitizeNick as gn, SIGNALING_WINDOW_MS as gt, IDENTITY_RESENDS as h, sanitizeDisplayText as hn, SIGNALING_ALLOWANCE_SHARE as ht, IDENTITY_CHECK_UNAVAILABLE as i, IDENTITY_MEMO_SIZE as in, GROUP_BURST_ONE_LINK as it, identityStatement as j, BREAKER_MAX_MS as jt, identityRefusal as k, BREAKER_ALL_DOWN_PROBE_MS as kt, IDENTITY_MAX_EVIDENCE as l, setPublicKeyFastPath as ln, HEDGE_MS as lt, IDENTITY_PROVIDER_ID as m, hasVisible as mn, RelaysFailedError as mt, isBitcoinAddress as n, IDENTITY_MEMO_IDLE_MS as nn, FRESH_READ_MS as nt, IDENTITY_FRAME_LIMIT as o, identityFromSeed as on, GROUP_RATION_WINDOW_MS as ot, IDENTITY_PROOF_CAPABILITY as p, dropLoneJoiners as pn, RelayTransport as pt, BACKGROUND_WHILE_SIGNALING as q, newerPacket as qt, IDENTITY_CHALLENGE_WINDOW as r, IDENTITY_MEMO_MAX as rn, GROUP_BURST_MS as rt, IDENTITY_FRAME_WINDOW_MS as s, identityFromSeedB64 as sn, GROUP_SIGNALING_ALLOWANCE_SHARE as st, BITCOIN_NETWORKS as t, readDnsName as tn, DOOR_FIRST_MS as tt, IDENTITY_MAX_FRAME as u, sign as un, PREVIOUS_DEFAULT_RELAYS as ut, IDENTITY_REVOCATION_LABEL as v, trimEndOf as vn, SLOW_MS as vt, IdentityExchange as w, normalizeRelayUrl as wt, IDENTITY_STATEMENT_PREFIX as x, WAY_BACK_SHARE as xt, IDENTITY_SEND_LIMIT as y, unwrapPasted as yn, TURN_SOURCE_TIMEOUT_MS as yt, IDENTITY_TIMELINE_MAX as z, publishedNowhere as zt };
3926
4146
 
3927
- //# sourceMappingURL=bitcoinAddress-BbPG0DF7.js.map
4147
+ //# sourceMappingURL=bitcoinAddress-DifDz48H.js.map