@t3foundry/tasra-sdk 0.3.1 → 0.4.0
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.
- package/CHANGELOG.md +1067 -28
- package/README.md +15 -0
- package/dist/app/approvals.d.ts +66 -4
- package/dist/app/approvals.js +153 -16
- package/dist/app/authorization.d.ts +1 -1
- package/dist/app/authorization.js +1 -1
- package/dist/app/browser.d.ts +63 -0
- package/dist/app/browser.js +242 -0
- package/dist/app/client.d.ts +114 -13
- package/dist/app/client.js +302 -76
- package/dist/app/identity.js +21 -9
- package/dist/app/index.d.ts +28 -3
- package/dist/app/index.js +16 -1
- package/dist/app/memory-store.d.ts +7 -0
- package/dist/app/memory-store.js +55 -0
- package/dist/app/node.d.ts +34 -6
- package/dist/app/node.js +387 -64
- package/dist/app/paid-allowance.d.ts +325 -0
- package/dist/app/paid-allowance.js +1290 -0
- package/dist/app/paid-approval.d.ts +122 -0
- package/dist/app/paid-approval.js +379 -0
- package/dist/app/paid-journal.d.ts +51 -0
- package/dist/app/paid-journal.js +117 -0
- package/dist/app/paid-keys.d.ts +12 -0
- package/dist/app/paid-keys.js +20 -0
- package/dist/app/paid-operation.d.ts +821 -0
- package/dist/app/paid-operation.js +1720 -0
- package/dist/app/paid-reservation.d.ts +157 -0
- package/dist/app/paid-reservation.js +323 -0
- package/dist/app/paid-session.d.ts +147 -0
- package/dist/app/paid-session.js +578 -0
- package/dist/app/payer-queue.d.ts +11 -0
- package/dist/app/payer-queue.js +27 -0
- package/dist/app/policy-bootstrap.d.ts +342 -0
- package/dist/app/policy-bootstrap.js +365 -0
- package/dist/app/policy-operation.d.ts +47 -0
- package/dist/app/policy-operation.js +101 -0
- package/dist/app/ready-slot.d.ts +12 -0
- package/dist/app/ready-slot.js +5 -2
- package/dist/app/rotation-lock.d.ts +38 -0
- package/dist/app/rotation-lock.js +42 -0
- package/dist/app/session-decrypt.d.ts +135 -0
- package/dist/app/session-decrypt.js +335 -0
- package/dist/app/session-grants.d.ts +349 -0
- package/dist/app/session-grants.js +811 -0
- package/dist/app/signing-intents.d.ts +78 -0
- package/dist/app/signing-intents.js +95 -0
- package/dist/app/store-commit.d.ts +63 -0
- package/dist/app/store-commit.js +126 -0
- package/dist/app/store-errors.d.ts +8 -0
- package/dist/app/store-errors.js +11 -0
- package/dist/app/tasra-client.d.ts +2 -0
- package/dist/app/tasra-client.js +1 -1
- package/dist/app/wallet.js +4 -1
- package/dist/auth/holderProof.d.ts +3 -0
- package/dist/auth/holderProof.js +8 -7
- package/dist/auth/verifier.d.ts +4 -2
- package/dist/auth/verifier.js +5 -2
- package/dist/chain/abis/index.d.ts +6178 -4101
- package/dist/chain/abis/index.js +3 -0
- package/dist/chain/abis/keyRegistry.d.ts +256 -0
- package/dist/chain/abis/keyRegistry.js +333 -0
- package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
- package/dist/chain/abis/prepaidFaultOracle.js +413 -0
- package/dist/chain/abis/settlement.d.ts +2203 -703
- package/dist/chain/abis/settlement.js +2685 -764
- package/dist/chain/allowance.d.ts +358 -0
- package/dist/chain/allowance.js +800 -0
- package/dist/chain/billing.d.ts +85 -0
- package/dist/chain/billing.js +197 -0
- package/dist/chain/chainId.d.ts +13 -0
- package/dist/chain/chainId.js +26 -0
- package/dist/chain/client.d.ts +15 -1
- package/dist/chain/client.js +57 -1
- package/dist/chain/commitmentRecovery.d.ts +51 -0
- package/dist/chain/commitmentRecovery.js +38 -0
- package/dist/chain/committeeClient.d.ts +17 -10
- package/dist/chain/committeeClient.js +64 -16
- package/dist/chain/committeeDraw.d.ts +12 -0
- package/dist/chain/committeeDraw.js +56 -0
- package/dist/chain/custodyHealth.d.ts +212 -0
- package/dist/chain/custodyHealth.js +365 -0
- package/dist/chain/deployments.js +2 -0
- package/dist/chain/events.js +2 -0
- package/dist/chain/headFollower.d.ts +77 -0
- package/dist/chain/headFollower.js +219 -0
- package/dist/chain/headPrefetch.d.ts +23 -0
- package/dist/chain/headPrefetch.js +67 -0
- package/dist/chain/index.d.ts +50 -8
- package/dist/chain/index.js +28 -3
- package/dist/chain/keeperExecution.d.ts +44 -0
- package/dist/chain/keeperExecution.js +127 -0
- package/dist/chain/keeperRecovery.d.ts +78 -0
- package/dist/chain/keeperRecovery.js +91 -0
- package/dist/chain/node.d.ts +24 -1
- package/dist/chain/node.js +88 -43
- package/dist/chain/offchain.d.ts +2 -0
- package/dist/chain/paidAgentTransport.d.ts +38 -0
- package/dist/chain/paidAgentTransport.js +1 -0
- package/dist/chain/paidEpoch.d.ts +66 -0
- package/dist/chain/paidEpoch.js +139 -0
- package/dist/chain/paidPacing.d.ts +81 -0
- package/dist/chain/paidPacing.js +136 -0
- package/dist/chain/pinnedReads.d.ts +49 -0
- package/dist/chain/pinnedReads.js +218 -0
- package/dist/chain/prepaid.d.ts +383 -0
- package/dist/chain/prepaid.js +1046 -0
- package/dist/chain/prepaidEscape.d.ts +274 -0
- package/dist/chain/prepaidEscape.js +432 -0
- package/dist/chain/prepaidFault.d.ts +94 -0
- package/dist/chain/prepaidFault.js +148 -0
- package/dist/chain/receipt.d.ts +24 -0
- package/dist/chain/receipt.js +82 -0
- package/dist/chain/registeredAgent.d.ts +68 -3
- package/dist/chain/registeredAgent.js +143 -42
- package/dist/chain/registeredOperation.d.ts +10 -1
- package/dist/chain/registeredOperation.js +18 -3
- package/dist/chain/registeredPaidAgent.d.ts +254 -0
- package/dist/chain/registeredPaidAgent.js +889 -0
- package/dist/chain/registeredRelay.d.ts +31 -1
- package/dist/chain/registeredRelay.js +164 -43
- package/dist/chain/relayVoucher.d.ts +64 -0
- package/dist/chain/relayVoucher.js +69 -0
- package/dist/chain/reservation.d.ts +239 -0
- package/dist/chain/reservation.js +746 -0
- package/dist/chain/reshareRoster.d.ts +64 -0
- package/dist/chain/reshareRoster.js +85 -0
- package/dist/chain/revertReason.d.ts +8 -0
- package/dist/chain/revertReason.js +2 -1
- package/dist/chain/rotationLock.d.ts +130 -0
- package/dist/chain/rotationLock.js +168 -0
- package/dist/chain/serviceRequestPolicy.d.ts +47 -0
- package/dist/chain/serviceRequestPolicy.js +86 -0
- package/dist/chain/services.d.ts +7 -0
- package/dist/chain/services.js +44 -4
- package/dist/chain/slotClient.js +11 -2
- package/dist/chain/slotHandoff.d.ts +81 -0
- package/dist/chain/slotHandoff.js +166 -0
- package/dist/chain/slotSeed.d.ts +47 -5
- package/dist/chain/slotSeed.js +173 -42
- package/dist/chain/verifierSnapshot.d.ts +36 -0
- package/dist/chain/verifierSnapshot.js +197 -0
- package/dist/chain/write.d.ts +111 -21
- package/dist/chain/write.js +378 -146
- package/dist/committee/blsSharing.d.ts +53 -0
- package/dist/committee/blsSharing.js +90 -0
- package/dist/committee/client.d.ts +62 -23
- package/dist/committee/client.js +288 -72
- package/dist/committee/dual-operation.d.ts +165 -0
- package/dist/committee/dual-operation.js +229 -0
- package/dist/committee/dual-sign.d.ts +26 -1
- package/dist/committee/dual-sign.js +85 -7
- package/dist/committee/ecdsa.d.ts +38 -0
- package/dist/committee/ecdsa.js +87 -15
- package/dist/committee/evidence.d.ts +30 -0
- package/dist/committee/evidence.js +65 -0
- package/dist/committee/execution.d.ts +414 -0
- package/dist/committee/execution.js +446 -0
- package/dist/committee/extraction.js +33 -26
- package/dist/committee/index.d.ts +30 -7
- package/dist/committee/index.js +18 -6
- package/dist/committee/keeperExecution.d.ts +37 -0
- package/dist/committee/keeperExecution.js +141 -0
- package/dist/committee/oauth.d.ts +14 -4
- package/dist/committee/oauth.js +17 -5
- package/dist/committee/payment.d.ts +369 -0
- package/dist/committee/payment.js +339 -0
- package/dist/committee/recovery.d.ts +136 -0
- package/dist/committee/recovery.js +204 -0
- package/dist/committee/recoveryJson.d.ts +2 -0
- package/dist/committee/recoveryJson.js +87 -0
- package/dist/committee/request.d.ts +63 -27
- package/dist/committee/request.js +77 -66
- package/dist/committee/session-grant.d.ts +320 -0
- package/dist/committee/session-grant.js +397 -0
- package/dist/committee/status-refresh.d.ts +257 -0
- package/dist/committee/status-refresh.js +619 -0
- package/dist/committee/token.d.ts +163 -15
- package/dist/committee/token.js +247 -10
- package/dist/crypto/bn254.d.ts +70 -0
- package/dist/crypto/bn254.js +222 -0
- package/dist/crypto/ibe.d.ts +32 -0
- package/dist/crypto/ibe.js +56 -8
- package/dist/crypto/index.d.ts +1 -1
- package/dist/crypto/index.js +1 -1
- package/dist/crypto/kem.d.ts +31 -0
- package/dist/crypto/kem.js +113 -7
- package/dist/crypto/recipient.d.ts +75 -0
- package/dist/crypto/recipient.js +107 -0
- package/dist/decryption/client.d.ts +10 -16
- package/dist/decryption/client.js +8 -76
- package/dist/decryption/index.d.ts +2 -0
- package/dist/decryption/index.js +2 -0
- package/dist/decryption/sealed.d.ts +72 -0
- package/dist/decryption/sealed.js +147 -0
- package/dist/decryption/session.d.ts +115 -0
- package/dist/decryption/session.js +358 -0
- package/dist/errors.d.ts +406 -1
- package/dist/errors.js +400 -5
- package/dist/index.d.ts +9 -2
- package/dist/index.js +6 -1
- package/dist/internal/bounded.d.ts +66 -0
- package/dist/internal/bounded.js +126 -0
- package/dist/internal/network.d.ts +4 -0
- package/dist/internal/network.js +40 -0
- package/dist/internal/retryAfter.d.ts +8 -0
- package/dist/internal/retryAfter.js +28 -0
- package/dist/internal/sleep.d.ts +6 -0
- package/dist/internal/sleep.js +15 -0
- package/dist/internal/typedData.d.ts +13 -0
- package/dist/internal/typedData.js +77 -0
- package/dist/internal/viemErrors.d.ts +26 -0
- package/dist/internal/viemErrors.js +49 -0
- package/dist/oid4vp/binding.d.ts +27 -1
- package/dist/oid4vp/binding.js +36 -1
- package/dist/oid4vp/jose.d.ts +4 -2
- package/dist/oid4vp/jose.js +39 -7
- package/dist/oid4vp/request-object.d.ts +61 -4
- package/dist/oid4vp/request-object.js +140 -5
- package/dist/oid4vp/verifier-agent.d.ts +18 -8
- package/dist/oid4vp/verifier-agent.js +48 -6
- package/dist/oid4vp/wallet.d.ts +2 -4
- package/dist/oid4vp/wallet.js +1 -0
- package/dist/retry.d.ts +78 -0
- package/dist/retry.js +137 -0
- package/dist/signing/frost.d.ts +1 -1
- package/dist/verifier-agent/index.d.ts +41 -5
- package/dist/verifier-agent/index.js +124 -9
- package/dist/verifier-agent/payment.d.ts +7 -0
- package/dist/verifier-agent/payment.js +17 -0
- package/docs/api.md +8 -2
- package/docs/application-api.md +25 -2
- package/docs/chain.md +155 -9
- package/docs/consumer-migrations.md +61 -0
- package/docs/encrypted-notes.md +3 -2
- package/docs/encryption.md +4 -2
- package/docs/errors.md +14 -1
- package/docs/flows.md +2 -2
- package/docs/funding.md +902 -0
- package/docs/native-approvals.md +63 -0
- package/docs/reference/README.md +9 -8
- package/docs/reference/app-browser.md +232 -0
- package/docs/reference/app-node.md +38 -8
- package/docs/reference/app.md +4621 -805
- package/docs/reference/chain-node.md +74 -16
- package/docs/reference/chain.md +6740 -1592
- package/docs/reference/committee.md +5630 -987
- package/docs/reference/main.md +1439 -140
- package/docs/reference/oid4vp.md +297 -144
- package/docs/reference/verifier-agent.md +77 -35
- package/docs/signing.md +6 -0
- package/examples/encrypted-notes.ts +21 -6
- package/examples/getting-started.ts +2 -7
- package/examples/live-config.ts +24 -17
- package/package.json +17 -5
|
@@ -0,0 +1,1290 @@
|
|
|
1
|
+
// ADR-0090 D1-D5, application side: a pool of allowance LANES per slot, so a paid operation is
|
|
2
|
+
// debited by an accountant-quorum voucher instead of waiting for its own on-chain reservation.
|
|
3
|
+
//
|
|
4
|
+
// lane = one allowance at a time (+ one reserved ahead) and a strictly serial `seq`.
|
|
5
|
+
//
|
|
6
|
+
// - L lanes (default min(streams, 8)) let L voucher rounds run at once; each lane's rounds are
|
|
7
|
+
// serialized by the store lock of that lane, so `seq` never forks.
|
|
8
|
+
// - The lane journal is written BEFORE a voucher is requested: (allowance, seq, request, payment,
|
|
9
|
+
// quote block), then the verified partials, then the aggregate. A resume therefore asks for the
|
|
10
|
+
// SAME seq and request at the SAME quote block; a member that already journaled them answers with
|
|
11
|
+
// its stored, deterministic partial. The aggregate is also saved under the request
|
|
12
|
+
// (`pav-<request>`) before the lane advances, so the operation finds it after any crash.
|
|
13
|
+
// - Allowances are fixed-amount. A replacement is reserved in the background once the current
|
|
14
|
+
// one's remainder is below 25 % of its amount or less than 10 minutes of its life remain, and it
|
|
15
|
+
// takes over when the current one can no longer fund an operation.
|
|
16
|
+
// - A definite refusal (every member that did not sign refused; none was unreachable) retires the
|
|
17
|
+
// lane: its seq may be claimed at some members by a request that can now never complete. The
|
|
18
|
+
// operation then falls back to a per-operation reservation (paid-operation.ts). Unreachable
|
|
19
|
+
// members leave the debit pending for the same seq and request.
|
|
20
|
+
// - Every aggregated voucher is pushed to every accountant in the background
|
|
21
|
+
// (`POST .../vouchers`, fire-and-forget, bounded). Members learn a seq's aggregate from the next
|
|
22
|
+
// debit's `previous`, but the LAST seq of a lane is nobody's `previous`, and which seq is last is
|
|
23
|
+
// unknowable when it is made (the lane may retire, the allowance expire, the process stop), so
|
|
24
|
+
// each one is pushed; the push is one small idempotent request per member. The outcome is
|
|
25
|
+
// journaled per allowance (`pap-<allowance>`): a retiring lane or an allowance close to expiry
|
|
26
|
+
// re-pushes its last voucher once to the members that did not acknowledge it. A push never
|
|
27
|
+
// blocks or fails an operation.
|
|
28
|
+
//
|
|
29
|
+
// - ADR-0090 D7 draw lanes: a session grant's messages pay its exact verifier draw (the keeper
|
|
30
|
+
// refuses any other), which follows the beacon every epoch, while a regular lane keeps its
|
|
31
|
+
// allowance's draw. Two sets of draw lanes per slot (lane `DRAW_LANE_BASE + (epoch % 2) x 8 + j`)
|
|
32
|
+
// hold one allowance on one draw each: the set of the grant's epoch serves its messages, the
|
|
33
|
+
// other is reserved for the next draw as soon as a message sees the beacon there (through a
|
|
34
|
+
// pinned, verified discovery), replacing the draw two epochs back, which no keeper admits any
|
|
35
|
+
// more. A message whose draw has no lane waits (bounded) for the reservation running for it.
|
|
36
|
+
// Every draw-lane allowance is counted, before anything is broadcast, until its expiry plus the
|
|
37
|
+
// accountants' close grace; at `maxDrawAllowances` per slot a message pays per operation.
|
|
38
|
+
//
|
|
39
|
+
// Reservations use the dedicated gas payer under the same durable payer claim as per-operation
|
|
40
|
+
// reservations (paid-reservation.ts), and the same in-process payer queue.
|
|
41
|
+
//
|
|
42
|
+
// Capability discovery: none exists on the network for allowances, so the path is enabled only by
|
|
43
|
+
// the explicit `PaidOperationConfig.allowances` option (D5: readers first; the application asserts
|
|
44
|
+
// every reader on the deployment is at the ADR-0090 version).
|
|
45
|
+
import { keccak256, toHex } from 'viem';
|
|
46
|
+
import { allowanceActionBits, allowanceFunds, ALLOWANCE_ACTIONS, prepaidAllowanceIntentTypedData, prepaidRequestId } from '../committee/payment.js';
|
|
47
|
+
import { collectDebitVoucher, DebitVoucherError, prepaidAllowanceId, pushDebitVoucher, reconcilePrepaidAllowance, reservePrepaidAllowance, ALLOWANCE_MAX_LIFETIME_SECS } from '../chain/allowance.js';
|
|
48
|
+
import { accountantEndpoints, PaidReservationUncertainError } from '../chain/reservation.js';
|
|
49
|
+
import { TasraError } from '../errors.js';
|
|
50
|
+
import { withDedicatedPayer } from './payer-queue.js';
|
|
51
|
+
import { releaseApplicationPayerClaim, withApplicationPayerClaim } from './paid-reservation.js';
|
|
52
|
+
import { HEX32, paidRecordKey } from './paid-keys.js';
|
|
53
|
+
import { headFollowerOf } from '../chain/headFollower.js';
|
|
54
|
+
import { saveAll, withCommit } from './store-commit.js';
|
|
55
|
+
/** Remainder fraction (numerator / 4) below which a replacement is reserved ahead. */
|
|
56
|
+
const LOW_REMAINDER_QUARTERS = 1n;
|
|
57
|
+
/** Remaining life below which a replacement is reserved ahead, seconds. */
|
|
58
|
+
const LOW_LIFE_SECS = 600;
|
|
59
|
+
/** An operation must expire at least this long before its allowance (clock skew), seconds. */
|
|
60
|
+
const EXPIRY_MARGIN_SECS = 30;
|
|
61
|
+
/** A pending debit's quote block is re-chosen (when no member signed yet) after this age, seconds. */
|
|
62
|
+
const QUOTE_REUSE_SECS = 20;
|
|
63
|
+
const MAX_LANES = 8;
|
|
64
|
+
const MAX_RETIRED = 16;
|
|
65
|
+
/**
|
|
66
|
+
* Draw lanes (session grants): lane indices `DRAW_LANE_BASE + (epoch % 2) * MAX_LANES + j`, j < lanes.
|
|
67
|
+
* Keepers admit a session grant only at the beacon's latest or previous epoch, so at most two draws
|
|
68
|
+
* are ever wanted at once: one lane set per epoch parity, re-reserved (the stale draw retired)
|
|
69
|
+
* every second epoch.
|
|
70
|
+
*/
|
|
71
|
+
const DRAW_LANE_BASE = MAX_LANES;
|
|
72
|
+
/** The accountants' default close grace after `expiresAt` (`DEFAULT_CLOSE_GRACE_SECS`): an allowance's escrow is locked until about then. */
|
|
73
|
+
const CLOSE_GRACE_SECS = 600;
|
|
74
|
+
/** A reserve-ahead for a draw is not attempted again within this time after one ran (ms). */
|
|
75
|
+
const AHEAD_RETRY_MS = 5_000;
|
|
76
|
+
/** The allowance path cannot fund this operation; nothing more will be requested for it. Fall back to a per-operation reservation. */
|
|
77
|
+
export class AllowanceRefusedError extends TasraError {
|
|
78
|
+
/** Stable reason. */
|
|
79
|
+
code = 'allowance-refused';
|
|
80
|
+
constructor(message, cause) { super(message, { retryable: false, cause }); }
|
|
81
|
+
}
|
|
82
|
+
/** Accountants were unreachable: the debit stays pending for the same seq and request; resume retries it. */
|
|
83
|
+
export class AllowanceUnavailableError extends TasraError {
|
|
84
|
+
/** Stable reason. */
|
|
85
|
+
code = 'allowance-unavailable';
|
|
86
|
+
constructor(message, cause) { super(message, { retryable: true, cause }); }
|
|
87
|
+
}
|
|
88
|
+
const now = () => Math.floor(Date.now() / 1000);
|
|
89
|
+
const same = (a, b) => a.toLowerCase() === b.toLowerCase();
|
|
90
|
+
/**
|
|
91
|
+
* Validate the allowance options against the operation limits.
|
|
92
|
+
* @param options - Allowance options.
|
|
93
|
+
* @param limits - Operation limits.
|
|
94
|
+
*/
|
|
95
|
+
export function validateAllowanceOptions(options, limits) {
|
|
96
|
+
if (!options || typeof options !== 'object' || options.enabled !== true)
|
|
97
|
+
throw new TasraError('Allowance funding needs an explicit enabled: true');
|
|
98
|
+
const cap = options.maxOpCost ?? limits.maxCost;
|
|
99
|
+
if (typeof options.amount !== 'bigint' || options.amount <= 0n || options.amount >= 1n << 256n || typeof cap !== 'bigint' || cap <= 0n || cap > options.amount
|
|
100
|
+
|| limits.maxCost > options.amount)
|
|
101
|
+
throw new TasraError('Allowance amount must be positive and cover the per-operation cap');
|
|
102
|
+
const life = options.lifetimeSecs ?? ALLOWANCE_MAX_LIFETIME_SECS;
|
|
103
|
+
if (!Number.isSafeInteger(life) || life < 900 || life > ALLOWANCE_MAX_LIFETIME_SECS)
|
|
104
|
+
throw new TasraError('Allowance lifetime must be 900..3600 seconds');
|
|
105
|
+
if (options.actions)
|
|
106
|
+
allowanceActionBits(options.actions);
|
|
107
|
+
if (options.streams !== undefined && (!Number.isSafeInteger(options.streams) || options.streams < 1))
|
|
108
|
+
throw new TasraError('Allowance streams must be a positive integer');
|
|
109
|
+
if (options.lanes !== undefined && (!Number.isSafeInteger(options.lanes) || options.lanes < 1 || options.lanes > MAX_LANES))
|
|
110
|
+
throw new TasraError('Allowance lanes must be 1..8');
|
|
111
|
+
const timeout = options.debitTimeoutMs ?? 15_000;
|
|
112
|
+
if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 60_000)
|
|
113
|
+
throw new TasraError('Invalid allowance debit timeout');
|
|
114
|
+
if (options.drawAmount !== undefined && (typeof options.drawAmount !== 'bigint' || options.drawAmount >= 1n << 256n || options.drawAmount < cap
|
|
115
|
+
|| limits.maxCost > options.drawAmount))
|
|
116
|
+
throw new TasraError('Allowance draw amount must cover the per-operation cap');
|
|
117
|
+
if (options.maxDrawAllowances !== undefined && (!Number.isSafeInteger(options.maxDrawAllowances) || options.maxDrawAllowances < 1
|
|
118
|
+
|| options.maxDrawAllowances > 1024))
|
|
119
|
+
throw new TasraError('Allowance maxDrawAllowances must be 1..1024');
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Lane count: `lanes`, else min(streams, 8).
|
|
123
|
+
* @param options - Allowance options.
|
|
124
|
+
*/
|
|
125
|
+
export function allowanceLaneCount(options) {
|
|
126
|
+
return options.lanes ?? Math.min(options.streams ?? 1, MAX_LANES);
|
|
127
|
+
}
|
|
128
|
+
function laneKey(d, slot, lane) {
|
|
129
|
+
const scope = keccak256(toHex(`${d.chainId}:${d.settlement.toLowerCase()}:${slot.toLowerCase()}`)).slice(2, 34);
|
|
130
|
+
return `pal-${scope}-${lane}`;
|
|
131
|
+
}
|
|
132
|
+
function voucherKey(requestId) {
|
|
133
|
+
if (!HEX32.test(requestId))
|
|
134
|
+
throw new TasraError('Invalid request ID');
|
|
135
|
+
return `pav-${requestId.slice(2).toLowerCase()}`;
|
|
136
|
+
}
|
|
137
|
+
async function loadLane(store, key, lane, slot) {
|
|
138
|
+
const state = await store.load(key);
|
|
139
|
+
if (state === undefined)
|
|
140
|
+
return { schema: 1, lane, slot };
|
|
141
|
+
if (!state || state.schema !== 1 || state.lane !== lane || !same(state.slot, slot))
|
|
142
|
+
throw new TasraError('Invalid allowance lane journal');
|
|
143
|
+
return state;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* The aggregated voucher journaled for a request, if any.
|
|
147
|
+
* @param store - Application store.
|
|
148
|
+
* @param requestId - Operation request ID.
|
|
149
|
+
*/
|
|
150
|
+
export async function journaledAllowanceVoucher(store, requestId) {
|
|
151
|
+
const saved = await store.load(voucherKey(requestId));
|
|
152
|
+
if (saved === undefined)
|
|
153
|
+
return undefined;
|
|
154
|
+
if (!saved || saved.schema !== 1 || !same(saved.voucher.request_id, requestId))
|
|
155
|
+
throw new TasraError('Invalid journaled debit voucher');
|
|
156
|
+
return saved.voucher;
|
|
157
|
+
}
|
|
158
|
+
const remaining = (c) => BigInt(c.intent.amount) - BigInt(c.cumulative);
|
|
159
|
+
function low(c) {
|
|
160
|
+
if (!c)
|
|
161
|
+
return true;
|
|
162
|
+
const amount = BigInt(c.intent.amount);
|
|
163
|
+
return remaining(c) * 4n < amount * LOW_REMAINDER_QUARTERS || c.intent.expires_at - now() < LOW_LIFE_SECS;
|
|
164
|
+
}
|
|
165
|
+
function sameSharing(fields, intent) {
|
|
166
|
+
const a = fields.keeper_assignment, b = intent.keeper_assignment;
|
|
167
|
+
const key = (k) => toHex(Uint8Array.from(k));
|
|
168
|
+
return fields.chain_id === intent.chain_id && same(fields.settlement, intent.settlement) && same(fields.slot, intent.slot)
|
|
169
|
+
&& a.key_epoch === b.key_epoch && a.committee_version === b.committee_version && a.threshold === b.threshold
|
|
170
|
+
&& a.contributors.length === b.contributors.length && a.contributors.every((k, i) => key(k) === key(b.contributors[i]));
|
|
171
|
+
}
|
|
172
|
+
/** The verifier draw an allowance's vouchers name (all six fields: the payment copies them from the allowance). */
|
|
173
|
+
function sameDraw(fields, intent) {
|
|
174
|
+
return fields.verification_epoch === intent.verification_epoch && same(fields.verification_seed, intent.verification_seed)
|
|
175
|
+
&& same(fields.verification_root, intent.verification_root) && fields.verification_registry_size === intent.verification_registry_size
|
|
176
|
+
&& fields.verification_committee === intent.verification_committee && fields.verification_quorum === intent.verification_quorum;
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Does an allowance (its balance and pending debits aside) fund `action` for an operation expiring
|
|
180
|
+
* at `expires`, under `context`'s keeper sharing (and exactly its verifier draw when `drawPinned`)?
|
|
181
|
+
* The one predicate both lane selection ({@link usable}) and readiness ({@link LaneWork}) apply.
|
|
182
|
+
*/
|
|
183
|
+
function serves(intent, context, action, expires, drawPinned = false) {
|
|
184
|
+
return allowanceFunds(intent.actions, action) && intent.expires_at >= expires + EXPIRY_MARGIN_SECS && sameSharing(context.intentFields, intent)
|
|
185
|
+
// An undrawn context has no draw: it never serves a pinned draw.
|
|
186
|
+
&& (!drawPinned || (context.undrawn !== true && sameDraw(context.intentFields, intent)));
|
|
187
|
+
}
|
|
188
|
+
/** Can this lane's current allowance fund one more operation (without asking anyone)? */
|
|
189
|
+
function usable(c, env, context, action, expires, drawPinned = false) {
|
|
190
|
+
return c !== undefined && c.phase === 'confirmed' && c.pending === undefined && remaining(c) >= env.limits.maxCost
|
|
191
|
+
&& serves(c.intent, context, action, expires, drawPinned);
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* A confirmed allowance that will soon stop funding operations like `operation` (by the time its
|
|
195
|
+
* payment would expire it is within {@link LOW_LIFE_SECS} of the allowance's own expiry), or one on
|
|
196
|
+
* a keeper sharing the slot no longer has: reserve its replacement ahead, exactly as for a `low()`
|
|
197
|
+
* one. Without it a current allowance whose life fell below the payment lifetime plus the margin
|
|
198
|
+
* (but above `low()`'s bound) could fund no operation and started no replacement either: every
|
|
199
|
+
* operation on it paid per operation.
|
|
200
|
+
*/
|
|
201
|
+
function endingFor(c, context, operation) {
|
|
202
|
+
return c.intent.expires_at - EXPIRY_MARGIN_SECS - operation.expires < LOW_LIFE_SECS || !sameSharing(context.intentFields, c.intent);
|
|
203
|
+
}
|
|
204
|
+
/** Voucher rounds running or queued in this process, per lane (advisory: the store lock is what serializes). */
|
|
205
|
+
const busyRounds = new Map();
|
|
206
|
+
const busy = {
|
|
207
|
+
has: (key) => (busyRounds.get(key) ?? 0) > 0,
|
|
208
|
+
add: (key) => { busyRounds.set(key, (busyRounds.get(key) ?? 0) + 1); },
|
|
209
|
+
delete: (key) => { const n = (busyRounds.get(key) ?? 0) - 1; if (n > 0)
|
|
210
|
+
busyRounds.set(key, n);
|
|
211
|
+
else
|
|
212
|
+
busyRounds.delete(key); },
|
|
213
|
+
};
|
|
214
|
+
/**
|
|
215
|
+
* Lanes handed out by a selection in this process whose voucher round has not started yet: lane key
|
|
216
|
+
* to the expiry times (ms) of those claims. Advisory, exactly like `busy`: it only spreads concurrent
|
|
217
|
+
* selections over a slot's lanes. Without it every selection running at once read the same cursor
|
|
218
|
+
* and the same idle lanes (the debit's pending journal is written only once its round starts, after
|
|
219
|
+
* the payment is signed and journaled), so they all took ONE lane and their voucher rounds, each a
|
|
220
|
+
* full accountant round trip under that lane's lock, ran one after another. A claim is consumed when
|
|
221
|
+
* a round on its lane starts and otherwise lapses after {@link CLAIM_MS}; nothing is refused on it
|
|
222
|
+
* (the store lock and the lane journal decide what may be debited).
|
|
223
|
+
*/
|
|
224
|
+
const claims = new Map();
|
|
225
|
+
const CLAIM_MS = 30_000;
|
|
226
|
+
const MAX_CLAIMS_PER_LANE = 1024;
|
|
227
|
+
function liveClaims(key) {
|
|
228
|
+
const at = Date.now(), live = (claims.get(key) ?? []).filter(until => until > at);
|
|
229
|
+
if (live.length > 0)
|
|
230
|
+
claims.set(key, live);
|
|
231
|
+
else
|
|
232
|
+
claims.delete(key);
|
|
233
|
+
return live;
|
|
234
|
+
}
|
|
235
|
+
/** In-process work on a lane: selections not yet debiting plus voucher rounds running or queued. */
|
|
236
|
+
function laneLoad(key) {
|
|
237
|
+
return liveClaims(key).length + (busyRounds.get(key) ?? 0);
|
|
238
|
+
}
|
|
239
|
+
function claimLane(key) {
|
|
240
|
+
const live = liveClaims(key);
|
|
241
|
+
if (live.length < MAX_CLAIMS_PER_LANE)
|
|
242
|
+
claims.set(key, [...live, Date.now() + CLAIM_MS]);
|
|
243
|
+
}
|
|
244
|
+
function consumeClaim(key) {
|
|
245
|
+
const live = liveClaims(key);
|
|
246
|
+
if (live.length > 0) {
|
|
247
|
+
live.shift();
|
|
248
|
+
if (live.length > 0)
|
|
249
|
+
claims.set(key, live);
|
|
250
|
+
else
|
|
251
|
+
claims.delete(key);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
/** Background reservations running in this process, per lane. Bounded by lanes x slots in use. */
|
|
255
|
+
const refilling = new Map();
|
|
256
|
+
/** The draw each running reservation reserves on (keyed like `refilling`). */
|
|
257
|
+
const refillingDraw = new Map();
|
|
258
|
+
const MAX_REFILLING = 256;
|
|
259
|
+
/** How long an operation with no usable lane waits for this slot's in-flight lane reservation. */
|
|
260
|
+
const LANE_WAIT_MS = 20_000;
|
|
261
|
+
/** Most times {@link prepareAllowanceLane} waits for a lane reservation already running before it gives up. */
|
|
262
|
+
const PREPARE_ROUNDS = 8;
|
|
263
|
+
const cursors = new Map();
|
|
264
|
+
/**
|
|
265
|
+
* Pick a lane whose current allowance can fund this operation, or undefined (fall back to a
|
|
266
|
+
* per-operation reservation). Starts background reservations for missing or low lanes. When no
|
|
267
|
+
* lane can fund it but one of this slot's lanes is being reserved in this process, waits for that
|
|
268
|
+
* reservation (at most {@link LANE_WAIT_MS}) and selects once more: a per-operation reservation
|
|
269
|
+
* would queue behind it on the same gas payer, so the fallback costs a second transaction and at
|
|
270
|
+
* least twice the wait (long enough, under contention, to outlive the verifier epoch it signed).
|
|
271
|
+
* @param env - Allowance environment.
|
|
272
|
+
* @param context - Fresh discovery for this operation.
|
|
273
|
+
* @param operation - The paid action and the payment expiry.
|
|
274
|
+
*/
|
|
275
|
+
export async function selectAllowanceLane(env, context, operation) {
|
|
276
|
+
// An undrawn context (a new epoch's anchors are landing) only selects a lane whose current
|
|
277
|
+
// allowance serves the operation now: it waits for nothing and starts no reservation (it has no
|
|
278
|
+
// draw to reserve on). A pinned draw needs that draw: never from it.
|
|
279
|
+
if (context.undrawn)
|
|
280
|
+
return operation.drawPinned ? undefined : selectLane(env, context, operation);
|
|
281
|
+
const select = async () => await selectLane(env, context, operation) ?? (operation.drawPinned ? selectDrawLane(env, context, operation) : undefined);
|
|
282
|
+
const chosen = await select();
|
|
283
|
+
// A session message on the previous epoch while the beacon is already at the next: reserve the
|
|
284
|
+
// next draw's lanes now, so the messages after the grant's refresh find them ready.
|
|
285
|
+
if (operation.drawPinned)
|
|
286
|
+
reserveAheadForBeacon(env, context);
|
|
287
|
+
if (chosen)
|
|
288
|
+
return chosen;
|
|
289
|
+
const slot = context.intentFields.slot, lanes = allowanceLaneCount(env.options), draw = context.intentFields;
|
|
290
|
+
// What this operation can be funded from once it lands: any regular lane reservation, or for a
|
|
291
|
+
// pinned draw only those on exactly its draw, its draw lanes and a reserve-ahead for it (whose
|
|
292
|
+
// discovery runs before any of its lanes is refilling).
|
|
293
|
+
const relevant = () => {
|
|
294
|
+
const inFlight = [];
|
|
295
|
+
for (let lane = 0; lane < lanes; lane++) {
|
|
296
|
+
const key = laneKey(env.deployment, slot, lane), work = refilling.get(key), on = refillingDraw.get(key);
|
|
297
|
+
if (work && (!operation.drawPinned || (on && sameDraw(draw, on))))
|
|
298
|
+
inFlight.push(work);
|
|
299
|
+
}
|
|
300
|
+
if (operation.drawPinned) {
|
|
301
|
+
for (let j = 0; j < lanes; j++) {
|
|
302
|
+
const work = refilling.get(laneKey(env.deployment, slot, drawLaneIndex(draw.verification_epoch, j)));
|
|
303
|
+
if (work)
|
|
304
|
+
inFlight.push(work);
|
|
305
|
+
}
|
|
306
|
+
const ahead = aheads.get(aheadKey(env.deployment, slot, draw.verification_epoch));
|
|
307
|
+
if (ahead)
|
|
308
|
+
inFlight.push(ahead);
|
|
309
|
+
}
|
|
310
|
+
return inFlight;
|
|
311
|
+
};
|
|
312
|
+
const inFlight = relevant();
|
|
313
|
+
if (inFlight.length === 0)
|
|
314
|
+
return undefined;
|
|
315
|
+
// Select once more as each of them ends; the first selection that finds a lane wins. Only the
|
|
316
|
+
// reservations running NOW are waited for (one a re-selection starts is not), within the bound.
|
|
317
|
+
let timer;
|
|
318
|
+
const found = new Promise(resolve => {
|
|
319
|
+
let left = inFlight.length;
|
|
320
|
+
const done = (ticket) => { if (ticket)
|
|
321
|
+
resolve(ticket);
|
|
322
|
+
else if (--left === 0)
|
|
323
|
+
resolve(undefined); };
|
|
324
|
+
for (const work of inFlight)
|
|
325
|
+
work.then(select).then(done, () => done(undefined));
|
|
326
|
+
});
|
|
327
|
+
try {
|
|
328
|
+
return await Promise.race([found, new Promise(resolve => { timer = setTimeout(() => resolve(undefined), LANE_WAIT_MS); })]);
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
clearTimeout(timer);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
/** The draw lane `j` of the lane set for `epoch`'s parity. */
|
|
335
|
+
function drawLaneIndex(epoch, j) {
|
|
336
|
+
return DRAW_LANE_BASE + (epoch % 2) * MAX_LANES + j;
|
|
337
|
+
}
|
|
338
|
+
function aheadKey(d, slot, epoch) {
|
|
339
|
+
return `${laneKey(d, slot, 0)}:draw:${epoch}`;
|
|
340
|
+
}
|
|
341
|
+
/** Draw-lane allowances one lane may hold (locked escrow), from `maxDrawAllowances` over every draw lane of the slot. */
|
|
342
|
+
function heldPerDrawLane(options) {
|
|
343
|
+
const lanes = allowanceLaneCount(options);
|
|
344
|
+
return Math.max(1, Math.floor((options.maxDrawAllowances ?? 4 * lanes) / (2 * lanes)));
|
|
345
|
+
}
|
|
346
|
+
/** A draw lane's allowance on this draw that needs no replacement. */
|
|
347
|
+
function drawGood(c, draw) {
|
|
348
|
+
return c !== undefined && c.phase === 'confirmed' && sameDraw(draw, c.intent) && !low(c);
|
|
349
|
+
}
|
|
350
|
+
/** Does draw lane `s` need a reservation for `draw` (nothing good on it, nothing confirmed reserved ahead for it)? */
|
|
351
|
+
function drawNeeds(s, draw) {
|
|
352
|
+
return !drawGood(s.current, draw) && !(s.next?.phase === 'confirmed' && sameDraw(draw, s.next.intent));
|
|
353
|
+
}
|
|
354
|
+
/**
|
|
355
|
+
* Session grants: a session operation's lane on its exact draw, among the draw lanes (the regular
|
|
356
|
+
* lanes were tried first and are never retired for a session). A miss starts one draw-lane
|
|
357
|
+
* reservation for this draw (the caller then waits for it, bounded); a lane whose current
|
|
358
|
+
* allowance runs low reserves its replacement on the same draw in the background.
|
|
359
|
+
*/
|
|
360
|
+
async function selectDrawLane(env, context, operation) {
|
|
361
|
+
const slot = context.intentFields.slot, lanes = allowanceLaneCount(env.options), draw = context.intentFields, epoch = draw.verification_epoch;
|
|
362
|
+
const scope = `${laneKey(env.deployment, slot, 0)}:draw`, start = cursors.get(scope) ?? 0;
|
|
363
|
+
const candidates = [];
|
|
364
|
+
for (let i = 0; i < lanes; i++)
|
|
365
|
+
candidates.push((start + i) % lanes);
|
|
366
|
+
candidates.sort((a, b) => laneLoad(laneKey(env.deployment, slot, drawLaneIndex(epoch, a))) - laneLoad(laneKey(env.deployment, slot, drawLaneIndex(epoch, b))));
|
|
367
|
+
let chosen;
|
|
368
|
+
let needy;
|
|
369
|
+
// As in {@link selectLane}: a fitting lane with in-process work is taken only when no idle one fits.
|
|
370
|
+
let loaded;
|
|
371
|
+
const take = async (j, lane, key, current) => {
|
|
372
|
+
chosen = { lane, allowanceId: current.id, fields: fieldsFor(current.intent, context) };
|
|
373
|
+
cursors.set(scope, (j + 1) % lanes);
|
|
374
|
+
claimLane(key);
|
|
375
|
+
// Low on the draw it serves: its replacement on the same draw, in the background.
|
|
376
|
+
if (env.options.reserveAhead !== false && drawNeeds(await loadLane(env.store, key, lane, slot), draw))
|
|
377
|
+
void refillDrawLane(env, context, j);
|
|
378
|
+
};
|
|
379
|
+
for (const j of candidates) {
|
|
380
|
+
const lane = drawLaneIndex(epoch, j), key = laneKey(env.deployment, slot, lane);
|
|
381
|
+
let state = await loadLane(env.store, key, lane, slot);
|
|
382
|
+
if (state.current?.pending && !busy.has(key))
|
|
383
|
+
state = await completeInterruptedAdvance(env, key, lane, slot, state);
|
|
384
|
+
if (state.current?.phase === 'confirmed' && state.current.seq > 0 && state.current.intent.expires_at - now() < LOW_LIFE_SECS)
|
|
385
|
+
repushLast(env, state.current);
|
|
386
|
+
const fits = usable(state.current, env, context, operation.action, operation.expires, true);
|
|
387
|
+
if (!chosen && fits && laneLoad(key) > 0) {
|
|
388
|
+
if (!loaded || laneLoad(key) < laneLoad(loaded.key))
|
|
389
|
+
loaded = { j, lane, key, current: state.current };
|
|
390
|
+
}
|
|
391
|
+
else if (!chosen && (fits || (state.next?.phase === 'confirmed' && sameDraw(draw, state.next.intent) && !state.current?.pending))) {
|
|
392
|
+
const current = fits ? state.current : await promoteDraw(env, key, lane, slot, context, operation);
|
|
393
|
+
if (current && !chosen)
|
|
394
|
+
await take(j, lane, key, current);
|
|
395
|
+
}
|
|
396
|
+
else if (needy === undefined && drawNeeds(state, draw) && !refilling.has(key))
|
|
397
|
+
needy = j;
|
|
398
|
+
}
|
|
399
|
+
if (!chosen && loaded)
|
|
400
|
+
await take(loaded.j, loaded.lane, loaded.key, loaded.current);
|
|
401
|
+
// One reservation per miss, and none when a regular lane is already being reserved on this very
|
|
402
|
+
// draw (the selection before this one started it): the caller waits for that one instead.
|
|
403
|
+
let regular = false;
|
|
404
|
+
for (let lane = 0; lane < lanes; lane++) {
|
|
405
|
+
const d = refillingDraw.get(laneKey(env.deployment, slot, lane));
|
|
406
|
+
if (d && sameDraw(draw, d))
|
|
407
|
+
regular = true;
|
|
408
|
+
}
|
|
409
|
+
if (!chosen && needy !== undefined && !regular && env.options.reserveAhead !== false)
|
|
410
|
+
void refillDrawLane(env, context, needy);
|
|
411
|
+
return chosen;
|
|
412
|
+
}
|
|
413
|
+
/** Swap in a draw lane's allowance reserved on this draw when the current one cannot fund the operation. */
|
|
414
|
+
async function promoteDraw(env, key, lane, slot, context, operation) {
|
|
415
|
+
return env.store.withLock(key, async () => {
|
|
416
|
+
const state = await loadLane(env.store, key, lane, slot);
|
|
417
|
+
if (usable(state.current, env, context, operation.action, operation.expires, true))
|
|
418
|
+
return state.current;
|
|
419
|
+
if (state.current?.pending || state.next?.phase !== 'confirmed' || !sameDraw(context.intentFields, state.next.intent))
|
|
420
|
+
return undefined;
|
|
421
|
+
const next = { ...state.next, seq: 0, cumulative: '0' };
|
|
422
|
+
if (!usable(next, env, context, operation.action, operation.expires, true))
|
|
423
|
+
return undefined;
|
|
424
|
+
await env.store.save(key, { ...state, current: next, next: undefined, retired: retire(state) });
|
|
425
|
+
repushLast(env, state.current);
|
|
426
|
+
return next;
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
/** Start (once per lane in this process) a background draw-lane reservation on `context`'s (verified) draw. */
|
|
430
|
+
function refillDrawLane(env, context, j) {
|
|
431
|
+
const lane = drawLaneIndex(context.intentFields.verification_epoch, j), key = laneKey(env.deployment, context.intentFields.slot, lane);
|
|
432
|
+
const running = refilling.get(key);
|
|
433
|
+
if (running)
|
|
434
|
+
return running;
|
|
435
|
+
if (refilling.size >= MAX_REFILLING)
|
|
436
|
+
return Promise.resolve();
|
|
437
|
+
const work = reserveOnLane(env, context, lane, drawPlan(env, context)).then(() => { }, () => { }).finally(() => { refilling.delete(key); refillingDraw.delete(key); });
|
|
438
|
+
refilling.set(key, work);
|
|
439
|
+
refillingDraw.set(key, context.intentFields);
|
|
440
|
+
return work;
|
|
441
|
+
}
|
|
442
|
+
/** Reserve-ahead attempts per (slot, draw epoch) in this process: the running job, or when the last one ended. */
|
|
443
|
+
const aheads = new Map();
|
|
444
|
+
const aheadDone = new Map();
|
|
445
|
+
const MAX_AHEADS = 256;
|
|
446
|
+
/**
|
|
447
|
+
* (a) A session operation pinned to epoch `e` while the beacon is at `e + 1`: the grant moves to
|
|
448
|
+
* `e + 1` next, and its messages then need lanes on that draw. Discover it (a fresh, verified,
|
|
449
|
+
* pinned discovery: never a draw from anywhere else) and reserve as many of its draw lanes as
|
|
450
|
+
* `e`'s draw lanes have in use (at least one), in the background. Never blocks or fails the operation.
|
|
451
|
+
*/
|
|
452
|
+
function reserveAheadForBeacon(env, context) {
|
|
453
|
+
const epoch = context.intentFields.verification_epoch, beacon = context.beaconEpoch, slot = context.intentFields.slot;
|
|
454
|
+
if (env.options.reserveAhead === false || !env.discover || beacon === undefined || beacon !== BigInt(epoch) + 1n)
|
|
455
|
+
return;
|
|
456
|
+
const next = epoch + 1, key = aheadKey(env.deployment, slot, next), at = Date.now();
|
|
457
|
+
if (aheads.has(key) || at - (aheadDone.get(key) ?? -Infinity) < AHEAD_RETRY_MS || aheads.size >= MAX_AHEADS)
|
|
458
|
+
return;
|
|
459
|
+
const discover = env.discover, lanes = allowanceLaneCount(env.options);
|
|
460
|
+
const work = (async () => {
|
|
461
|
+
let inUse = 0;
|
|
462
|
+
for (let j = 0; j < lanes; j++) {
|
|
463
|
+
const s = await loadLane(env.store, laneKey(env.deployment, slot, drawLaneIndex(epoch, j)), drawLaneIndex(epoch, j), slot);
|
|
464
|
+
if (s.current?.phase === 'confirmed' && sameDraw(context.intentFields, s.current.intent))
|
|
465
|
+
inUse = j + 1;
|
|
466
|
+
}
|
|
467
|
+
const wanted = [];
|
|
468
|
+
for (let j = 0; j < Math.max(1, inUse); j++) {
|
|
469
|
+
const lane = drawLaneIndex(next, j), s = await loadLane(env.store, laneKey(env.deployment, slot, lane), lane, slot);
|
|
470
|
+
// Its draw is unknown until discovered; a lane already good on SOME draw of epoch `next` is that draw's.
|
|
471
|
+
if (!(s.current?.phase === 'confirmed' && s.current.intent.verification_epoch === next && !low(s.current))
|
|
472
|
+
&& !(s.next?.phase === 'confirmed' && s.next.intent.verification_epoch === next))
|
|
473
|
+
wanted.push(j);
|
|
474
|
+
}
|
|
475
|
+
if (wanted.length === 0)
|
|
476
|
+
return;
|
|
477
|
+
const drawn = await discover(slot, BigInt(next));
|
|
478
|
+
if (drawn.undrawn || drawn.intentFields.verification_epoch !== next || !same(drawn.intentFields.slot, slot) || drawn.intentFields.chain_id !== env.deployment.chainId
|
|
479
|
+
|| !same(drawn.intentFields.settlement, env.deployment.settlement))
|
|
480
|
+
return;
|
|
481
|
+
await Promise.all(wanted.map(j => refillDrawLane(env, drawn, j)));
|
|
482
|
+
})().catch(() => { }).finally(() => { aheads.delete(key); aheadDone.set(key, Date.now()); if (aheadDone.size > MAX_AHEADS)
|
|
483
|
+
aheadDone.delete(aheadDone.keys().next().value); });
|
|
484
|
+
aheads.set(key, work);
|
|
485
|
+
}
|
|
486
|
+
async function selectLane(env, context, operation) {
|
|
487
|
+
const slot = context.intentFields.slot, lanes = allowanceLaneCount(env.options), scope = laneKey(env.deployment, slot, 0);
|
|
488
|
+
const start = cursors.get(scope) ?? 0;
|
|
489
|
+
let chosen;
|
|
490
|
+
const candidates = [];
|
|
491
|
+
for (let i = 0; i < lanes; i++)
|
|
492
|
+
candidates.push((start + i) % lanes);
|
|
493
|
+
// Lanes idle in this process first; a busy one only serializes behind its round.
|
|
494
|
+
candidates.sort((a, b) => laneLoad(laneKey(env.deployment, slot, a)) - laneLoad(laneKey(env.deployment, slot, b)));
|
|
495
|
+
// A lane that fits but already carries in-process work (judged at the moment of choosing, after
|
|
496
|
+
// this selection's own reads, so selections running at once see each other's claims): taken only
|
|
497
|
+
// when no idle lane fits, the least loaded first.
|
|
498
|
+
let loaded;
|
|
499
|
+
const take = (lane, key, current) => {
|
|
500
|
+
chosen = { lane, allowanceId: current.id, fields: fieldsFor(current.intent, context) };
|
|
501
|
+
cursors.set(scope, (lane + 1) % lanes);
|
|
502
|
+
claimLane(key);
|
|
503
|
+
};
|
|
504
|
+
for (const lane of candidates) {
|
|
505
|
+
const key = laneKey(env.deployment, slot, lane);
|
|
506
|
+
let state = await loadLane(env.store, key, lane, slot);
|
|
507
|
+
// A lane held by a debit whose voucher is already journaled (a stop between that journal and
|
|
508
|
+
// the lane commit) is completed here, asking nobody: no selection would ever run a round on it.
|
|
509
|
+
if (state.current?.pending && !busy.has(key))
|
|
510
|
+
state = await completeInterruptedAdvance(env, key, lane, slot, state);
|
|
511
|
+
if (env.options.reserveAhead !== false && !state.next && !context.undrawn
|
|
512
|
+
&& (low(state.current) || state.current?.phase !== 'confirmed' || endingFor(state.current, context, operation)))
|
|
513
|
+
refillLane(env, context, lane, operation);
|
|
514
|
+
// Close to expiry the current allowance may see no further debit: make sure its last voucher reached the members.
|
|
515
|
+
if (state.current?.phase === 'confirmed' && state.current.seq > 0 && state.current.intent.expires_at - now() < LOW_LIFE_SECS)
|
|
516
|
+
repushLast(env, state.current);
|
|
517
|
+
// A pinned draw never promotes: retiring a current allowance only because its draw is not this
|
|
518
|
+
// session's would strand its balance for every other operation.
|
|
519
|
+
const fits = usable(state.current, env, context, operation.action, operation.expires, operation.drawPinned);
|
|
520
|
+
if (!chosen && fits && laneLoad(key) > 0) {
|
|
521
|
+
if (!loaded || laneLoad(key) < laneLoad(loaded.key))
|
|
522
|
+
loaded = { lane, key, current: state.current };
|
|
523
|
+
}
|
|
524
|
+
else if (!chosen && (fits || (!operation.drawPinned && state.next?.phase === 'confirmed' && !state.current?.pending))) {
|
|
525
|
+
const current = fits ? state.current : await promote(env, key, lane, slot, context, operation);
|
|
526
|
+
if (current && !chosen)
|
|
527
|
+
take(lane, key, current);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
if (!chosen && loaded)
|
|
531
|
+
take(loaded.lane, loaded.key, loaded.current);
|
|
532
|
+
return chosen;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Complete a lane advance interrupted after its voucher was journaled (`pav-` or the operation's
|
|
536
|
+
* `reserved`, see {@link completedVoucher}): the advance, the voucher under its request and the
|
|
537
|
+
* push journal in one commit under the lane and push locks, exactly what the round's own lane
|
|
538
|
+
* commit would have published; then the push, in the background. A pending debit without a
|
|
539
|
+
* journaled voucher, a lane that moved meanwhile or a failure leaves the lane as it was (its own
|
|
540
|
+
* operation's resume still completes it).
|
|
541
|
+
*/
|
|
542
|
+
async function completeInterruptedAdvance(env, key, lane, slot, seen) {
|
|
543
|
+
const store = env.store, allowance = seen.current.id;
|
|
544
|
+
try {
|
|
545
|
+
if (!(seen.current.pending.voucher ?? await completedVoucher(store, seen.current.pending)))
|
|
546
|
+
return seen;
|
|
547
|
+
const push = HEX32.test(allowance) ? pushKey(allowance) : undefined;
|
|
548
|
+
const done = await withCommit(store, [key, ...push ? [push] : []], async (commit) => {
|
|
549
|
+
const state = await loadLane(store, key, lane, slot), current = state.current, pending = current?.pending;
|
|
550
|
+
if (!current || !pending || !same(current.id, allowance))
|
|
551
|
+
return { state };
|
|
552
|
+
const voucher = pending.voucher ?? await completedVoucher(store, pending);
|
|
553
|
+
if (!voucher || voucher.seq !== pending.seq || !same(voucher.allowance_id, allowance))
|
|
554
|
+
return { state };
|
|
555
|
+
const next = { ...state, current: { ...current, seq: pending.seq, cumulative: voucher.cumulative, previous: voucher, pending: undefined } };
|
|
556
|
+
if (!await journaledAllowanceVoucher(store, pending.requestId))
|
|
557
|
+
commit.stage(voucherKey(pending.requestId), { schema: 1, voucher });
|
|
558
|
+
commit.stage(key, next);
|
|
559
|
+
if (push) {
|
|
560
|
+
const journaled = await loadPush(store, allowance).catch(() => undefined);
|
|
561
|
+
if (!journaled || journaled.voucher.seq < voucher.seq)
|
|
562
|
+
commit.stage(push, { schema: 1, voucher, acked: [], repushed: false });
|
|
563
|
+
}
|
|
564
|
+
return { state: next, voucher };
|
|
565
|
+
});
|
|
566
|
+
if (done.voucher && push) {
|
|
567
|
+
const voucher = done.voucher;
|
|
568
|
+
background(() => sendAndJournal(env, voucher, accountantEndpoints(env, env.deployment.chainId)));
|
|
569
|
+
}
|
|
570
|
+
return done.state;
|
|
571
|
+
}
|
|
572
|
+
catch {
|
|
573
|
+
return seen;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
/** Swap in the reserved-ahead allowance when the current one cannot fund the operation. */
|
|
577
|
+
async function promote(env, key, lane, slot, context, operation) {
|
|
578
|
+
return env.store.withLock(key, async () => {
|
|
579
|
+
const state = await loadLane(env.store, key, lane, slot);
|
|
580
|
+
if (usable(state.current, env, context, operation.action, operation.expires))
|
|
581
|
+
return state.current;
|
|
582
|
+
if (state.current?.pending || state.next?.phase !== 'confirmed')
|
|
583
|
+
return undefined;
|
|
584
|
+
const next = { ...state.next, seq: 0, cumulative: '0' };
|
|
585
|
+
if (!usable(next, env, context, operation.action, operation.expires))
|
|
586
|
+
return undefined;
|
|
587
|
+
await env.store.save(key, { ...state, current: next, next: undefined, retired: retire(state) });
|
|
588
|
+
repushLast(env, state.current);
|
|
589
|
+
return next;
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
function retire(state) {
|
|
593
|
+
return [...state.retired ?? [], ...state.current ? [state.current.id] : []].slice(-MAX_RETIRED);
|
|
594
|
+
}
|
|
595
|
+
function fieldsFor(intent, context) {
|
|
596
|
+
return { chain_id: intent.chain_id, settlement: intent.settlement, key_registry: intent.key_registry, slot: intent.slot,
|
|
597
|
+
verification_epoch: intent.verification_epoch, verification_seed: intent.verification_seed, verification_root: intent.verification_root,
|
|
598
|
+
verification_registry_size: intent.verification_registry_size, verification_committee: intent.verification_committee,
|
|
599
|
+
verification_quorum: intent.verification_quorum,
|
|
600
|
+
keeper_assignment: { ...structuredClone(intent.keeper_assignment), coordinator: [...context.intentFields.keeper_assignment.coordinator] } };
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Start (once per lane in this process) a background reservation for a lane that lacks a usable
|
|
604
|
+
* or reserved-ahead allowance. Failures are kept on the lane journal state only; they never fail an operation.
|
|
605
|
+
*/
|
|
606
|
+
function refillLane(env, context, lane, operation) {
|
|
607
|
+
const key = laneKey(env.deployment, context.intentFields.slot, lane);
|
|
608
|
+
if (context.undrawn || refilling.has(key) || refilling.size >= MAX_REFILLING)
|
|
609
|
+
return;
|
|
610
|
+
const work = reserveOnLane(env, context, lane, operationPlan(env, context, operation)).then(() => { }, () => { }).finally(() => { refilling.delete(key); refillingDraw.delete(key); });
|
|
611
|
+
refilling.set(key, work);
|
|
612
|
+
refillingDraw.set(key, context.intentFields);
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Reserve (or reconcile) one lane's next allowance now. Exposed for applications that want lanes
|
|
616
|
+
* ready before the first operation; operations otherwise trigger it in the background.
|
|
617
|
+
* @param env - Allowance environment.
|
|
618
|
+
* @param context - Fresh discovery for the slot (verification epoch and keeper sharing of the allowance).
|
|
619
|
+
* @param lane - Lane index.
|
|
620
|
+
* @param signal - Cancellation (honoured until the reservation is prepared).
|
|
621
|
+
* @param ready - What the lane must be ready for (see {@link LaneReadiness}); unset, the plain `low()` rule.
|
|
622
|
+
*/
|
|
623
|
+
export async function reserveForLane(env, context, lane, signal, ready) {
|
|
624
|
+
if (ready)
|
|
625
|
+
validateLaneReadiness(env, ready);
|
|
626
|
+
// An allowance is drawn on its context's verifier draw: an undrawn one has none.
|
|
627
|
+
if (context.undrawn)
|
|
628
|
+
throw new TasraError('An undrawn payment context cannot reserve an allowance; discover again');
|
|
629
|
+
const outcome = await reserveOnLane(env, context, lane, ready ? readinessPlan(env, ready) : regularPlan(env), signal);
|
|
630
|
+
return outcome === 'capped' ? 'not-needed' : outcome;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
633
|
+
* Open one regular lane ahead of its first operation (see `prepareAllowances` in paid-operation.ts).
|
|
634
|
+
* The reservation is {@link reserveForLane}'s, journaled phase by phase exactly as a background
|
|
635
|
+
* refill: no other path. Before anything is discovered or signed:
|
|
636
|
+
* - a reservation of this lane already running in this process (an operation's refill) is awaited,
|
|
637
|
+
* never doubled, and the lane judged again after it;
|
|
638
|
+
* - a lane that needs nothing (a usable confirmed allowance, or a confirmed one reserved ahead)
|
|
639
|
+
* reports `not-needed` without a discovery, a signature or a send.
|
|
640
|
+
* With `ready` ({@link LaneReadiness}) "needs nothing" means ready for the coming work: when the
|
|
641
|
+
* current allowance is not confirmed, low, expires within `minLifetimeSecs`, or the lane cannot
|
|
642
|
+
* fund `minOperations`, the NEXT allowance is reserved ahead (and the lane judged again). A lane
|
|
643
|
+
* whose current allowance is spent takes its confirmed next over first, exactly as an operation
|
|
644
|
+
* would; one still short while holding both throws {@link AllowanceCapacityError}, never a third.
|
|
645
|
+
* Otherwise `discover` is called for a FRESH context (never one cached across lanes) and the lane is
|
|
646
|
+
* reserved; the reservation is registered as this lane's refill, so an operation selecting meanwhile
|
|
647
|
+
* waits for it (bounded) instead of starting its own.
|
|
648
|
+
* @param env - Allowance environment.
|
|
649
|
+
* @param slot - Slot.
|
|
650
|
+
* @param lane - Regular lane index, 0..lanes-1.
|
|
651
|
+
* @param discover - Fresh discovery for the slot (`fundedByAllowance`), called at most once per reservation.
|
|
652
|
+
* @param signal - Cancellation (honoured until the reservation is prepared; afterwards it is reconciled).
|
|
653
|
+
* @param ready - What the lane must be ready for (default: the plain `low()` rule).
|
|
654
|
+
*/
|
|
655
|
+
export async function prepareAllowanceLane(env, slot, lane, discover, signal, ready = {}) {
|
|
656
|
+
if (!HEX32.test(slot))
|
|
657
|
+
throw new TasraError('Invalid allowance slot');
|
|
658
|
+
if (!Number.isSafeInteger(lane) || lane < 0 || lane >= allowanceLaneCount(env.options))
|
|
659
|
+
throw new TasraError('Allowance lane out of range');
|
|
660
|
+
validateLaneReadiness(env, ready);
|
|
661
|
+
if (ready.work && !same(ready.work.context.intentFields.slot, slot))
|
|
662
|
+
throw new TasraError('Readiness discovery is for another slot');
|
|
663
|
+
const demanding = (ready.minOperations ?? 0) > 0 || (ready.minLifetimeSecs ?? 0) > 0 || ready.work !== undefined;
|
|
664
|
+
const key = laneKey(env.deployment, slot, lane), base = regularPlan(env), plan = demanding ? readinessPlan(env, ready) : base;
|
|
665
|
+
let reserved = false;
|
|
666
|
+
// Bounded: operations that keep restarting a failing refill of this lane leave it to them.
|
|
667
|
+
for (let round = 0;; round++) {
|
|
668
|
+
signal?.throwIfAborted();
|
|
669
|
+
if (round >= PREPARE_ROUNDS)
|
|
670
|
+
throw new AllowanceUnavailableError('the lane is being reserved by operations; inspect it once they settle');
|
|
671
|
+
const running = refilling.get(key);
|
|
672
|
+
if (running) {
|
|
673
|
+
await running;
|
|
674
|
+
continue;
|
|
675
|
+
}
|
|
676
|
+
const state = await loadLane(env.store, key, lane, slot);
|
|
677
|
+
// An uncertain earlier reservation is reconciled by reserveForLane before anything new is signed.
|
|
678
|
+
const uncertain = state.next?.record !== undefined && state.next.phase !== 'confirmed';
|
|
679
|
+
if (!uncertain) {
|
|
680
|
+
const verdict = laneVerdict(env, base, state, ready, demanding);
|
|
681
|
+
if (verdict === 'ready')
|
|
682
|
+
return reserved ? 'reserved' : 'not-needed';
|
|
683
|
+
if (verdict === 'short') {
|
|
684
|
+
// The current allowance is spent for operations (exactly when a fresh reservation would
|
|
685
|
+
// replace it at once): take the confirmed reserved-ahead one over, as an operation's
|
|
686
|
+
// promotion would, and judge again (the next round reserves the following one). Otherwise
|
|
687
|
+
// the lane already holds its two allowances (2 x lanes x amount): never a third.
|
|
688
|
+
if (state.current?.pending === undefined && plan.takeOver(state) && await takeOverNext(env, key, lane, slot, plan))
|
|
689
|
+
continue;
|
|
690
|
+
throw new AllowanceCapacityError(lane, laneOperations(env, state, ready), ready);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const context = await discover();
|
|
694
|
+
signal?.throwIfAborted();
|
|
695
|
+
if (context.undrawn)
|
|
696
|
+
throw new TasraError('An undrawn payment context cannot reserve an allowance; discover again');
|
|
697
|
+
const f = context.intentFields;
|
|
698
|
+
if (!same(f.slot, slot) || f.chain_id !== env.deployment.chainId || !same(f.settlement, env.deployment.settlement))
|
|
699
|
+
throw new TasraError('Discovery is for another slot or deployment');
|
|
700
|
+
// An operation's refill started while discovering: judge the lane again once it ends.
|
|
701
|
+
if (refilling.has(key))
|
|
702
|
+
continue;
|
|
703
|
+
const work = reserveForLane(env, context, lane, signal, demanding ? ready : undefined);
|
|
704
|
+
const tracked = work.then(() => { }, () => { }).finally(() => { if (refilling.get(key) === tracked) {
|
|
705
|
+
refilling.delete(key);
|
|
706
|
+
refillingDraw.delete(key);
|
|
707
|
+
} });
|
|
708
|
+
refilling.set(key, tracked);
|
|
709
|
+
refillingDraw.set(key, f);
|
|
710
|
+
const outcome = await work;
|
|
711
|
+
// Pending (uncertain) is reported as is; a reservation is judged again against the coming work.
|
|
712
|
+
if (outcome === 'pending' || (!demanding && outcome === 'reserved'))
|
|
713
|
+
return outcome;
|
|
714
|
+
if (outcome === 'reserved')
|
|
715
|
+
reserved = true;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
/** The lane cannot hold what the coming work needs: it already holds a current and a reserved-ahead allowance. */
|
|
719
|
+
export class AllowanceCapacityError extends TasraError {
|
|
720
|
+
lane;
|
|
721
|
+
operations;
|
|
722
|
+
/** Stable reason. */
|
|
723
|
+
code = 'allowance-capacity';
|
|
724
|
+
constructor(
|
|
725
|
+
/** The allowance lane that is full. */
|
|
726
|
+
lane,
|
|
727
|
+
/** Operations the lane can still fund within the required lifetime. */
|
|
728
|
+
operations, ready) {
|
|
729
|
+
super(`Allowance lane ${lane} can fund ${operations} operation(s) outliving ${ready.minLifetimeSecs ?? 0} s, below the ${ready.minOperations ?? 0} required; `
|
|
730
|
+
+ 'it already holds its current and one reserved-ahead allowance (at most 2 x lanes x amount locked): raise amount or lanes, or prepare again once the current one is spent', { retryable: false });
|
|
731
|
+
this.lane = lane;
|
|
732
|
+
this.operations = operations;
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
/**
|
|
736
|
+
* Validate a lane readiness request against the allowance options.
|
|
737
|
+
* @param env - Allowance environment.
|
|
738
|
+
* @param ready - Readiness request.
|
|
739
|
+
*/
|
|
740
|
+
export function validateLaneReadiness(env, ready) {
|
|
741
|
+
const ops = ready.minOperations ?? 0, life = ready.minLifetimeSecs ?? 0, lifetime = env.options.lifetimeSecs ?? ALLOWANCE_MAX_LIFETIME_SECS;
|
|
742
|
+
const most = 2n * (env.options.amount / env.limits.maxCost);
|
|
743
|
+
if (!Number.isSafeInteger(ops) || ops < 0 || BigInt(ops) > most)
|
|
744
|
+
throw new TasraError(`Allowance minOperations must be 0..${most} (two allowances of amount / maxCost operations)`);
|
|
745
|
+
if (!Number.isSafeInteger(life) || life < 0 || life > lifetime - 120)
|
|
746
|
+
throw new TasraError(`Allowance minLifetimeSecs must be 0..${lifetime - 120} (the allowance lifetime minus 120 s)`);
|
|
747
|
+
const work = ready.work;
|
|
748
|
+
if (work === undefined)
|
|
749
|
+
return;
|
|
750
|
+
validateReadinessHorizon(env, life, work.ttlSecs);
|
|
751
|
+
if (work.actions.length === 0 || new Set(work.actions).size !== work.actions.length)
|
|
752
|
+
throw new TasraError('Allowance readiness actions must be distinct and non-empty');
|
|
753
|
+
// An action the configured allowances never fund cannot be readied by any reservation.
|
|
754
|
+
const funded = env.options.actions ? allowanceActionBits(env.options.actions) : ALLOWANCE_ACTIONS;
|
|
755
|
+
for (const action of work.actions)
|
|
756
|
+
if (!allowanceFunds(funded, action))
|
|
757
|
+
throw new TasraError(`Allowances of this configuration do not fund ${String(action).slice(0, 32)}`);
|
|
758
|
+
}
|
|
759
|
+
/**
|
|
760
|
+
* Validate that an operation of lifetime `ttlSecs` started at the end of a `minLifetimeSecs` horizon
|
|
761
|
+
* can be funded by a fresh allowance at all ({@link LaneWork}).
|
|
762
|
+
* @param env - Allowance environment.
|
|
763
|
+
* @param minLifetimeSecs - Readiness horizon, seconds.
|
|
764
|
+
* @param ttlSecs - The operations' payment lifetime, seconds.
|
|
765
|
+
*/
|
|
766
|
+
export function validateReadinessHorizon(env, minLifetimeSecs, ttlSecs) {
|
|
767
|
+
const lifetime = env.options.lifetimeSecs ?? ALLOWANCE_MAX_LIFETIME_SECS;
|
|
768
|
+
if (!Number.isSafeInteger(ttlSecs) || ttlSecs < 1 || ttlSecs > 3600)
|
|
769
|
+
throw new TasraError('Allowance readiness operation lifetime must be 1..3600 seconds');
|
|
770
|
+
if (minLifetimeSecs + ttlSecs > lifetime - 120) {
|
|
771
|
+
throw new TasraError(`Allowance minLifetimeSecs plus the operation lifetime (${ttlSecs} s) must be at most ${lifetime - 120} s: no allowance could fund an operation started at the end of the horizon`);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
/** Can a confirmed allowance fund every operation of `work` started at `at` (balance aside)? */
|
|
775
|
+
function servesWork(intent, work, at) {
|
|
776
|
+
return work.actions.every(action => serves(intent, work.context, action, at + work.ttlSecs));
|
|
777
|
+
}
|
|
778
|
+
/** Would a confirmed allowance ever fund `work` (its actions and keeper sharing; expiry aside)? A stale one never will. */
|
|
779
|
+
function compatible(intent, work) {
|
|
780
|
+
return work.actions.every(action => allowanceFunds(intent.actions, action)) && sameSharing(work.context.intentFields, intent);
|
|
781
|
+
}
|
|
782
|
+
/**
|
|
783
|
+
* Operations the lane's confirmed allowances fund at the per-operation cap, counting only those
|
|
784
|
+
* outliving `minLifetimeSecs` (with `work`: only those lane selection would accept for each of its
|
|
785
|
+
* operations started at the end of that horizon).
|
|
786
|
+
*/
|
|
787
|
+
function laneOperations(env, s, ready) {
|
|
788
|
+
const horizon = ready.minLifetimeSecs ?? 0, at = now() + horizon, cap = env.limits.maxCost, work = ready.work;
|
|
789
|
+
const counts = (a) => a.phase === 'confirmed' && (work ? servesWork(a.intent, work, at) : a.intent.expires_at >= at + EXPIRY_MARGIN_SECS);
|
|
790
|
+
let ops = 0n;
|
|
791
|
+
if (s.current && counts(s.current)) {
|
|
792
|
+
const own = remaining(s.current) / cap - (s.current.pending ? 1n : 0n);
|
|
793
|
+
if (own > 0n)
|
|
794
|
+
ops += own;
|
|
795
|
+
}
|
|
796
|
+
if (s.next && counts(s.next))
|
|
797
|
+
ops += BigInt(s.next.intent.amount) / cap;
|
|
798
|
+
return Number(ops);
|
|
799
|
+
}
|
|
800
|
+
/** Ready for the coming work, a reservation needed, or short with the lane full (current + a confirmed next). */
|
|
801
|
+
function laneVerdict(env, plan, s, ready, demanding) {
|
|
802
|
+
if (!demanding)
|
|
803
|
+
return plan.needed(s) ? 'reserve' : 'ready';
|
|
804
|
+
const meets = laneOperations(env, s, ready) >= Math.max(ready.minOperations ?? 0, 1);
|
|
805
|
+
// A reserved-ahead allowance that can never fund the work (another keeper sharing, an action it
|
|
806
|
+
// does not fund) is replaced (`replaceNext`), never counted as the lane being full.
|
|
807
|
+
if (s.next?.phase === 'confirmed')
|
|
808
|
+
return meets ? 'ready' : ready.work && !compatible(s.next.intent, ready.work) ? 'reserve' : 'short';
|
|
809
|
+
// No reserved-ahead allowance: the current one alone must be confirmed, not low, outlive the horizon and fund the work.
|
|
810
|
+
return !plan.needed(s) && meets ? 'ready' : 'reserve';
|
|
811
|
+
}
|
|
812
|
+
/** Replace the current allowance with the confirmed reserved-ahead one when `plan.takeOver` allows it and no debit is pending. */
|
|
813
|
+
async function takeOverNext(env, key, lane, slot, plan, id) {
|
|
814
|
+
return env.store.withLock(key, async () => {
|
|
815
|
+
const s = await loadLane(env.store, key, lane, slot);
|
|
816
|
+
if (s.next?.phase !== 'confirmed' || (id !== undefined && !same(s.next.id, id)) || s.current?.pending)
|
|
817
|
+
return false;
|
|
818
|
+
if (!plan.takeOver(s))
|
|
819
|
+
return false;
|
|
820
|
+
await env.store.save(key, { ...s, current: { ...s.next, seq: 0, cumulative: '0' }, next: undefined, retired: retire(s) });
|
|
821
|
+
repushLast(env, s.current);
|
|
822
|
+
return true;
|
|
823
|
+
});
|
|
824
|
+
}
|
|
825
|
+
function regularPlan(env) {
|
|
826
|
+
return { amount: env.options.amount,
|
|
827
|
+
needed: s => !(s.next?.phase === 'confirmed' || (s.current && !low(s.current) && s.current.phase === 'confirmed')),
|
|
828
|
+
takeOver: s => !(s.current && s.current.phase === 'confirmed' && remaining(s.current) >= env.limits.maxCost && s.current.intent.expires_at - now() > LOW_LIFE_SECS / 2) };
|
|
829
|
+
}
|
|
830
|
+
/** The regular plan, needing a reservation whenever the lane is not ready for `ready` (and holds no confirmed reserved-ahead allowance). */
|
|
831
|
+
function readinessPlan(env, ready) {
|
|
832
|
+
const plan = regularPlan(env), work = ready.work;
|
|
833
|
+
const needed = (s) => laneVerdict(env, plan, s, ready, true) === 'reserve';
|
|
834
|
+
if (!work)
|
|
835
|
+
return { ...plan, needed };
|
|
836
|
+
return { ...plan, needed,
|
|
837
|
+
// As an operation's promotion would: a current allowance that cannot fund the work's next
|
|
838
|
+
// operation (its balance, its expiry, a stale keeper sharing) gives way to the confirmed next.
|
|
839
|
+
takeOver: s => plan.takeOver(s) || !s.current || !(s.current.phase === 'confirmed' && s.current.pending === undefined
|
|
840
|
+
&& remaining(s.current) >= env.limits.maxCost && servesWork(s.current.intent, work, now())),
|
|
841
|
+
replaceNext: next => next.phase === 'confirmed' && !compatible(next.intent, work) };
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* The regular plan for a background refill started by `operation`'s selection: a confirmed current
|
|
845
|
+
* allowance {@link endingFor} it needs its replacement too, not only a `low()` one.
|
|
846
|
+
*/
|
|
847
|
+
function operationPlan(env, context, operation) {
|
|
848
|
+
const plan = regularPlan(env);
|
|
849
|
+
return { ...plan, needed: s => plan.needed(s) || (s.next === undefined && s.current?.phase === 'confirmed' && endingFor(s.current, context, operation)) };
|
|
850
|
+
}
|
|
851
|
+
/** A draw lane on `context`'s draw: replaces an allowance of any other draw (only a stale one can be on its lane set) or a low one. */
|
|
852
|
+
function drawPlan(env, context) {
|
|
853
|
+
const draw = context.intentFields;
|
|
854
|
+
return { amount: env.options.drawAmount ?? env.options.amount, hold: heldPerDrawLane(env.options), needed: s => drawNeeds(s, draw),
|
|
855
|
+
// Left reserved ahead on an older draw (its take-over waited behind a debit): no session needs it any more.
|
|
856
|
+
replaceNext: next => next.phase === 'confirmed' && !sameDraw(draw, next.intent),
|
|
857
|
+
takeOver: s => !s.current || !sameDraw(s.next.intent, s.current.intent)
|
|
858
|
+
|| !(s.current.phase === 'confirmed' && remaining(s.current) >= env.limits.maxCost && s.current.intent.expires_at - now() > LOW_LIFE_SECS / 2) };
|
|
859
|
+
}
|
|
860
|
+
const unexpired = (held) => (held ?? []).filter(h => h.until > now());
|
|
861
|
+
async function reserveOnLane(env, context, lane, plan, signal) {
|
|
862
|
+
const slot = context.intentFields.slot, key = laneKey(env.deployment, slot, lane), d = env.deployment, store = env.store;
|
|
863
|
+
const payer = env.gasPayer.account.address;
|
|
864
|
+
// Type-enforced (an undrawn context has no draw fields); refused again for an untyped caller.
|
|
865
|
+
if (context.undrawn)
|
|
866
|
+
throw new TasraError('An undrawn payment context cannot reserve an allowance; discover again');
|
|
867
|
+
// Reconcile an earlier uncertain reservation first; never sign a second one beside it.
|
|
868
|
+
const before = await loadLane(store, key, lane, slot);
|
|
869
|
+
if (before.next?.record && before.next.phase !== 'confirmed') {
|
|
870
|
+
const { state, allowance } = await reconcilePrepaidAllowance(env.client, d, before.next.record);
|
|
871
|
+
if (state === 'uncertain')
|
|
872
|
+
return 'pending';
|
|
873
|
+
await releaseApplicationPayerClaim(env.client, store, d.chainId, before.next.record.transaction.from, before.next.id, state === 'not-reserved');
|
|
874
|
+
await store.withLock(key, async () => {
|
|
875
|
+
const s = await loadLane(store, key, lane, slot);
|
|
876
|
+
if (!s.next || !same(s.next.id, before.next.id))
|
|
877
|
+
return;
|
|
878
|
+
// Known not mined: it locks nothing, so it no longer counts against the lane's bound.
|
|
879
|
+
const held = state === 'not-reserved' && s.held ? { held: s.held.filter(h => !same(h.id, before.next.id)) } : {};
|
|
880
|
+
await store.save(key, { ...s, ...held, next: state === 'reserved' ? { ...s.next, phase: 'confirmed', assignmentBlock: allowance.assignmentBlock } : undefined });
|
|
881
|
+
});
|
|
882
|
+
return state === 'reserved' ? 'reserved' : 'pending';
|
|
883
|
+
}
|
|
884
|
+
if (!plan.needed(before))
|
|
885
|
+
return 'not-needed';
|
|
886
|
+
if (plan.hold !== undefined && unexpired(before.held).filter(h => !(before.next?.phase === 'signing' && same(h.id, before.next.id))).length >= plan.hold)
|
|
887
|
+
return 'capped';
|
|
888
|
+
const options = env.options, life = options.lifetimeSecs ?? ALLOWANCE_MAX_LIFETIME_SECS;
|
|
889
|
+
const unsigned = { chain_id: d.chainId, settlement: d.settlement, key_registry: d.keyRegistry, slot,
|
|
890
|
+
intent_nonce: toHex(globalThis.crypto.getRandomValues(new Uint8Array(32))), amount: plan.amount.toString(),
|
|
891
|
+
max_op_cost: (options.maxOpCost ?? env.limits.maxCost).toString(), actions: options.actions ? allowanceActionBits(options.actions) : ALLOWANCE_ACTIONS,
|
|
892
|
+
// Members measure the one-hour bound from the quote block (pinned to this observation below),
|
|
893
|
+
// whose timestamp trails the clock: never exceed it, or every member refuses the archive.
|
|
894
|
+
expires_at: Math.min(now() + life, Number(context.blockTimestamp) + ALLOWANCE_MAX_LIFETIME_SECS), verification_epoch: context.intentFields.verification_epoch, verification_seed: context.intentFields.verification_seed,
|
|
895
|
+
verification_root: context.intentFields.verification_root, verification_registry_size: context.intentFields.verification_registry_size,
|
|
896
|
+
verification_committee: context.intentFields.verification_committee, verification_quorum: context.intentFields.verification_quorum,
|
|
897
|
+
keeper_assignment: structuredClone(context.intentFields.keeper_assignment) };
|
|
898
|
+
const intent = { ...unsigned, signature: await env.creator.signTypedData(prepaidAllowanceIntentTypedData(unsigned)) };
|
|
899
|
+
const id = prepaidAllowanceId(intent);
|
|
900
|
+
const claimed = await store.withLock(key, async () => {
|
|
901
|
+
const s = await loadLane(store, key, lane, slot);
|
|
902
|
+
// A `signing` marker without a record was never broadcast (prepared is journaled first).
|
|
903
|
+
const replaced = s.next?.phase === 'confirmed' && plan.replaceNext?.(s.next) ? s.next : undefined;
|
|
904
|
+
if (s.next && s.next.phase !== 'signing' && !replaced)
|
|
905
|
+
return 'pending';
|
|
906
|
+
// The bound is judged and the new allowance counted in the same durable save, before anything
|
|
907
|
+
// is sent; a replaced `signing` marker was never broadcast and stops counting.
|
|
908
|
+
let held = {};
|
|
909
|
+
if (plan.hold !== undefined) {
|
|
910
|
+
const live = unexpired(s.held).filter(h => !(s.next?.phase === 'signing' && same(h.id, s.next.id)));
|
|
911
|
+
if (live.length >= plan.hold)
|
|
912
|
+
return 'capped';
|
|
913
|
+
held = { held: [...live, { id, until: intent.expires_at + CLOSE_GRACE_SECS }] };
|
|
914
|
+
}
|
|
915
|
+
await store.save(key, { ...s, ...held, ...replaced ? { retired: [...s.retired ?? [], replaced.id].slice(-MAX_RETIRED) } : {}, next: { id, intent, phase: 'signing' } });
|
|
916
|
+
return true;
|
|
917
|
+
});
|
|
918
|
+
if (claimed !== true)
|
|
919
|
+
return claimed;
|
|
920
|
+
const update = (patch, require) => store.withLock(key, async () => {
|
|
921
|
+
const s = await loadLane(store, key, lane, slot);
|
|
922
|
+
if (!s.next || !same(s.next.id, id) || !require.includes(s.next.phase))
|
|
923
|
+
throw new TasraError('Allowance lane changed during its reservation');
|
|
924
|
+
await store.save(key, { ...s, next: { ...s.next, ...patch } });
|
|
925
|
+
});
|
|
926
|
+
try {
|
|
927
|
+
const result = await withDedicatedPayer(`${d.chainId}-${payer.toLowerCase()}`, () => withApplicationPayerClaim(store, d.chainId, payer, id, claim => reservePrepaidAllowance(env.client, env.gasPayer, d, intent, { accountantUrls: env.accountantUrls, allowLocalHttp: env.allowLocalHttp, quoteBlock: context.blockHash,
|
|
928
|
+
maxGas: env.limits.maxGas, maxGasPrice: env.limits.maxGasPrice, signal, persist: async (checkpoint) => {
|
|
929
|
+
if (checkpoint.phase === 'prepared') {
|
|
930
|
+
// Journal first: a crash before the payer claim cannot have broadcast.
|
|
931
|
+
await update({ phase: 'prepared', record: checkpoint.record, ...(checkpoint.transactionHash ? { transactionHash: checkpoint.transactionHash } : {}) }, ['signing']);
|
|
932
|
+
await claim(checkpoint.record.transaction.nonce);
|
|
933
|
+
}
|
|
934
|
+
else if (checkpoint.phase === 'submitted')
|
|
935
|
+
await update({ phase: 'submitted', transactionHash: checkpoint.transactionHash }, ['prepared']);
|
|
936
|
+
else
|
|
937
|
+
await update({ phase: 'confirmed', transactionHash: checkpoint.transactionHash }, ['prepared', 'submitted']);
|
|
938
|
+
} })));
|
|
939
|
+
await update({ assignmentBlock: result.allowance.assignmentBlock }, ['confirmed']);
|
|
940
|
+
// Take over at once when the lane has nothing usable and no debit in flight.
|
|
941
|
+
await takeOverNext(env, key, lane, slot, plan, id);
|
|
942
|
+
return 'reserved';
|
|
943
|
+
}
|
|
944
|
+
catch (error) {
|
|
945
|
+
if (error instanceof PaidReservationUncertainError)
|
|
946
|
+
return 'pending';
|
|
947
|
+
// Nothing prepared means nothing broadcast: drop the marker so a later attempt can sign anew.
|
|
948
|
+
await store.withLock(key, async () => {
|
|
949
|
+
const s = await loadLane(store, key, lane, slot);
|
|
950
|
+
if (s.next && same(s.next.id, id) && s.next.phase === 'signing') {
|
|
951
|
+
await store.save(key, { ...s, ...s.held ? { held: s.held.filter(h => !same(h.id, id)) } : {}, next: undefined });
|
|
952
|
+
}
|
|
953
|
+
});
|
|
954
|
+
throw error;
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
async function freshQuoteBlock(client) {
|
|
958
|
+
// A live head follower's tip is the same head; the freshness rule below applies to it unchanged.
|
|
959
|
+
const tip = headFollowerOf(client)?.tip();
|
|
960
|
+
const head = tip ? { hash: tip.blockHash, timestamp: tip.blockTimestamp } : await client.getBlock({ blockTag: 'latest' });
|
|
961
|
+
if (head.hash === null || !HEX32.test(head.hash) || BigInt(now()) - head.timestamp > 20n || head.timestamp - BigInt(now()) > 2n)
|
|
962
|
+
throw new Error('debit quote head is stale or unavailable');
|
|
963
|
+
return head.hash;
|
|
964
|
+
}
|
|
965
|
+
/**
|
|
966
|
+
* The voucher journaled for a pending debit's request, when it is exactly that debit's: under the
|
|
967
|
+
* request (`pav-`), or in the operation journal's `reserved` phase, which a fresh round commits
|
|
968
|
+
* together with it (a crash may keep either one).
|
|
969
|
+
*/
|
|
970
|
+
async function completedVoucher(store, debit) {
|
|
971
|
+
const exact = (voucher) => voucher && same(voucher.request_id, debit.requestId) && voucher.seq === debit.seq
|
|
972
|
+
&& same(voucher.allowance_id, debit.payment.allowance_id ?? '') ? voucher : undefined;
|
|
973
|
+
const saved = exact(await journaledAllowanceVoucher(store, debit.requestId));
|
|
974
|
+
if (saved)
|
|
975
|
+
return saved;
|
|
976
|
+
const record = await store.load(paidRecordKey(debit.requestId)).catch(() => undefined);
|
|
977
|
+
return exact(record?.payment?.debit_voucher);
|
|
978
|
+
}
|
|
979
|
+
/** Whether a pending debit of another request may still be completed (its operation can resume). */
|
|
980
|
+
async function resumable(store, debit) {
|
|
981
|
+
if (debit.payment.expires <= now() + EXPIRY_MARGIN_SECS)
|
|
982
|
+
return false;
|
|
983
|
+
const record = await store.load(paidRecordKey(debit.requestId)).catch(() => undefined);
|
|
984
|
+
return record?.phase === 'reserving';
|
|
985
|
+
}
|
|
986
|
+
/**
|
|
987
|
+
* Obtain (or re-read) the debit voucher of one allowance-backed payment on its lane. Journals the
|
|
988
|
+
* debit before any request; resumes the same seq, request and quote block. Throws
|
|
989
|
+
* {@link AllowanceRefusedError} (lane retired, fall back) or {@link AllowanceUnavailableError} (retry later).
|
|
990
|
+
* @param env - Allowance environment.
|
|
991
|
+
* @param ticket - The lane the payment was signed for.
|
|
992
|
+
* @param payment - Creator-signed allowance payment without a voucher.
|
|
993
|
+
* @param signal - Cancellation of the network round (an aborted round stays pending).
|
|
994
|
+
*/
|
|
995
|
+
export async function obtainAllowanceVoucher(env, ticket, payment, signal, options = {}) {
|
|
996
|
+
const requestId = prepaidRequestId(payment), store = env.store;
|
|
997
|
+
const saved = await journaledAllowanceVoucher(store, requestId);
|
|
998
|
+
if (saved)
|
|
999
|
+
return saved;
|
|
1000
|
+
if (payment.allowance_id === undefined)
|
|
1001
|
+
throw new TasraError('Payment names no allowance');
|
|
1002
|
+
const slot = payment.slot, key = laneKey(env.deployment, slot, ticket.lane), allowance = payment.allowance_id;
|
|
1003
|
+
const push = HEX32.test(allowance) ? pushKey(allowance) : undefined;
|
|
1004
|
+
// Background work that takes locks this round holds starts once they are released; vouchers are
|
|
1005
|
+
// pushed only once the commit that journals them resolved.
|
|
1006
|
+
const after = [], toPush = [];
|
|
1007
|
+
consumeClaim(key);
|
|
1008
|
+
busy.add(key);
|
|
1009
|
+
try {
|
|
1010
|
+
// The lane lock serializes the lane's rounds; the push journal's lock is held with it, so the
|
|
1011
|
+
// voucher a round completes is journaled for its push in the same commit as the lane advance.
|
|
1012
|
+
const settled = await withCommit(store, [key, ...push ? [push] : [], ...options.lock ?? []], async (commit) => {
|
|
1013
|
+
await options.check?.();
|
|
1014
|
+
let state = await loadLane(store, key, ticket.lane, slot);
|
|
1015
|
+
// `save` is durable before it returns; `advance` only records the lane's next state, which is
|
|
1016
|
+
// published with the unlock (or by the next durable `save`, which carries it).
|
|
1017
|
+
let unsaved = false;
|
|
1018
|
+
const save = async (next) => { await store.save(key, next); state = next; unsaved = false; };
|
|
1019
|
+
const pushed = [];
|
|
1020
|
+
const round = { save, advance: next => { state = next; unsaved = true; }, pushed: voucher => { pushed.push(voucher); } };
|
|
1021
|
+
const retireLane = async (why, cause) => {
|
|
1022
|
+
const promoted = state.next?.phase === 'confirmed' ? { ...state.next, seq: 0, cumulative: '0' } : undefined, retiring = state.current;
|
|
1023
|
+
await save({ ...state, current: promoted, next: promoted ? undefined : state.next, retired: retire(state) });
|
|
1024
|
+
after.push(() => repushLast(env, retiring));
|
|
1025
|
+
throw new AllowanceRefusedError(why, cause);
|
|
1026
|
+
};
|
|
1027
|
+
// A round that fails after it completed another request's interrupted debit (`finalize`, whose
|
|
1028
|
+
// voucher is already journaled) still publishes that lane advance and its push journal: the
|
|
1029
|
+
// failure is reported after the commit, never by discarding the advance, which would leave
|
|
1030
|
+
// the lane pending on a debit no selection ever runs a round for again.
|
|
1031
|
+
const outcome = await (async () => {
|
|
1032
|
+
const current = state.current;
|
|
1033
|
+
if (!current || !same(current.id, allowance))
|
|
1034
|
+
throw new AllowanceRefusedError('the lane no longer holds this allowance');
|
|
1035
|
+
// A completed round of another request whose lane advance was interrupted: its voucher is
|
|
1036
|
+
// on the lane (older journals) or journaled for its request (`finalize` writes that first).
|
|
1037
|
+
if (current.pending && !same(current.pending.requestId, requestId)) {
|
|
1038
|
+
const done = current.pending.voucher ?? await completedVoucher(store, current.pending);
|
|
1039
|
+
if (done)
|
|
1040
|
+
await finalize(env, state, current, { ...current.pending, voucher: done }, round);
|
|
1041
|
+
}
|
|
1042
|
+
const other = state.current?.pending;
|
|
1043
|
+
if (other && !same(other.requestId, requestId)) {
|
|
1044
|
+
if (!await resumable(store, other))
|
|
1045
|
+
return retireLane('a debit of an abandoned or expired operation holds this lane');
|
|
1046
|
+
// Complete the earlier request first (its operation resumes onto the journaled voucher).
|
|
1047
|
+
await runRound(env, state, state.current, other, round, retireLane, signal);
|
|
1048
|
+
}
|
|
1049
|
+
const lane = state.current;
|
|
1050
|
+
if (lane.pending && lane.pending.voucher)
|
|
1051
|
+
return finalize(env, state, lane, lane.pending, round, options.journal);
|
|
1052
|
+
let debit = lane.pending;
|
|
1053
|
+
if (!debit) {
|
|
1054
|
+
// The accountants judge cost against the remainder; an empty allowance cannot fund anything.
|
|
1055
|
+
if (remaining(lane) <= 0n)
|
|
1056
|
+
return retireLane('allowance exhausted');
|
|
1057
|
+
if (lane.intent.expires_at < payment.expires + EXPIRY_MARGIN_SECS)
|
|
1058
|
+
throw new AllowanceRefusedError('allowance expires before the operation');
|
|
1059
|
+
let quoteBlock;
|
|
1060
|
+
try {
|
|
1061
|
+
quoteBlock = await freshQuoteBlock(env.client);
|
|
1062
|
+
}
|
|
1063
|
+
catch (error) {
|
|
1064
|
+
throw new AllowanceUnavailableError('no fresh quote block for the debit', error);
|
|
1065
|
+
}
|
|
1066
|
+
debit = { seq: lane.seq + 1, requestId, payment: structuredClone(payment), quoteBlock, quotedAt: now(), partials: [] };
|
|
1067
|
+
// The lane journal BEFORE any request: a resume asks for this exact seq and request.
|
|
1068
|
+
await save({ ...state, current: { ...lane, pending: debit } });
|
|
1069
|
+
}
|
|
1070
|
+
else if (debit.partials.length === 0 && now() - debit.quotedAt > QUOTE_REUSE_SECS) {
|
|
1071
|
+
try {
|
|
1072
|
+
debit = { ...debit, quoteBlock: await freshQuoteBlock(env.client), quotedAt: now() };
|
|
1073
|
+
}
|
|
1074
|
+
catch (error) {
|
|
1075
|
+
throw new AllowanceUnavailableError('no fresh quote block for the debit', error);
|
|
1076
|
+
}
|
|
1077
|
+
await save({ ...state, current: { ...lane, pending: debit } });
|
|
1078
|
+
}
|
|
1079
|
+
return runRound(env, state, state.current, debit, round, retireLane, signal, options.journal);
|
|
1080
|
+
})().then(voucher => ({ voucher }), (error) => ({ error }));
|
|
1081
|
+
if (unsaved)
|
|
1082
|
+
commit.stage(key, state);
|
|
1083
|
+
// The allowance's last voucher, journaled (unacknowledged) before it is pushed. Committed with
|
|
1084
|
+
// the lane advance: a crash may keep either one. A journal without the advance names a seq whose
|
|
1085
|
+
// voucher is journaled for its request (the next round completes the advance and journals it
|
|
1086
|
+
// again, a no-op); an advance without the journal loses nothing: `repushLast` takes the
|
|
1087
|
+
// lane's `previous` (published by that advance) when the journal is missing or older.
|
|
1088
|
+
const last = pushed.reduce((a, v) => !a || v.seq > a.seq ? v : a, undefined);
|
|
1089
|
+
if (last && push) {
|
|
1090
|
+
const journaled = await loadPush(store, allowance).catch(() => undefined);
|
|
1091
|
+
if (!journaled || journaled.voucher.seq < last.seq)
|
|
1092
|
+
commit.stage(push, { schema: 1, voucher: last, acked: [], repushed: false });
|
|
1093
|
+
toPush.push(...pushed);
|
|
1094
|
+
}
|
|
1095
|
+
return outcome;
|
|
1096
|
+
});
|
|
1097
|
+
// Never awaited by the operation; beyond the background bound the journal keeps it for the re-push.
|
|
1098
|
+
for (const done of toPush)
|
|
1099
|
+
background(() => sendAndJournal(env, done, accountantEndpoints(env, env.deployment.chainId)));
|
|
1100
|
+
if ('error' in settled)
|
|
1101
|
+
throw settled.error;
|
|
1102
|
+
return settled.voucher;
|
|
1103
|
+
}
|
|
1104
|
+
finally {
|
|
1105
|
+
busy.delete(key);
|
|
1106
|
+
for (const job of after)
|
|
1107
|
+
job();
|
|
1108
|
+
}
|
|
1109
|
+
}
|
|
1110
|
+
/** One voucher round for `debit` on the lane's current allowance; advances the lane on success. */
|
|
1111
|
+
async function runRound(env, state, lane, debit, round, retireLane, signal, journal) {
|
|
1112
|
+
try {
|
|
1113
|
+
const { voucher, partials } = await collectDebitVoucher(env.client, env.deployment, { payment: debit.payment, seq: debit.seq, previous: lane.previous,
|
|
1114
|
+
quoteBlock: debit.quoteBlock, maxOpCost: BigInt(lane.intent.max_op_cost) }, { accountantUrls: env.accountantUrls, allowLocalHttp: env.allowLocalHttp,
|
|
1115
|
+
requestTimeoutMs: env.options.debitTimeoutMs, signal, known: debit.partials });
|
|
1116
|
+
// No separate lane save of the completed round: `finalize` journals the voucher under its
|
|
1117
|
+
// request FIRST, which is what an interrupted advance is resumed from (`completedVoucher`).
|
|
1118
|
+
const done = { ...debit, partials, voucher };
|
|
1119
|
+
return await finalize(env, state, { ...lane, pending: done }, done, round, journal);
|
|
1120
|
+
}
|
|
1121
|
+
catch (error) {
|
|
1122
|
+
if (error instanceof DebitVoucherError) {
|
|
1123
|
+
const known = new Map(debit.partials.map(p => [p.identifier, p]));
|
|
1124
|
+
for (const o of error.outcomes)
|
|
1125
|
+
if (o.kind === 'partial')
|
|
1126
|
+
known.set(o.partial.identifier, o.partial);
|
|
1127
|
+
await round.save({ ...state, current: { ...lane, pending: { ...debit, partials: [...known.values()] } } });
|
|
1128
|
+
if (error.definite)
|
|
1129
|
+
return retireLane('the accountants refused the debit', error);
|
|
1130
|
+
throw new AllowanceUnavailableError('accountants unavailable for the debit; resume requests the same seq', error);
|
|
1131
|
+
}
|
|
1132
|
+
if (error instanceof AllowanceRefusedError || error instanceof AllowanceUnavailableError)
|
|
1133
|
+
throw error;
|
|
1134
|
+
throw new AllowanceUnavailableError('debit voucher round failed', error);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Journal the voucher under its request (with `journal`'s entries, in one durable commit), then
|
|
1139
|
+
* advance the lane past its seq, then push it (journaled with the lane's unlock, sent after it in
|
|
1140
|
+
* the background). The lane advance is ordered after that commit and needs no flush of its own: it
|
|
1141
|
+
* is published with the lane's unlock, or carried by the next durable lane save, and a crash before
|
|
1142
|
+
* either leaves the debit pending with its voucher journaled, which the next round on the lane
|
|
1143
|
+
* completes (`completedVoucher`) without asking anyone.
|
|
1144
|
+
*/
|
|
1145
|
+
async function finalize(env, state, lane, debit, round, journal) {
|
|
1146
|
+
const voucher = debit.voucher, store = env.store;
|
|
1147
|
+
const entries = await journaledAllowanceVoucher(store, debit.requestId) ? [] : [[voucherKey(debit.requestId), { schema: 1, voucher }]];
|
|
1148
|
+
entries.push(...journal?.(voucher) ?? []);
|
|
1149
|
+
await saveAll(store, entries);
|
|
1150
|
+
round.advance({ ...state, current: { ...lane, seq: debit.seq, cumulative: voucher.cumulative, previous: voucher, pending: undefined } });
|
|
1151
|
+
round.pushed(voucher);
|
|
1152
|
+
return voucher;
|
|
1153
|
+
}
|
|
1154
|
+
const PUSH_TIMEOUT_MS = 10_000;
|
|
1155
|
+
const PUSH_CONCURRENCY = 4;
|
|
1156
|
+
/** Background push jobs in this process; beyond it a push is skipped (the journal keeps it unacknowledged for the re-push). */
|
|
1157
|
+
const MAX_PUSHES = 64;
|
|
1158
|
+
const pushes = new Set();
|
|
1159
|
+
function pushKey(allowance) {
|
|
1160
|
+
if (!HEX32.test(allowance))
|
|
1161
|
+
throw new TasraError('Invalid allowance ID');
|
|
1162
|
+
return `pap-${allowance.slice(2).toLowerCase()}`;
|
|
1163
|
+
}
|
|
1164
|
+
async function loadPush(store, allowance) {
|
|
1165
|
+
const r = await store.load(pushKey(allowance));
|
|
1166
|
+
if (r === undefined)
|
|
1167
|
+
return undefined;
|
|
1168
|
+
if (!r || r.schema !== 1 || !same(r.voucher.allowance_id, allowance) || !Array.isArray(r.acked))
|
|
1169
|
+
throw new TasraError('Invalid voucher push journal');
|
|
1170
|
+
return r;
|
|
1171
|
+
}
|
|
1172
|
+
function background(work) {
|
|
1173
|
+
if (pushes.size >= MAX_PUSHES)
|
|
1174
|
+
return;
|
|
1175
|
+
const job = Promise.resolve().then(work).catch(() => { }).finally(() => pushes.delete(job));
|
|
1176
|
+
pushes.add(job);
|
|
1177
|
+
}
|
|
1178
|
+
/** Send `voucher` to `urls` and merge the acknowledgements into its journal (when it is still the allowance's last). */
|
|
1179
|
+
async function sendAndJournal(env, voucher, urls) {
|
|
1180
|
+
if (urls.length === 0)
|
|
1181
|
+
return;
|
|
1182
|
+
const outcomes = await pushDebitVoucher(env.deployment.chainId, voucher, { accountantUrls: urls, allowLocalHttp: env.allowLocalHttp,
|
|
1183
|
+
requestTimeoutMs: PUSH_TIMEOUT_MS, concurrency: PUSH_CONCURRENCY });
|
|
1184
|
+
const accepted = outcomes.filter(o => o.kind === 'accepted').map(o => o.url);
|
|
1185
|
+
if (accepted.length === 0)
|
|
1186
|
+
return;
|
|
1187
|
+
const key = pushKey(voucher.allowance_id);
|
|
1188
|
+
await env.store.withLock(key, async () => {
|
|
1189
|
+
const r = await loadPush(env.store, voucher.allowance_id);
|
|
1190
|
+
if (!r || r.voucher.seq !== voucher.seq)
|
|
1191
|
+
return;
|
|
1192
|
+
await env.store.save(key, { ...r, acked: [...new Set([...r.acked, ...accepted])] });
|
|
1193
|
+
});
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Re-push an allowance's last voucher ONCE to the members that did not acknowledge it (lane
|
|
1197
|
+
* retiring, allowance near expiry). Never throws.
|
|
1198
|
+
*
|
|
1199
|
+
* The push journal is committed with the lane advance, but a crash may keep either one of that
|
|
1200
|
+
* commit: a lane advanced past its last voucher whose push journal is missing or names an older
|
|
1201
|
+
* seq. The voucher it would name is durable anyway: the lane's `previous`, published by that same
|
|
1202
|
+
* advance. When the journal is missing or older, that voucher stands in, acknowledged by no
|
|
1203
|
+
* member, so an allowance's last voucher is re-pushed after a crash too, with no flush added to the
|
|
1204
|
+
* debit path. Only the lost journal's acknowledgements are lost: a member that had acknowledged is
|
|
1205
|
+
* asked again (an idempotent accept).
|
|
1206
|
+
*/
|
|
1207
|
+
function repushLast(env, lane) {
|
|
1208
|
+
if (!lane)
|
|
1209
|
+
return;
|
|
1210
|
+
const allowance = lane.id;
|
|
1211
|
+
const last = lane.seq > 0 && lane.previous && same(lane.previous.allowance_id, allowance) ? lane.previous : undefined;
|
|
1212
|
+
background(async () => {
|
|
1213
|
+
const urls = accountantEndpoints(env, env.deployment.chainId), key = pushKey(allowance);
|
|
1214
|
+
const todo = await env.store.withLock(key, async () => {
|
|
1215
|
+
const journaled = await loadPush(env.store, allowance);
|
|
1216
|
+
const r = last && (!journaled || journaled.voucher.seq < last.seq)
|
|
1217
|
+
? { schema: 1, voucher: last, acked: [], repushed: false } : journaled;
|
|
1218
|
+
if (!r || r.repushed)
|
|
1219
|
+
return undefined;
|
|
1220
|
+
const missing = urls.filter(u => !r.acked.includes(u));
|
|
1221
|
+
if (missing.length === 0)
|
|
1222
|
+
return undefined;
|
|
1223
|
+
// Marked before sending: once, even if this process stops mid-push.
|
|
1224
|
+
await env.store.save(key, { ...r, repushed: true });
|
|
1225
|
+
return { voucher: r.voucher, missing };
|
|
1226
|
+
});
|
|
1227
|
+
if (todo)
|
|
1228
|
+
await sendAndJournal(env, todo.voucher, todo.missing);
|
|
1229
|
+
});
|
|
1230
|
+
}
|
|
1231
|
+
/**
|
|
1232
|
+
* The voucher push journal of an allowance: its last voucher, the members that acknowledged it and
|
|
1233
|
+
* whether the one re-push was spent (diagnostics).
|
|
1234
|
+
* @param store - Application store.
|
|
1235
|
+
* @param allowance - Allowance ID.
|
|
1236
|
+
*/
|
|
1237
|
+
export async function inspectAllowanceVoucherPush(store, allowance) {
|
|
1238
|
+
const r = await loadPush(store, allowance);
|
|
1239
|
+
return r && { seq: r.voucher.seq, acked: [...r.acked], repushed: r.repushed };
|
|
1240
|
+
}
|
|
1241
|
+
/** Test hook: wait for every background voucher push started in this process. */
|
|
1242
|
+
export async function settleAllowanceVoucherPushes() {
|
|
1243
|
+
while (pushes.size > 0)
|
|
1244
|
+
await Promise.all([...pushes]);
|
|
1245
|
+
}
|
|
1246
|
+
/**
|
|
1247
|
+
* Inspect the lanes of a slot: allowance, seq, cumulative and any pending debit (diagnostics).
|
|
1248
|
+
* @param store - Application store.
|
|
1249
|
+
* @param deployment - Approved deployment.
|
|
1250
|
+
* @param slot - Slot.
|
|
1251
|
+
* @param lanes - Lane count.
|
|
1252
|
+
*/
|
|
1253
|
+
export async function inspectAllowanceLanes(store, deployment, slot, lanes) {
|
|
1254
|
+
const out = [];
|
|
1255
|
+
for (let lane = 0; lane < lanes; lane++) {
|
|
1256
|
+
const s = await loadLane(store, laneKey(deployment, slot, lane), lane, slot);
|
|
1257
|
+
out.push({ lane, ...s.current ? { allowanceId: s.current.id, phase: s.current.phase, seq: s.current.seq, cumulative: s.current.cumulative,
|
|
1258
|
+
amount: s.current.intent.amount, expiresAt: s.current.intent.expires_at,
|
|
1259
|
+
...s.current.pending ? { pending: { seq: s.current.pending.seq, requestId: s.current.pending.requestId, partials: s.current.pending.partials.length } } : {} } : {},
|
|
1260
|
+
...s.next ? { next: { allowanceId: s.next.id, phase: s.next.phase } } : {}, retired: s.retired?.length ?? 0 });
|
|
1261
|
+
}
|
|
1262
|
+
return out;
|
|
1263
|
+
}
|
|
1264
|
+
/**
|
|
1265
|
+
* Inspect the session-grant draw lanes of a slot for one epoch's parity: as {@link inspectAllowanceLanes},
|
|
1266
|
+
* with each allowance's verifier epoch and how many allowances the lane holds (escrow possibly still locked).
|
|
1267
|
+
* @param store - Application store.
|
|
1268
|
+
* @param deployment - Approved deployment.
|
|
1269
|
+
* @param slot - Slot.
|
|
1270
|
+
* @param lanes - Lane count.
|
|
1271
|
+
* @param epoch - A verifier epoch of the parity to inspect.
|
|
1272
|
+
*/
|
|
1273
|
+
export async function inspectAllowanceDrawLanes(store, deployment, slot, lanes, epoch) {
|
|
1274
|
+
const out = [];
|
|
1275
|
+
for (let j = 0; j < lanes; j++) {
|
|
1276
|
+
const lane = drawLaneIndex(epoch, j), s = await loadLane(store, laneKey(deployment, slot, lane), lane, slot);
|
|
1277
|
+
out.push({ lane, ...s.current ? { allowanceId: s.current.id, epoch: s.current.intent.verification_epoch, phase: s.current.phase, seq: s.current.seq, amount: s.current.intent.amount } : {},
|
|
1278
|
+
...s.next ? { next: { allowanceId: s.next.id, phase: s.next.phase, epoch: s.next.intent.verification_epoch } } : {}, retired: s.retired?.length ?? 0, held: unexpired(s.held).length });
|
|
1279
|
+
}
|
|
1280
|
+
return out;
|
|
1281
|
+
}
|
|
1282
|
+
/** Test hook: wait for every background reservation (and draw reserve-ahead) started in this process. */
|
|
1283
|
+
export async function settleAllowanceRefills() {
|
|
1284
|
+
while (refilling.size > 0 || aheads.size > 0)
|
|
1285
|
+
await Promise.all([...refilling.values(), ...aheads.values()]);
|
|
1286
|
+
}
|
|
1287
|
+
/** Test hook: forget this process's reserve-ahead retry times (a new process starts without them). */
|
|
1288
|
+
export function resetAllowanceDrawAheads() {
|
|
1289
|
+
aheadDone.clear();
|
|
1290
|
+
}
|