@t3foundry/tasra-sdk 0.3.1-next.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,1720 @@
|
|
|
1
|
+
import { verifyEvidenceBinding } from '../committee/evidence.js';
|
|
2
|
+
import { recipientPayloadDigest } from '../crypto/recipient.js';
|
|
3
|
+
import { sha256 } from '@noble/hashes/sha256';
|
|
4
|
+
import { ibeVerifyShare } from '../crypto/ibe.js';
|
|
5
|
+
// One paid committee operation, end to end, from the client side.
|
|
6
|
+
//
|
|
7
|
+
// billing guard → canonical discovery → creator-signed operation and payment intent →
|
|
8
|
+
// drawn verifier witnesses → accountant quote + on-chain reservation (dedicated gas payer) →
|
|
9
|
+
// creator execution certificate → registered paid session (stage approvals, presentation,
|
|
10
|
+
// continuation) → verified committee grant → the keeper operation, once.
|
|
11
|
+
//
|
|
12
|
+
// Every step that spends or sends a billable write is journaled in the application store
|
|
13
|
+
// before it happens. An uncertain step is never repeated automatically: the call throws
|
|
14
|
+
// PaidOperationRecoveryError naming the request, and resumePaidOperation continues from the
|
|
15
|
+
// journal (reconciling the reservation on chain, re-reading the session) without a second
|
|
16
|
+
// reservation, a second session or a second keeper execution.
|
|
17
|
+
import { hexToBytes, keccak256, toHex } from 'viem';
|
|
18
|
+
import { keyRegistryAbi } from '../chain/abis/keyRegistry.js';
|
|
19
|
+
import { discoverPaidOperationContext, followPaidRequest, readClientExecutionPolicy, readCurrentBeaconEpoch, drawnIntentFields } from '../chain/prepaid.js';
|
|
20
|
+
import { fetchDrawnVerifierWitnesses } from '../chain/verifierSnapshot.js';
|
|
21
|
+
import { prepareRegisteredPaidSession } from '../chain/registeredPaidAgent.js';
|
|
22
|
+
import { createKeeperExecutionApprover } from '../chain/keeperExecution.js';
|
|
23
|
+
import { recoverKeeperExecution } from '../chain/keeperRecovery.js';
|
|
24
|
+
import { ruleCommitment } from '../chain/write.js';
|
|
25
|
+
import { loadPaidReservationJournal } from './paid-journal.js';
|
|
26
|
+
import { reserveApplicationPayment, reconcileApplicationPayment, reconcileApplicationReservation, ApplicationPayerRecoveryError } from './paid-reservation.js';
|
|
27
|
+
import { drivePaidSession, waitForPaidSnapshot, FIRST_COMMIT, PaidSessionRecoveryError } from './paid-session.js';
|
|
28
|
+
import { PaidAgentControlError } from '../chain/registeredPaidAgent.js';
|
|
29
|
+
import { VerifierAgentSessionError } from '../verifier-agent/index.js';
|
|
30
|
+
import { withDedicatedPayer } from './payer-queue.js';
|
|
31
|
+
import { createExecutionCertificate, createLocalExecutionSigner } from '../committee/execution.js';
|
|
32
|
+
import { allowanceActionBits, paymentIntentHash, paymentIntentTypedData, paymentSessionCommitment, prepaidRequestId } from '../committee/payment.js';
|
|
33
|
+
import { compoundTokenHash, decodeCompoundToken, requireStatusAttestations, signersThatVerify, verifyStatusAttestation, verifyStatusAttestations, STATUS_SKEW_SECS } from '../committee/token.js';
|
|
34
|
+
import { acceptStatusRefreshRelay, createStatusRefreshProof, refreshStatusDirect, statusRefreshRelayBody } from '../committee/status-refresh.js';
|
|
35
|
+
import { canonicalize, isOauthFormat } from '../auth/oid4vp.js';
|
|
36
|
+
import { isOauthEnvelope } from '../auth/rego.js';
|
|
37
|
+
import { presentationOperationTypedData, verifierAgentResult } from '../oid4vp/verifier-agent.js';
|
|
38
|
+
import { requestHash } from '../oid4vp/binding.js';
|
|
39
|
+
import { PaidApprovalUnresolvedError, RevocationStatusPreflightError, StatusRefreshError, TasraError } from '../errors.js';
|
|
40
|
+
import { base64Decode } from '../crypto/envelope.js';
|
|
41
|
+
import { HEX32, RECORD_KEY, RECORD_PREFIX, paidRecordKey as recordKey } from './paid-keys.js';
|
|
42
|
+
import { AllowanceRefusedError, allowanceLaneCount, journaledAllowanceVoucher, obtainAllowanceVoucher, prepareAllowanceLane, selectAllowanceLane, validateAllowanceOptions, validateLaneReadiness, validateReadinessHorizon } from './paid-allowance.js';
|
|
43
|
+
import { storeIdentity, withCommit } from './store-commit.js';
|
|
44
|
+
import { admitSlotPolicySequence, requireCurrentSlotPolicy, verifySlotPolicyBootstrap } from './policy-bootstrap.js';
|
|
45
|
+
/** The journaled salt of an operation that never held one (a policy bootstrap, a presentationless payment). */
|
|
46
|
+
const ZERO_SALT = `0x${'00'.repeat(32)}`;
|
|
47
|
+
/** The operation stopped where repeating a step could pay or execute twice; resume or recover it. */
|
|
48
|
+
export class PaidOperationRecoveryError extends TasraError {
|
|
49
|
+
requestId;
|
|
50
|
+
phase;
|
|
51
|
+
/** Stable machine-readable reason. */
|
|
52
|
+
code;
|
|
53
|
+
/** Whether {@link resumePaidOperation} can still make progress; false for a final refusal or a step only `recover` can read. */
|
|
54
|
+
resumable;
|
|
55
|
+
constructor(
|
|
56
|
+
/** Reservation identity to resume with. */ requestId,
|
|
57
|
+
/** Step whose outcome is uncertain. */ phase, cause,
|
|
58
|
+
/** Classification; defaults to the uncertain outcome of the phase. */
|
|
59
|
+
detail = {}) {
|
|
60
|
+
super(`Paid operation ${requestId.slice(0, 12)}… stopped during ${phase}; resume it from its journal, never start it again`, { retryable: false, cause });
|
|
61
|
+
this.requestId = requestId;
|
|
62
|
+
this.phase = phase;
|
|
63
|
+
this.code = detail.code ?? (phase === 'reservation' ? 'reservation-uncertain' : phase === 'session' ? 'session-interrupted' : 'execution-uncertain');
|
|
64
|
+
this.resumable = detail.resumable ?? !['reservation-failed', 'session-refused', 'session-write-uncertain', 'payment-expired', 'execution-uncertain'].includes(this.code);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const expired = (payment) => payment.expires <= Math.floor(Date.now() / 1000);
|
|
68
|
+
/** Final 4xx refusals; 408/409/425/429 are transient or need a status read first. */
|
|
69
|
+
const refusal = (status) => status >= 400 && status < 500 && ![408, 409, 425, 429].includes(status);
|
|
70
|
+
function sessionFailure(requestId, payment, error) {
|
|
71
|
+
let code = 'session-interrupted';
|
|
72
|
+
if (error instanceof PaidSessionRecoveryError || error instanceof PaidApprovalUnresolvedError)
|
|
73
|
+
code = 'session-write-uncertain';
|
|
74
|
+
else if (error instanceof VerifierAgentSessionError) {
|
|
75
|
+
if (error.kind === 'refused' || (error.httpStatus !== undefined && refusal(error.httpStatus)))
|
|
76
|
+
code = 'session-refused';
|
|
77
|
+
}
|
|
78
|
+
else if (error instanceof PaidAgentControlError && refusal(error.httpStatus))
|
|
79
|
+
code = 'session-refused';
|
|
80
|
+
if (code !== 'session-refused' && code !== 'session-write-uncertain' && expired(payment))
|
|
81
|
+
code = 'payment-expired';
|
|
82
|
+
return new PaidOperationRecoveryError(requestId, 'session', error, { code });
|
|
83
|
+
}
|
|
84
|
+
/** The preflight refusal, tagged with the paid operation it stopped before execution. */
|
|
85
|
+
function statusRefusal(requestId, error) {
|
|
86
|
+
return new RevocationStatusPreflightError({ code: error.code, message: error.message, requestId, cause: error });
|
|
87
|
+
}
|
|
88
|
+
/** The keeper's revocation-status rule over a journaled grant, against its anchored witnesses. */
|
|
89
|
+
function statusPreflight(config, record, wire) {
|
|
90
|
+
const token = decodeCompoundToken(wire);
|
|
91
|
+
const set = { registrySize: record.payment.verification_registry_size,
|
|
92
|
+
pubkeys: new Map(record.members.map(m => [m.index, hexToBytes(m.publicKey)])) };
|
|
93
|
+
requireStatusAttestations({ tokenHash: compoundTokenHash(token), attestations: token.statusAttestations, counted: signersThatVerify(token, set),
|
|
94
|
+
set, quorum: record.payment.verification_quorum, now: Math.floor(Date.now() / 1000), allowMissing: config.allowMissingStatusAttestations === true });
|
|
95
|
+
}
|
|
96
|
+
/** A caller abort in a journaled step that sent nothing uncertain. */
|
|
97
|
+
function abortedError(requestId, phase, payment, signal, error) {
|
|
98
|
+
return new PaidOperationRecoveryError(requestId, phase, signal.reason ?? error, { code: 'aborted', resumable: !expired(payment) });
|
|
99
|
+
}
|
|
100
|
+
/** Bound on journaled attempts per operation (verifiers cap successful refreshes at 16 per token). */
|
|
101
|
+
const MAX_STATUS_REFRESH_ATTEMPTS = 64;
|
|
102
|
+
/** Deadline of one relayed refresh (the agent fans out to the committee). */
|
|
103
|
+
const RELAY_REFRESH_TIMEOUT_MS = 30_000;
|
|
104
|
+
// The operation index, oldest first. `paid-op-index` is the original single list: still read, never
|
|
105
|
+
// dropped, and rewritten only by the one-time backfill (and by older SDKs, whose entries are read
|
|
106
|
+
// too). New operations append to bounded segments `paid-op-index-0`, `-1`, … instead, so indexing
|
|
107
|
+
// one operation rewrites at most SEGMENT_IDS entries rather than the whole history. Readers take
|
|
108
|
+
// the legacy list, then the segments in order until the first absent one; an id is listed once.
|
|
109
|
+
const INDEX_KEY = 'paid-op-index';
|
|
110
|
+
/** Most ids in one index segment; a full segment is never rewritten again. */
|
|
111
|
+
const SEGMENT_IDS = 256;
|
|
112
|
+
const segmentKey = (n) => `${INDEX_KEY}-${n}`;
|
|
113
|
+
const validIds = (ids) => Array.isArray(ids) && !ids.some(id => typeof id !== 'string' || !HEX32.test(id));
|
|
114
|
+
async function loadIndexRecord(store) {
|
|
115
|
+
const index = await store.load(INDEX_KEY);
|
|
116
|
+
if (index === undefined)
|
|
117
|
+
return { schema: 1, ids: [] };
|
|
118
|
+
if (!index || index.schema !== 1 || !validIds(index.ids)
|
|
119
|
+
|| (index.backfilled !== undefined && index.backfilled !== true))
|
|
120
|
+
throw new TasraError('Invalid paid operation index');
|
|
121
|
+
return index;
|
|
122
|
+
}
|
|
123
|
+
async function loadSegment(store, n) {
|
|
124
|
+
const segment = await store.load(segmentKey(n));
|
|
125
|
+
if (segment === undefined)
|
|
126
|
+
return undefined;
|
|
127
|
+
if (!segment || segment.schema !== 1 || !validIds(segment.ids) || segment.ids.length > SEGMENT_IDS)
|
|
128
|
+
throw new TasraError('Invalid paid operation index');
|
|
129
|
+
return segment;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* In-process state per store IDENTITY ({@link storeIdentity}): one entry per backing state, shared by
|
|
133
|
+
* every store object on it (an application may open one file store object per call on one
|
|
134
|
+
* directory), else per store object. Bounded by the directories a process uses.
|
|
135
|
+
*/
|
|
136
|
+
function perStore() {
|
|
137
|
+
const named = new Map(), objects = new WeakMap();
|
|
138
|
+
return {
|
|
139
|
+
get: (store) => { const id = storeIdentity(store); return typeof id === 'string' ? named.get(id) : objects.get(id); },
|
|
140
|
+
set: (store, value) => { const id = storeIdentity(store); if (typeof id === 'string')
|
|
141
|
+
named.set(id, value);
|
|
142
|
+
else
|
|
143
|
+
objects.set(id, value); },
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/** First segment that may still have room, per store identity: a hint only, always probed forward. */
|
|
147
|
+
const segmentHints = perStore();
|
|
148
|
+
/** Every indexed id, oldest first, without duplicates: the legacy list, then each segment. */
|
|
149
|
+
async function loadIndex(store) {
|
|
150
|
+
const ids = new Set((await loadIndexRecord(store)).ids.map(id => id.toLowerCase()));
|
|
151
|
+
for (let n = 0;; n++) {
|
|
152
|
+
const segment = await loadSegment(store, n);
|
|
153
|
+
if (!segment)
|
|
154
|
+
break;
|
|
155
|
+
for (const id of segment.ids)
|
|
156
|
+
ids.add(id.toLowerCase());
|
|
157
|
+
}
|
|
158
|
+
return [...ids];
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Stage the index entries of `ids` (lowercase, in order) into the segments: the first segment with
|
|
162
|
+
* room from this store's hint, then the next ones. Segments fill in order; a crash between
|
|
163
|
+
* filling one and starting the next leaves nothing to repair, because the next writer probes
|
|
164
|
+
* forward from the hint to the first one with room. Needs the index lock. Returns the last segment
|
|
165
|
+
* staged: the caller moves the hint there only once the commit landed, so a failed commit never
|
|
166
|
+
* leaves the hint past a segment that was never written (a gap would hide every later segment).
|
|
167
|
+
*/
|
|
168
|
+
async function stageIndexEntries(store, commit, ids) {
|
|
169
|
+
const left = [...new Set(ids)];
|
|
170
|
+
let last;
|
|
171
|
+
for (let n = segmentHints.get(store) ?? 0; left.length > 0; n++) {
|
|
172
|
+
const segment = await loadSegment(store, n);
|
|
173
|
+
for (const id of segment?.ids ?? []) {
|
|
174
|
+
const at = left.indexOf(id);
|
|
175
|
+
if (at !== -1)
|
|
176
|
+
left.splice(at, 1);
|
|
177
|
+
}
|
|
178
|
+
if (left.length === 0)
|
|
179
|
+
return last;
|
|
180
|
+
if (!segment || segment.ids.length < SEGMENT_IDS) {
|
|
181
|
+
const added = left.splice(0, SEGMENT_IDS - (segment?.ids.length ?? 0));
|
|
182
|
+
commit.stage(segmentKey(n), { schema: 1, ids: [...segment?.ids ?? [], ...added] });
|
|
183
|
+
last = n;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return last;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Per store identity (not per store object: one store object per call on one directory would
|
|
190
|
+
* otherwise commit every new operation on its own, one after another, on the global index lock):
|
|
191
|
+
* the journal commit running now, and the new operations waiting for the next one.
|
|
192
|
+
*/
|
|
193
|
+
const newOperationQueues = perStore();
|
|
194
|
+
/**
|
|
195
|
+
* Journal a new operation's record and index it, refusing a request that is already journaled.
|
|
196
|
+
* Concurrent new operations of one process share ONE commit instead of queueing on the global index
|
|
197
|
+
* lock one by one: every record lock and the index lock are taken together, and the records and the
|
|
198
|
+
* index segment are published with one data barrier and one directory sync. A caller joins the next
|
|
199
|
+
* commit that has not started, so its record is never written before its call.
|
|
200
|
+
*
|
|
201
|
+
* A crash before this resolves may leave any subset. A record without its index entry was always
|
|
202
|
+
* possible (a crash between the two former writes): it is found by its request ID, which
|
|
203
|
+
* `onRequestId` already handed out. An index entry without its record is listed by no one
|
|
204
|
+
* (listPaidOperations skips it). Nothing was sent for either: the reservation starts only after.
|
|
205
|
+
*/
|
|
206
|
+
function journalNewOperation(store, requestId, record) {
|
|
207
|
+
let queue = newOperationQueues.get(store);
|
|
208
|
+
if (!queue) {
|
|
209
|
+
queue = { running: Promise.resolve() };
|
|
210
|
+
newOperationQueues.set(store, queue);
|
|
211
|
+
}
|
|
212
|
+
let batch = queue.waiting;
|
|
213
|
+
if (!batch) {
|
|
214
|
+
const own = [], q = queue;
|
|
215
|
+
batch = q.waiting = own;
|
|
216
|
+
q.running = q.running.then(() => { if (q.waiting === own)
|
|
217
|
+
q.waiting = undefined; return commitNewOperations(store, own); });
|
|
218
|
+
}
|
|
219
|
+
const joined = batch;
|
|
220
|
+
return new Promise((resolve, reject) => { joined.push({ key: recordKey(requestId), id: requestId.toLowerCase(), record, resolve, reject }); });
|
|
221
|
+
}
|
|
222
|
+
/** One journal commit for a batch of new operations; settles every caller, never rejects. */
|
|
223
|
+
async function commitNewOperations(store, batch) {
|
|
224
|
+
const refused = new Map();
|
|
225
|
+
try {
|
|
226
|
+
let staged;
|
|
227
|
+
await withCommit(store, [INDEX_KEY, ...batch.map(op => op.key)], async (commit) => {
|
|
228
|
+
const created = [], seen = new Set();
|
|
229
|
+
for (const op of batch) {
|
|
230
|
+
try {
|
|
231
|
+
if (seen.has(op.key) || await store.load(op.key) !== undefined)
|
|
232
|
+
throw new TasraError('Paid operation already journaled; resume it');
|
|
233
|
+
}
|
|
234
|
+
catch (error) {
|
|
235
|
+
refused.set(op, error);
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
seen.add(op.key);
|
|
239
|
+
commit.stage(op.key, op.record);
|
|
240
|
+
created.push(op.id);
|
|
241
|
+
}
|
|
242
|
+
staged = await stageIndexEntries(store, commit, created);
|
|
243
|
+
});
|
|
244
|
+
if (staged !== undefined)
|
|
245
|
+
segmentHints.set(store, staged);
|
|
246
|
+
}
|
|
247
|
+
catch (error) {
|
|
248
|
+
for (const op of batch)
|
|
249
|
+
op.reject(refused.get(op) ?? error);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
for (const op of batch) {
|
|
253
|
+
const error = refused.get(op);
|
|
254
|
+
if (error === undefined)
|
|
255
|
+
op.resolve();
|
|
256
|
+
else
|
|
257
|
+
op.reject(error);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
/** Index journals written before the index existed, once per store (by payment expiry). */
|
|
261
|
+
async function backfillIndex(store) {
|
|
262
|
+
if ((await loadIndexRecord(store)).backfilled)
|
|
263
|
+
return;
|
|
264
|
+
if (typeof store.list !== 'function')
|
|
265
|
+
throw new TasraError('Backfilling the paid operation index needs a store that can list its keys');
|
|
266
|
+
const list = store.list.bind(store);
|
|
267
|
+
await store.withLock(INDEX_KEY, async () => {
|
|
268
|
+
const index = await loadIndexRecord(store);
|
|
269
|
+
if (index.backfilled)
|
|
270
|
+
return;
|
|
271
|
+
const indexed = new Set(await loadIndex(store));
|
|
272
|
+
const found = [];
|
|
273
|
+
for (const key of await list(RECORD_PREFIX)) {
|
|
274
|
+
if (!RECORD_KEY.test(key))
|
|
275
|
+
continue;
|
|
276
|
+
const id = `0x${key.slice(RECORD_PREFIX.length)}`;
|
|
277
|
+
if (indexed.has(id))
|
|
278
|
+
continue;
|
|
279
|
+
const record = await loadRecord(store, id);
|
|
280
|
+
if (record)
|
|
281
|
+
found.push({ id, expires: record.payment.expires });
|
|
282
|
+
}
|
|
283
|
+
found.sort((a, b) => a.expires - b.expires);
|
|
284
|
+
// Unindexed journals predate the index, so they come first.
|
|
285
|
+
await store.save(INDEX_KEY, { schema: 1, ids: [...found.map(f => f.id), ...index.ids], backfilled: true });
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
function random32() { return globalThis.crypto.getRandomValues(new Uint8Array(32)); }
|
|
289
|
+
function positive(value, name) { if (typeof value !== 'bigint' || value <= 0n)
|
|
290
|
+
throw new TasraError(`Paid operation requires a finite positive ${name}`); }
|
|
291
|
+
function sleep(ms, signal) {
|
|
292
|
+
return new Promise((resolve, reject) => {
|
|
293
|
+
signal.throwIfAborted();
|
|
294
|
+
const done = () => { signal.removeEventListener('abort', abort); resolve(); };
|
|
295
|
+
const timer = setTimeout(done, ms);
|
|
296
|
+
const abort = () => { clearTimeout(timer); reject(signal.reason); };
|
|
297
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
function validateConfig(config) {
|
|
301
|
+
const d = config.deployment;
|
|
302
|
+
for (const address of [d.settlement, d.keyRegistry, d.verifierSet, d.accountantSet, d.beacon]) {
|
|
303
|
+
if (typeof address !== 'string' || !/^0x[0-9a-f]{40}$/i.test(address) || /^0x0{40}$/i.test(address))
|
|
304
|
+
throw new TasraError('Paid operation requires independently approved Settlement, registries and beacon');
|
|
305
|
+
}
|
|
306
|
+
positive(config.limits.maxCost, 'TASRA limit');
|
|
307
|
+
positive(config.limits.maxGas, 'gas limit');
|
|
308
|
+
positive(config.limits.maxGasPrice, 'gas price limit');
|
|
309
|
+
if (!config.accountantUrls.length || config.accountantUrls.length > 16 || new Set(config.accountantUrls).size !== config.accountantUrls.length)
|
|
310
|
+
throw new TasraError('Paid operation requires distinct approved accountant URLs');
|
|
311
|
+
if (config.gasPayer.chain.id !== d.chainId)
|
|
312
|
+
throw new TasraError('Gas payer is bound to another chain');
|
|
313
|
+
if (config.chain.addresses.ServiceRegistry?.toLowerCase() !== config.agent.profile.approval.registry.toLowerCase())
|
|
314
|
+
throw new TasraError('Agent profile is approved on another ServiceRegistry');
|
|
315
|
+
const wait = config.snapshotWaitMs ?? 180_000, poll = config.pollIntervalMs ?? 1_000;
|
|
316
|
+
if (!Number.isSafeInteger(wait) || wait < 1 || wait > 300_000 || !Number.isSafeInteger(poll) || poll < 10 || poll > 60_000)
|
|
317
|
+
throw new TasraError('Invalid paid operation timing');
|
|
318
|
+
if (config.allowances?.enabled)
|
|
319
|
+
validateAllowanceOptions(config.allowances, config.limits);
|
|
320
|
+
}
|
|
321
|
+
function allowanceEnv(config) {
|
|
322
|
+
if (!config.allowances?.enabled)
|
|
323
|
+
return undefined;
|
|
324
|
+
const d = { ...config.deployment };
|
|
325
|
+
return { client: config.chain.client, deployment: config.deployment, creator: config.creator, gasPayer: config.gasPayer, store: config.store,
|
|
326
|
+
accountantUrls: config.accountantUrls, allowLocalHttp: config.allowLocalHttp, limits: config.limits, options: config.allowances,
|
|
327
|
+
// ADR-0090 D7 reserve-ahead: the next draw, verified exactly as a session message's pinned discovery.
|
|
328
|
+
discover: (slot, epoch) => discoverPaidOperationContext(config.chain.client, d, slot, { allowLocalHttp: config.allowLocalHttp,
|
|
329
|
+
defaultVerificationPolicy: d.defaultVerificationPolicy, fundedByAllowance: true, verificationEpoch: epoch }) };
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Prepaid allowances: open (reserve) a slot's allowance lanes BEFORE its first paid operation, like loading
|
|
333
|
+
* a card, so no user operation waits for an allowance reservation (approve + reserve transactions
|
|
334
|
+
* and their receipts) inside it. Operations otherwise open a cold lane themselves: the first one on
|
|
335
|
+
* each lane then falls back to a per-operation reservation or waits for the lane.
|
|
336
|
+
*
|
|
337
|
+
* Each lane is reserved through the same journaled reservation as an operation's background refill
|
|
338
|
+
* (intent signed by the creator, `signing`, then `prepared`, `submitted` and `confirmed` under the
|
|
339
|
+
* durable payer claim and the dedicated payer queue), with its own FRESH discovery (never a context
|
|
340
|
+
* cached across lanes); a lane that needs nothing is reported `not-needed` without any read or
|
|
341
|
+
* send, so the call is idempotent. A lane failure is reported on that lane only; the other lanes
|
|
342
|
+
* are unaffected. Never throws for a lane's outcome; throws only for invalid input or
|
|
343
|
+
* configuration, and when the signal was aborted before anything started.
|
|
344
|
+
*
|
|
345
|
+
* Draw lanes (session grants) are not opened here: their draw is known only once a
|
|
346
|
+
* grant exists.
|
|
347
|
+
* @param config Approved deployment, creator, gas payer, store, accountants, limits and `allowances` (enabled).
|
|
348
|
+
* @param request Slot, lanes, concurrency, readiness for the coming work and cancellation.
|
|
349
|
+
*/
|
|
350
|
+
export async function prepareAllowances(config, request) {
|
|
351
|
+
validateConfig(config);
|
|
352
|
+
const env = allowanceEnv(config);
|
|
353
|
+
if (!env)
|
|
354
|
+
throw new TasraError('Opening allowances needs the allowances option enabled');
|
|
355
|
+
const slot = request.slot, signal = request.signal ?? new AbortController().signal;
|
|
356
|
+
if (!HEX32.test(slot))
|
|
357
|
+
throw new TasraError('Invalid paid operation slot');
|
|
358
|
+
const count = allowanceLaneCount(config.allowances);
|
|
359
|
+
const lanes = request.lanes ? [...request.lanes] : Array.from({ length: count }, (_, i) => i);
|
|
360
|
+
if (lanes.length === 0 || lanes.some(l => !Number.isSafeInteger(l) || l < 0 || l >= count) || new Set(lanes).size !== lanes.length)
|
|
361
|
+
throw new TasraError(`Allowance lanes must be distinct indices 0..${count - 1}`);
|
|
362
|
+
const concurrency = request.concurrency ?? 4;
|
|
363
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 8)
|
|
364
|
+
throw new TasraError('Allowance concurrency must be 1..8');
|
|
365
|
+
const ready = { minOperations: request.minOperations, minLifetimeSecs: request.minLifetimeSecs };
|
|
366
|
+
validateLaneReadiness(env, ready);
|
|
367
|
+
if (request.operationTtlSecs !== undefined && request.actions === undefined)
|
|
368
|
+
throw new TasraError('Allowance operationTtlSecs needs actions');
|
|
369
|
+
const actions = request.actions, ttlSecs = request.operationTtlSecs ?? 600;
|
|
370
|
+
if (actions !== undefined) {
|
|
371
|
+
if (actions.length === 0 || new Set(actions).size !== actions.length)
|
|
372
|
+
throw new TasraError('Allowance readiness actions must be distinct and non-empty');
|
|
373
|
+
allowanceActionBits(actions);
|
|
374
|
+
// Before any read; what the configured allowances fund is judged once the slot's mode is known.
|
|
375
|
+
validateReadinessHorizon(env, request.minLifetimeSecs ?? 0, ttlSecs);
|
|
376
|
+
}
|
|
377
|
+
signal.throwIfAborted();
|
|
378
|
+
if (config.billing)
|
|
379
|
+
await config.billing.requirePrepaid(slot);
|
|
380
|
+
const d = { ...config.deployment }, client = config.chain.client;
|
|
381
|
+
// One fresh, canonical discovery per reservation, exactly as an allowance-funded operation discovers.
|
|
382
|
+
const discover = async () => {
|
|
383
|
+
const readiness = AbortSignal.any([signal, AbortSignal.timeout(config.snapshotWaitMs ?? 180_000)]);
|
|
384
|
+
const context = await waitForPaidSnapshot(() => discoverPaidOperationContext(client, d, slot, { allowLocalHttp: config.allowLocalHttp, defaultVerificationPolicy: d.defaultVerificationPolicy, coordinator: request.coordinator, fundedByAllowance: true }), readiness, () => sleep(1_000, readiness));
|
|
385
|
+
if (context.creator.toLowerCase() !== config.creator.address.toLowerCase())
|
|
386
|
+
throw new TasraError('Paid operations are signed by the slot creator; this signer is not it');
|
|
387
|
+
return context;
|
|
388
|
+
};
|
|
389
|
+
const results = lanes.map(lane => ({ lane, outcome: 'cancelled' }));
|
|
390
|
+
if (actions !== undefined) {
|
|
391
|
+
// One fresh discovery judges every lane against what an operation would be paid under now.
|
|
392
|
+
let context;
|
|
393
|
+
try {
|
|
394
|
+
context = await discover();
|
|
395
|
+
}
|
|
396
|
+
catch (error) {
|
|
397
|
+
return { slot, lanes: lanes.map(lane => signal.aborted ? { lane, outcome: 'cancelled', error } : { lane, outcome: 'failed', error }) };
|
|
398
|
+
}
|
|
399
|
+
// Threshold ECDSA slots (mode 2 secp256k1, mode 4 P-256) pay `sign` as `eoa-sign` (as paymentAttempt does).
|
|
400
|
+
const paid = [...new Set(actions.map((a) => a === 'sign' && (context.mode === 2 || context.mode === 4) ? 'eoa-sign' : a))];
|
|
401
|
+
ready.work = { context, actions: paid, ttlSecs };
|
|
402
|
+
validateLaneReadiness(env, ready);
|
|
403
|
+
}
|
|
404
|
+
let next = 0;
|
|
405
|
+
const worker = async () => {
|
|
406
|
+
while (next < lanes.length && !signal.aborted) {
|
|
407
|
+
const i = next++, lane = lanes[i];
|
|
408
|
+
try {
|
|
409
|
+
results[i] = { lane, outcome: await prepareAllowanceLane(env, slot, lane, discover, signal, ready) };
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
results[i] = signal.aborted ? { lane, outcome: 'cancelled', error } : { lane, outcome: 'failed', error };
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, lanes.length) }, worker));
|
|
417
|
+
return { slot, lanes: results };
|
|
418
|
+
}
|
|
419
|
+
/** The allowance path refused this operation for good; it was journaled `failed` and is retried once per operation. */
|
|
420
|
+
class AllowanceFallback extends Error {
|
|
421
|
+
requestId;
|
|
422
|
+
constructor(requestId, cause) {
|
|
423
|
+
super('allowance debit refused; falling back to a per-operation reservation', { cause });
|
|
424
|
+
this.requestId = requestId;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/** Decode a commitment-verified retained IBE result into a combinable partial. */
|
|
428
|
+
async function ibePartial(resultJson, nodeUrl, record, options, chainId) {
|
|
429
|
+
const d = JSON.parse(resultJson);
|
|
430
|
+
const binding = record.params.decryption, trusted = options.verifyingShares?.get(d.identifier);
|
|
431
|
+
if (!binding || !options.recipient || options.identity === undefined || !trusted || trusted.length !== 144 || d.epoch !== binding.ciphertext_epoch || d.key_slot_id.replace(/^0x/, '').toLowerCase() !== record.payment.slot.replace(/^0x/, '').toLowerCase())
|
|
432
|
+
throw new Error('Original recipient, identity, epoch and authenticated sharing required for sealed IBE recovery');
|
|
433
|
+
const verifying = base64Decode(d.verifying_share);
|
|
434
|
+
if (verifying.length !== 144 || !trusted.every((b, i) => b === verifying[i]))
|
|
435
|
+
throw new Error('Recovered verifying share differs from authenticated package');
|
|
436
|
+
const content = sha256(new TextEncoder().encode(options.identity));
|
|
437
|
+
const digest = recipientPayloadDigest(content, binding.ciphertext_epoch, options.recipient.recipient);
|
|
438
|
+
if (toHex(digest).toLowerCase() !== record.payloadDigest.toLowerCase())
|
|
439
|
+
throw new Error('Recovery recipient or identity differs from original authorization');
|
|
440
|
+
const hash = requestHash(chainId, hexToBytes(record.payment.slot), 'ibe-extract', digest);
|
|
441
|
+
const value = await options.recipient.open(d.sealed_share, hash, d.identifier, d.epoch, trusted);
|
|
442
|
+
try {
|
|
443
|
+
ibeVerifyShare(new Map([[d.identifier, trusted.slice(0, 96)]]), new TextEncoder().encode(options.identity), { identifier: d.identifier, value });
|
|
444
|
+
return { keySlotId: d.key_slot_id, identifier: d.identifier, value, verifyingShareG2: trusted.slice(0, 96), epoch: d.epoch, nodeUrl };
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
value.fill(0);
|
|
448
|
+
throw error;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Authorize one paid committee operation. Returns a handle whose `execute` runs the keeper
|
|
453
|
+
* operation once. Throws PaidOperationRecoveryError when a reservation, session write or the
|
|
454
|
+
* execution outcome is uncertain; continue with {@link resumePaidOperation}, never by calling
|
|
455
|
+
* this again (that would be a second payment).
|
|
456
|
+
* @param config Approved deployment, creator, gas payer, store, agent, accountants and limits.
|
|
457
|
+
* @param request Slot, operation, original rule, holder strategy and cancellation.
|
|
458
|
+
*/
|
|
459
|
+
export async function paidOperation(config, request) {
|
|
460
|
+
validateConfig(config);
|
|
461
|
+
if (!config.allowances?.enabled)
|
|
462
|
+
return paymentAttempt(config, request, false);
|
|
463
|
+
// ADR-0090: at most one allowance attempt; a definite refusal (journaled `failed`, no voucher)
|
|
464
|
+
// falls back to a fresh per-operation payment with its own request ID.
|
|
465
|
+
try {
|
|
466
|
+
return await paymentAttempt(config, request, true);
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
if (!(error instanceof AllowanceFallback))
|
|
470
|
+
throw error;
|
|
471
|
+
return paymentAttempt(config, request, false);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* One per-operation payment. A refused reservation is never replaced by a re-signed intent here:
|
|
476
|
+
* an intent that reached an accountant can still be reserved by anyone holding it (the accountant
|
|
477
|
+
* accepts a client-pinned quote block up to MAX_QUOTE_AGE old, and `reservePrepaid*` is
|
|
478
|
+
* permissionless) until its payment expires, so a second intent could be charged as well. The
|
|
479
|
+
* journal stays `reserving`, reconcilable (`reconcilePaidOperation`, `resumePaidOperation`) and
|
|
480
|
+
* not abandonable until that window has passed; a reservation that lands meanwhile is found by
|
|
481
|
+
* reconciliation, and one left unused is refunded by the accountants' unused-reservation close.
|
|
482
|
+
*/
|
|
483
|
+
/**
|
|
484
|
+
* A per-operation reservation that waited for its payer past its verifier epoch, refused BEFORE the
|
|
485
|
+
* first prepare (see {@link reserve}): the signed intent never left this process, so it is
|
|
486
|
+
* journaled `failed` and the operation is signed once more at a current epoch. A
|
|
487
|
+
* {@link paidOperation} does that itself (once); a {@link paidSessionDecrypt} pays the GRANT's
|
|
488
|
+
* draw, so it throws this and its caller pays again on a refreshed grant (`decryptInSession`).
|
|
489
|
+
* `beaconEpoch` is this process's own chain read that refused it.
|
|
490
|
+
*/
|
|
491
|
+
export class NewerVerifierEpoch extends Error {
|
|
492
|
+
requestId;
|
|
493
|
+
beaconEpoch;
|
|
494
|
+
/** Stable reason. */
|
|
495
|
+
code = 'newer-verifier-epoch';
|
|
496
|
+
constructor(
|
|
497
|
+
/** The refused reservation's payment request id. */
|
|
498
|
+
requestId,
|
|
499
|
+
/** The beacon epoch this process read when it refused. */
|
|
500
|
+
beaconEpoch) {
|
|
501
|
+
super('the verifier epoch moved on while this reservation waited for its payer; nothing was sent');
|
|
502
|
+
this.requestId = requestId;
|
|
503
|
+
this.beaconEpoch = beaconEpoch;
|
|
504
|
+
this.name = 'NewerVerifierEpoch';
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async function paymentAttempt(config, request, useAllowance) {
|
|
508
|
+
try {
|
|
509
|
+
return await paidOperationAttempt(config, request, useAllowance);
|
|
510
|
+
}
|
|
511
|
+
catch (error) {
|
|
512
|
+
if (!(error instanceof NewerVerifierEpoch))
|
|
513
|
+
throw error;
|
|
514
|
+
// Once only: a second wait past two epochs is reported like any other refusal.
|
|
515
|
+
try {
|
|
516
|
+
return await paidOperationAttempt(config, request, useAllowance);
|
|
517
|
+
}
|
|
518
|
+
catch (again) {
|
|
519
|
+
if (again instanceof NewerVerifierEpoch)
|
|
520
|
+
throw new PaidOperationRecoveryError(again.requestId, 'reservation', again, { code: 'reservation-refused', resumable: false });
|
|
521
|
+
throw again;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
async function paidOperationAttempt(config, request, useAllowance) {
|
|
526
|
+
const d = { ...config.deployment }, client = config.chain.client, signal = request.signal ?? new AbortController().signal;
|
|
527
|
+
const slot = request.slot;
|
|
528
|
+
if (!HEX32.test(slot))
|
|
529
|
+
throw new TasraError('Invalid paid operation slot');
|
|
530
|
+
// Without a cached detector, discovery itself refuses a non-prepaid slot (the Settlement version,
|
|
531
|
+
// prepaidEnabled and prepaidFromGenesis, read in its own block-pinned round) with the same typed
|
|
532
|
+
// BillingModeError, instead of a separate billing observation of ~4 sequential reads before it.
|
|
533
|
+
if (config.billing)
|
|
534
|
+
await config.billing.requirePrepaid(slot);
|
|
535
|
+
const readiness = AbortSignal.any([signal, AbortSignal.timeout(config.snapshotWaitMs ?? 180_000)]);
|
|
536
|
+
// ADR-0090: an allowance-funded payment names its allowance's draw, so while a new epoch's anchors
|
|
537
|
+
// land (no admissible complete draw at this head) an operation a current allowance serves need not
|
|
538
|
+
// wait for them: discovery returns an UNDRAWN context, and only when no lane serves the operation
|
|
539
|
+
// is the slot discovered again with the bounded anchor wait. Session openings (a pinned draw) wait.
|
|
540
|
+
const undrawnOk = useAllowance && request.sessionGrant === undefined;
|
|
541
|
+
const discover = (undrawnDuringAnchorGap) => waitForPaidSnapshot(() => discoverPaidOperationContext(client, d, slot, { allowLocalHttp: config.allowLocalHttp, defaultVerificationPolicy: d.defaultVerificationPolicy, coordinator: request.coordinator, fundedByAllowance: useAllowance,
|
|
542
|
+
...undrawnDuringAnchorGap ? { undrawnDuringAnchorGap } : {} }), readiness, () => sleep(1_000, readiness));
|
|
543
|
+
// The rule the holder will see must be the one the slot committed to on chain. Discovery read the
|
|
544
|
+
// slot at its canonical, rechecked block hash; a context without that field is read again here.
|
|
545
|
+
// A policy bootstrap is checked offline first (signature, deployment, slot, audience, scope,
|
|
546
|
+
// lifetime, rule hash); its on-chain half below. Without one, the rule and salt reproduce it.
|
|
547
|
+
const policy = 'policy' in request.rule
|
|
548
|
+
? (await verifySlotPolicyBootstrap(request.rule.policy, { chainId: d.chainId, keyRegistry: d.keyRegistry, slot, audience: request.rule.audience,
|
|
549
|
+
action: request.operation.action, signer: config.creator.address })).bootstrap
|
|
550
|
+
: undefined;
|
|
551
|
+
const rawRule = policy ? policy.rule : request.rule.rule;
|
|
552
|
+
const expectedCommitment = policy ? policy.statement.ruleCommitment : ruleCommitment(request.rule.salt, rawRule).toLowerCase();
|
|
553
|
+
const checked = async (context) => {
|
|
554
|
+
if (context.creator.toLowerCase() !== config.creator.address.toLowerCase())
|
|
555
|
+
throw new TasraError('Paid operations are signed by the slot creator; this signer is not it');
|
|
556
|
+
let observed = { ruleCommitment: context.ruleCommitment ?? '', ruleVersion: context.ruleVersion };
|
|
557
|
+
if (context.ruleCommitment === undefined || (policy && context.ruleVersion === undefined)) {
|
|
558
|
+
const original = await client.readContract({ address: d.keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [slot], blockNumber: context.blockNumber });
|
|
559
|
+
if ((await client.getBlock({ blockNumber: context.blockNumber })).hash !== context.blockHash)
|
|
560
|
+
throw new TasraError('Rule observation reorganized');
|
|
561
|
+
observed = { ruleCommitment: original.ruleCommitment, ruleVersion: Number(original.ruleVersion) };
|
|
562
|
+
}
|
|
563
|
+
if (policy)
|
|
564
|
+
requireCurrentSlotPolicy(policy.statement, config.creator.address, { creator: context.creator, ruleCommitment: observed.ruleCommitment, ruleVersion: observed.ruleVersion ?? -1 });
|
|
565
|
+
else if (observed.ruleCommitment.toLowerCase() !== expectedCommitment)
|
|
566
|
+
throw new TasraError('Supplied rule or salt differs from the slot commitment');
|
|
567
|
+
return context;
|
|
568
|
+
};
|
|
569
|
+
let context = await checked(await discover(undrawnOk));
|
|
570
|
+
// A bootstrap older than one this store already accepted for the slot and application is a replay.
|
|
571
|
+
if (policy)
|
|
572
|
+
await admitSlotPolicySequence(config.store, policy.statement);
|
|
573
|
+
// Validate the DCQL JSON, but retain the provisioned bytes. The chain's salted
|
|
574
|
+
// commitment canonicalizes JSON; verifier tokens bind keccak256(raw rule).
|
|
575
|
+
// Rewriting whitespace/key order here changes the expected token hash.
|
|
576
|
+
canonicalize(rawRule);
|
|
577
|
+
// The holder's presentation family must be the rule's: refused before anything is signed or spent.
|
|
578
|
+
const oauthHolder = request.holder?.kind === 'oauth';
|
|
579
|
+
if (oauthRule(rawRule) !== oauthHolder)
|
|
580
|
+
throw new TasraError(oauthHolder ? 'An OAuth holder needs an OAuth (oauth+access-token+dpop or kk_oauth) slot rule' : 'An OAuth slot rule needs an OAuth holder');
|
|
581
|
+
// A session grant opens only from a KEM decrypt presentation (checked again, with the slots, before signing).
|
|
582
|
+
if (request.sessionGrant && request.operation.action !== 'decrypt')
|
|
583
|
+
throw new TasraError('A session grant opens only from a KEM decrypt presentation');
|
|
584
|
+
const ttlSecs = request.operation.ttlSecs ?? 600;
|
|
585
|
+
if (!Number.isSafeInteger(ttlSecs) || ttlSecs <= 0 || ttlSecs > 3600)
|
|
586
|
+
throw new TasraError('Paid operation lifetime must be 1..3600 seconds');
|
|
587
|
+
const built = presentationOperationTypedData({ action: request.operation.action, message: request.operation.message, identity: request.operation.identity,
|
|
588
|
+
payloadDigest: request.operation.payloadDigest, decryption: request.operation.decryption, chainId: d.chainId, keyRegistry: d.keyRegistry, slotId: slot,
|
|
589
|
+
description: request.operation.description ?? 'Paid Tasra operation', nowSecs: Math.floor(Date.now() / 1000), ttlSecs });
|
|
590
|
+
const randomBytes = random32(), random = toHex(randomBytes);
|
|
591
|
+
randomBytes.fill(0);
|
|
592
|
+
const operationSig = await config.creator.signTypedData(built.typedData);
|
|
593
|
+
// Threshold ECDSA slots (mode 2 secp256k1, mode 4 P-256) sign through the keeper's eoa-digest route, paid as `eoa-sign`.
|
|
594
|
+
const action = request.operation.action === 'sign' && (context.mode === 2 || context.mode === 4) ? 'eoa-sign' : request.operation.action;
|
|
595
|
+
// ADR-0090: a lane with room funds this operation by voucher; its verification and keeper
|
|
596
|
+
// fields are the allowance's (the readers judge them at the allowance's assignment block).
|
|
597
|
+
const env = useAllowance ? allowanceEnv(config) : undefined;
|
|
598
|
+
// ADR-0090 D7: a session grant is drawn on the OPENING payment's draw and judged at the LIVE
|
|
599
|
+
// beacon by every verifier and keeper, while a voucher keeps its allowance's (older) draw, whose
|
|
600
|
+
// epoch is judged at the allowance's quote block. So a session-mode opening is funded only by an
|
|
601
|
+
// allowance drawn on this fresh discovery's draw, else by a per-operation reservation at it -
|
|
602
|
+
// never by a voucher whose grant no verifier would sign (C7 fleet: `session_context_changed`).
|
|
603
|
+
const lane = { action, expires: built.operation.exp, drawPinned: request.sessionGrant !== undefined };
|
|
604
|
+
let ticket = env ? await selectAllowanceLane(env, context, lane) : undefined;
|
|
605
|
+
// Undrawn and no lane serves it now: discover the draw (waiting, bounded, for its anchors) and
|
|
606
|
+
// select again, which may start or wait for a lane reservation or fall back per operation.
|
|
607
|
+
if (!ticket && context.undrawn) {
|
|
608
|
+
context = await checked(await discover(false));
|
|
609
|
+
if (context.undrawn)
|
|
610
|
+
throw new TasraError('Paid operation discovery returned no verifier draw');
|
|
611
|
+
ticket = env ? await selectAllowanceLane(env, context, lane) : undefined;
|
|
612
|
+
}
|
|
613
|
+
// A voucher payment names its allowance's draw; a per-operation one this context's, which an
|
|
614
|
+
// undrawn context does not have (refused, never zero fields).
|
|
615
|
+
const unsigned = { ...ticket ? ticket.fields : drawnIntentFields(context), action,
|
|
616
|
+
payload_digest: toHex(built.payloadDigest), session_commitment: paymentSessionCommitment(random, config.agent.profile.clientId, built.operation.exp),
|
|
617
|
+
nonce: toHex(random32()), max_cost: config.limits.maxCost.toString(), expires: built.operation.exp, ...ticket ? { allowance_id: ticket.allowanceId } : {} };
|
|
618
|
+
const payment = { ...unsigned, signature: await config.creator.signTypedData(paymentIntentTypedData(unsigned)) };
|
|
619
|
+
const expected = { slot, action: payment.action, payloadDigest: payment.payload_digest };
|
|
620
|
+
const requestId = prepaidRequestId(payment);
|
|
621
|
+
// With a head follower, this request's own settlement state is pre-read at each new head.
|
|
622
|
+
followPaidRequest(client, d, payment);
|
|
623
|
+
await request.onRequestId?.(requestId);
|
|
624
|
+
signal.throwIfAborted();
|
|
625
|
+
const { witnesses } = await fetchDrawnVerifierWitnesses(config.accountantUrls, payment, d.verifierSet, { signal: AbortSignal.any([signal, AbortSignal.timeout(Math.min(150_000, ttlSecs * 1000))]), fetch: config.fetch,
|
|
626
|
+
waitForPublicationMs: Math.min(config.snapshotWaitMs ?? 180_000, 150_000, ttlSecs * 1000) });
|
|
627
|
+
const record = { schema: 1, phase: 'reserving', payment, expected, members: witnesses, rule: rawRule,
|
|
628
|
+
ruleSalt: policy ? ZERO_SALT : request.rule.salt, ...(policy ? { policy: { statement: structuredClone(policy.statement), signature: policy.signature } } : {}),
|
|
629
|
+
params: { operation: built.operation, operationSig, messageHex: built.messageHex, random, ...(oauthHolder ? { kind: 'oauth' } : {}), ...(request.operation.decryption ? { decryption: structuredClone(request.operation.decryption) } : {}),
|
|
630
|
+
...(request.sessionGrant ? { sessionGrant: structuredClone(request.sessionGrant.session_grant) } : {}) }, coordinator: context.coordinator, contributors: context.contributors,
|
|
631
|
+
action: request.operation.action, payloadDigest: toHex(built.payloadDigest), payer: config.gasPayer.account.address, ...ticket ? { allowance: { lane: ticket.lane } } : {} };
|
|
632
|
+
await journalNewOperation(config.store, requestId, record);
|
|
633
|
+
try {
|
|
634
|
+
await reserve(config, record, signal);
|
|
635
|
+
}
|
|
636
|
+
catch (error) {
|
|
637
|
+
if (ticket && error instanceof PaidOperationRecoveryError && error.code === 'reservation-failed' && error.cause instanceof AllowanceRefusedError)
|
|
638
|
+
throw new AllowanceFallback(requestId, error);
|
|
639
|
+
throw error;
|
|
640
|
+
}
|
|
641
|
+
return continueOperation(config, requestId, request.holder, signal, request.observeRequest);
|
|
642
|
+
}
|
|
643
|
+
class NoLongerReserving extends Error {
|
|
644
|
+
}
|
|
645
|
+
/** Whether a provisioned rule authorizes OAuth access tokens (a kk_oauth envelope or an OAuth-format DCQL query). */
|
|
646
|
+
function oauthRule(rule) {
|
|
647
|
+
if (isOauthEnvelope(rule))
|
|
648
|
+
return true;
|
|
649
|
+
let parsed;
|
|
650
|
+
try {
|
|
651
|
+
parsed = JSON.parse(rule);
|
|
652
|
+
}
|
|
653
|
+
catch {
|
|
654
|
+
return false;
|
|
655
|
+
}
|
|
656
|
+
const credentials = parsed?.credentials;
|
|
657
|
+
if (!Array.isArray(credentials) || credentials.length === 0)
|
|
658
|
+
return false;
|
|
659
|
+
const formats = credentials.map(c => typeof c?.format === 'string' && isOauthFormat(c.format));
|
|
660
|
+
if (formats.some(f => f) && !formats.every(f => f))
|
|
661
|
+
throw new TasraError('Slot rule mixes OAuth and wallet credential formats');
|
|
662
|
+
return formats[0] === true;
|
|
663
|
+
}
|
|
664
|
+
async function reserve(config, record, signal) {
|
|
665
|
+
const d = { ...config.deployment }, requestId = prepaidRequestId(record.payment), key = recordKey(requestId);
|
|
666
|
+
if (signal.aborted)
|
|
667
|
+
throw abortedError(requestId, 'reservation', record.payment, signal, signal.reason);
|
|
668
|
+
if (record.payment.allowance_id !== undefined)
|
|
669
|
+
return debit(config, record, signal);
|
|
670
|
+
try {
|
|
671
|
+
// Under the journal's lock, so abandonPaidOperation cannot close it while a reservation runs.
|
|
672
|
+
await config.store.withLock(key, async () => {
|
|
673
|
+
if ((await config.store.load(key))?.phase !== 'reserving')
|
|
674
|
+
throw new NoLongerReserving();
|
|
675
|
+
await withDedicatedPayer(`${d.chainId}-${config.gasPayer.account.address.toLowerCase()}`, async () => {
|
|
676
|
+
// The intent was signed at discovery and may have queued behind this payer for longer than
|
|
677
|
+
// the accountants' window ({latest-1, latest} at their own head). Until its first prepare it
|
|
678
|
+
// exists only here - the witness fetch carries no payment - so an epoch already two behind
|
|
679
|
+
// is certain to be refused and is safely signed again instead. Once a preparation is
|
|
680
|
+
// journaled the intent may have been seen, and it is never replaced (it could still land).
|
|
681
|
+
// A failed epoch read changes nothing: the accountants judge the epoch themselves.
|
|
682
|
+
let current;
|
|
683
|
+
try {
|
|
684
|
+
current = await readCurrentBeaconEpoch(config.chain.client, d);
|
|
685
|
+
}
|
|
686
|
+
catch {
|
|
687
|
+
current = undefined;
|
|
688
|
+
}
|
|
689
|
+
if (typeof current === 'bigint' && current >= BigInt(record.payment.verification_epoch) + 2n
|
|
690
|
+
&& await loadPaidReservationJournal(config.store, requestId) === undefined)
|
|
691
|
+
throw new NewerVerifierEpoch(requestId, current);
|
|
692
|
+
return reserveApplicationPayment(config.chain.client, config.gasPayer, d, record.payment, record.expected, { store: config.store, session: { random: record.params.random, audience: config.agent.profile.clientId },
|
|
693
|
+
accountantUrls: config.accountantUrls, allowLocalHttp: config.allowLocalHttp, maxGas: config.limits.maxGas, maxGasPrice: config.limits.maxGasPrice, signal });
|
|
694
|
+
});
|
|
695
|
+
});
|
|
696
|
+
}
|
|
697
|
+
catch (error) {
|
|
698
|
+
if (error instanceof NoLongerReserving)
|
|
699
|
+
throw new TasraError('Paid operation was closed before its reservation; it is not reserved again');
|
|
700
|
+
if (error instanceof NewerVerifierEpoch) {
|
|
701
|
+
await advance(config.store, requestId, 'reserving', { phase: 'failed', failure: { reason: 'superseded before its first prepare: the verifier epoch moved on; never sent' } });
|
|
702
|
+
throw error;
|
|
703
|
+
}
|
|
704
|
+
const journal = await loadPaidReservationJournal(config.store, requestId).catch(() => 'unreadable');
|
|
705
|
+
// Another request holds the payer and this one journaled nothing: refuse without uncertainty.
|
|
706
|
+
if (error instanceof ApplicationPayerRecoveryError && journal === undefined)
|
|
707
|
+
throw error;
|
|
708
|
+
// No preparation was journaled, and none is ever broadcast without one: nothing was sent.
|
|
709
|
+
if (journal === undefined) {
|
|
710
|
+
if (signal.aborted)
|
|
711
|
+
throw abortedError(requestId, 'reservation', record.payment, signal, error);
|
|
712
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', error, expired(record.payment) ? { code: 'reservation-refused', resumable: false } : { code: 'reservation-refused' });
|
|
713
|
+
}
|
|
714
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', error, { code: 'reservation-uncertain' });
|
|
715
|
+
}
|
|
716
|
+
await advance(config.store, requestId, 'reserving', { phase: 'reserved' });
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Prepaid allowances: obtain this payment's debit voucher on its lane instead of a reservation, and journal
|
|
720
|
+
* the payment WITH the voucher (`reserved`). A definite refusal journals `failed` (no voucher can
|
|
721
|
+
* exist: fewer than k members signed and the lane is retired); unreachable accountants leave the
|
|
722
|
+
* debit pending for the same seq and request (`reservation-refused`, resumable).
|
|
723
|
+
*/
|
|
724
|
+
async function debit(config, record, signal) {
|
|
725
|
+
const requestId = prepaidRequestId(record.payment), key = recordKey(requestId), env = allowanceEnv(config);
|
|
726
|
+
if (!env || !record.allowance) {
|
|
727
|
+
const saved = await journaledAllowanceVoucher(config.store, requestId);
|
|
728
|
+
if (!saved)
|
|
729
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', new TasraError('Resuming an allowance-backed operation needs the allowances option'), { code: 'reservation-refused' });
|
|
730
|
+
}
|
|
731
|
+
try {
|
|
732
|
+
// The voucher and the `reserved` phase that carries it are journaled under the ONE record
|
|
733
|
+
// lock that admitted the debit (one durable lock instead of two; the same checks).
|
|
734
|
+
// Checked under the journal's lock: only a `reserving` journal is debited.
|
|
735
|
+
let current;
|
|
736
|
+
const check = async () => {
|
|
737
|
+
current = await config.store.load(key);
|
|
738
|
+
if (current?.phase !== 'reserving')
|
|
739
|
+
throw new NoLongerReserving();
|
|
740
|
+
if (current.schema !== 1)
|
|
741
|
+
throw new TasraError('Paid operation journal changed concurrently');
|
|
742
|
+
};
|
|
743
|
+
const reserved = (voucher) => ({ ...current, phase: 'reserved', payment: { ...record.payment, debit_voucher: voucher } });
|
|
744
|
+
const saved = await journaledAllowanceVoucher(config.store, requestId);
|
|
745
|
+
if (saved)
|
|
746
|
+
await withCommit(config.store, key, async (commit) => { await check(); commit.stage(key, reserved(saved)); });
|
|
747
|
+
else {
|
|
748
|
+
// A fresh round runs under the journal's lock together with the lane's (one set of locks,
|
|
749
|
+
// released in the lane's commit), and journals `reserved` WITH the voucher under its request
|
|
750
|
+
// (one commit, before the lane advances past the seq): either one lets a resume continue
|
|
751
|
+
// from the voucher, and the lane completes an interrupted advance from whichever a crash kept.
|
|
752
|
+
let journaled = false;
|
|
753
|
+
const voucher = await obtainAllowanceVoucher(env, record.allowance, record.payment, signal, { lock: [key], check, journal: found => { journaled = true; return [[key, reserved(found)]]; } });
|
|
754
|
+
// A voucher another call journaled meanwhile: journal `reserved` with it now.
|
|
755
|
+
if (!journaled)
|
|
756
|
+
await withCommit(config.store, key, async (commit) => { await check(); commit.stage(key, reserved(voucher)); });
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
catch (error) {
|
|
760
|
+
if (error instanceof NoLongerReserving)
|
|
761
|
+
throw new TasraError('Paid operation was closed before its debit; it is not debited again');
|
|
762
|
+
if (error instanceof AllowanceRefusedError) {
|
|
763
|
+
await advance(config.store, requestId, 'reserving', { phase: 'failed', failure: { reason: `allowance debit refused: ${error.message}` } });
|
|
764
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', error, { code: 'reservation-failed' });
|
|
765
|
+
}
|
|
766
|
+
if (signal.aborted)
|
|
767
|
+
throw abortedError(requestId, 'reservation', record.payment, signal, error);
|
|
768
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', error, expired(record.payment) ? { code: 'reservation-refused', resumable: false } : { code: 'reservation-refused' });
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
async function advance(store, requestId, from, patch, guard) {
|
|
772
|
+
const key = recordKey(requestId);
|
|
773
|
+
// A local transition: nothing is sent under this lock, so the new phase is published with the
|
|
774
|
+
// unlock in one commit. A crash before it resolves leaves the previous phase (the transition did
|
|
775
|
+
// not happen; its caller was not told and sent nothing after it) or the new one.
|
|
776
|
+
return withCommit(store, key, async (commit) => {
|
|
777
|
+
const current = await store.load(key);
|
|
778
|
+
if (!current || current.schema !== 1 || !(Array.isArray(from) ? from : [from]).includes(current.phase))
|
|
779
|
+
throw new TasraError('Paid operation journal changed concurrently');
|
|
780
|
+
guard?.(current);
|
|
781
|
+
const next = { ...current, ...patch };
|
|
782
|
+
commit.stage(key, next);
|
|
783
|
+
return next;
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
async function continueOperation(config, requestId, holder, signal, observeRequest) {
|
|
787
|
+
const d = { ...config.deployment }, client = config.chain.client, store = config.store;
|
|
788
|
+
let record = await store.load(recordKey(requestId));
|
|
789
|
+
if (!record || record.schema !== 1 || prepaidRequestId(record.payment).toLowerCase() !== requestId.toLowerCase())
|
|
790
|
+
throw new TasraError('No paid operation journal for this request');
|
|
791
|
+
if (record.finalSign)
|
|
792
|
+
throw new TasraError('A final Sign payment has no session; resume it with resumePaidFinalSign');
|
|
793
|
+
if (record.sessionDecrypt)
|
|
794
|
+
throw new TasraError('A session-grant decrypt payment has no presentation; resume it with resumePaidSessionDecrypt');
|
|
795
|
+
if (signal.aborted && (record.phase === 'reserved' || record.phase === 'certified'))
|
|
796
|
+
throw abortedError(requestId, 'session', record.payment, signal, signal.reason);
|
|
797
|
+
// A fresh execution consent is journaled with the session's first write (its creation), not on
|
|
798
|
+
// its own: the session's identity derives from it, and nothing bound to it is sent before that
|
|
799
|
+
// commit. A crash before it leaves `reserved`, which a resume certifies anew (nothing was sent);
|
|
800
|
+
// one that kept only the creation record leaves it under a session identity nobody derives again.
|
|
801
|
+
let consent;
|
|
802
|
+
if (record.phase === 'reserved') {
|
|
803
|
+
const { policy } = await readClientExecutionPolicy(client, { ...d, defaultVerificationPolicy: d.defaultVerificationPolicy }, record.payment, record.expected);
|
|
804
|
+
const seed = random32(), signer = createLocalExecutionSigner(seed);
|
|
805
|
+
try {
|
|
806
|
+
const certificate = await createExecutionCertificate({ payment: record.payment, policy, publicKey: signer.publicKey, expires: record.payment.expires,
|
|
807
|
+
creator: config.creator });
|
|
808
|
+
const certified = { ...record, phase: 'certified', seed: Uint8Array.from(seed), certificate, pollSecret: toHex(random32()).slice(2) };
|
|
809
|
+
const key = recordKey(requestId);
|
|
810
|
+
consent = { lock: [key], entries: [[key, certified]], check: async () => {
|
|
811
|
+
const current = await store.load(key);
|
|
812
|
+
if (!current || current.schema !== 1 || current.phase !== 'reserved')
|
|
813
|
+
throw new TasraError('Paid operation journal changed concurrently');
|
|
814
|
+
} };
|
|
815
|
+
record = certified;
|
|
816
|
+
}
|
|
817
|
+
finally {
|
|
818
|
+
signer.dispose();
|
|
819
|
+
seed.fill(0);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
/**
|
|
823
|
+
* The consent on its own, as before, when the drive did not journal it: a session that failed
|
|
824
|
+
* before its first write (nothing bound to the consent was sent) or a driver that does not
|
|
825
|
+
* journal it (a test double). Keeps such a failure resumable with the same consent. A journal
|
|
826
|
+
* already holding exactly this consent (a store without native commits that failed mid-commit) is
|
|
827
|
+
* left as it is.
|
|
828
|
+
*/
|
|
829
|
+
const journalConsent = async () => {
|
|
830
|
+
if (!consent || consent.published)
|
|
831
|
+
return;
|
|
832
|
+
const key = recordKey(requestId), certified = consent.entries[0][1];
|
|
833
|
+
await withCommit(store, key, async (commit) => {
|
|
834
|
+
const current = await store.load(key);
|
|
835
|
+
if (current?.schema === 1 && current.phase === 'certified' && current.certificate?.execution_key === certified.certificate?.execution_key)
|
|
836
|
+
return;
|
|
837
|
+
if (!current || current.schema !== 1 || current.phase !== 'reserved')
|
|
838
|
+
throw new TasraError('Paid operation journal changed concurrently');
|
|
839
|
+
commit.stage(key, certified);
|
|
840
|
+
});
|
|
841
|
+
consent.published = true;
|
|
842
|
+
};
|
|
843
|
+
if (!record.seed || !record.certificate || !record.pollSecret)
|
|
844
|
+
throw new TasraError('Paid operation journal lacks its execution consent');
|
|
845
|
+
const signer = createLocalExecutionSigner(record.seed);
|
|
846
|
+
try {
|
|
847
|
+
if (record.phase === 'certified') {
|
|
848
|
+
if (!holder)
|
|
849
|
+
throw new TasraError('Resuming a paid session requires its holder strategy');
|
|
850
|
+
// The session's identity binds its kind: a resume with another holder family is refused, sending nothing.
|
|
851
|
+
if ((holder.kind === 'oauth') !== (record.params.kind === 'oauth'))
|
|
852
|
+
throw new TasraError(record.params.kind === 'oauth'
|
|
853
|
+
? 'This paid operation was journaled with an OAuth holder; resume it with one' : 'This paid operation was journaled with a wallet holder; resume it with one');
|
|
854
|
+
const params = { operation: record.params.operation, operationSig: record.params.operationSig,
|
|
855
|
+
messageHex: record.params.messageHex, payment: record.payment, random: record.params.random, ...(record.params.kind === 'oauth' ? { kind: 'oauth' } : {}), ...(record.params.decryption ? { decryption: record.params.decryption } : {}),
|
|
856
|
+
...(record.params.sessionGrant ? { sessionGrant: record.params.sessionGrant } : {}) };
|
|
857
|
+
let session;
|
|
858
|
+
try {
|
|
859
|
+
session = await prepareRegisteredPaidSession(config.chain, { profile: config.agent.profile, deployment: { ...d, defaultVerificationPolicy: d.defaultVerificationPolicy },
|
|
860
|
+
transport: config.agent.transport, members: record.members, ruleHash: keccak256(toHex(record.rule)), dcqlQuery: JSON.parse(record.rule),
|
|
861
|
+
allowMissingStatusAttestations: config.allowMissingStatusAttestations === true }, params, { certificate: record.certificate, signer, pollSecret: record.pollSecret, signal });
|
|
862
|
+
}
|
|
863
|
+
catch (error) {
|
|
864
|
+
// Best effort: unjournaled, a resume certifies anew, which is safe as nothing was sent.
|
|
865
|
+
await journalConsent().catch(() => { });
|
|
866
|
+
if (signal.aborted)
|
|
867
|
+
throw abortedError(requestId, 'session', record.payment, signal, error);
|
|
868
|
+
throw error;
|
|
869
|
+
}
|
|
870
|
+
const interval = config.pollIntervalMs ?? 1_000;
|
|
871
|
+
let result;
|
|
872
|
+
try {
|
|
873
|
+
result = await drivePaidSession({ session, members: record.members, store, signal, holder, observeRequest, resume: true,
|
|
874
|
+
wait: hint => sleep(Math.min(Math.max(hint ?? interval, 10), 60_000), signal), ...consent ? { [FIRST_COMMIT]: consent } : {} });
|
|
875
|
+
}
|
|
876
|
+
catch (error) {
|
|
877
|
+
// Best effort, as above: the drive's own failure is what the caller must see.
|
|
878
|
+
await journalConsent().catch(() => { });
|
|
879
|
+
// The completed grant failed the revocation-status preflight: nothing reached a keeper and
|
|
880
|
+
// the journal stays `certified`. Never a new session or payment automatically.
|
|
881
|
+
if (error instanceof RevocationStatusPreflightError)
|
|
882
|
+
throw statusRefusal(requestId, error);
|
|
883
|
+
// A journaled session write with an unknown outcome stays uncertain, abort or not.
|
|
884
|
+
if (signal.aborted && !(error instanceof PaidSessionRecoveryError) && !(error instanceof PaidApprovalUnresolvedError))
|
|
885
|
+
throw abortedError(requestId, 'session', record.payment, signal, error);
|
|
886
|
+
throw sessionFailure(requestId, record.payment, error);
|
|
887
|
+
}
|
|
888
|
+
const grant = verifierAgentResult({ sessionId: session.sessionId, paymentHash: paymentIntentHash(record.payment),
|
|
889
|
+
requestHash: requestHash(d.chainId, hexToBytes(record.payment.slot), record.action, hexToBytes(record.payloadDigest)) }, result);
|
|
890
|
+
if (!grant.verifierProofs?.length)
|
|
891
|
+
throw new TasraError('Paid grant lacks anchored verifier proofs');
|
|
892
|
+
await journalConsent();
|
|
893
|
+
record = await advance(store, requestId, 'certified', { phase: 'authorized', grant: { compound_token: grant.token, verifierProofs: grant.verifierProofs, sessionId: session.sessionId, ...(grant.evidenceCt !== undefined ? { evidenceCt: grant.evidenceCt } : {}),
|
|
894
|
+
...(record.params.sessionGrant ? { sessionGrant: result.sessionGrant ?? { error: 'session_grant_missing' } } : {}) } });
|
|
895
|
+
}
|
|
896
|
+
return handle(config, record, signer);
|
|
897
|
+
}
|
|
898
|
+
catch (error) {
|
|
899
|
+
signer.dispose();
|
|
900
|
+
throw error;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
function handle(config, record, signer) {
|
|
904
|
+
const d = { ...config.deployment }, requestId = prepaidRequestId(record.payment), store = config.store;
|
|
905
|
+
if (!record.grant || !record.certificate)
|
|
906
|
+
throw new TasraError('Paid operation is not authorized');
|
|
907
|
+
const route = config.keeperUrl ?? ((url) => url);
|
|
908
|
+
const approveExecution = createKeeperExecutionApprover({ client: config.chain.client, deployment: d, payment: record.payment, expected: record.expected,
|
|
909
|
+
certificate: record.certificate, signer, keeperUrl: config.keeperUrl, transportPolicy: { allowLocalHttp: config.allowLocalHttp } });
|
|
910
|
+
const grant = record.grant, certificate = record.certificate;
|
|
911
|
+
// The latest journaled grant this handle knows: a status refresh replaces its attestations.
|
|
912
|
+
let current = structuredClone(grant.compound_token);
|
|
913
|
+
// A revocation refusal this handle saw, honoured even if journaling it failed.
|
|
914
|
+
let refusedHere;
|
|
915
|
+
const operation = {
|
|
916
|
+
requestId, payment: structuredClone(record.payment), coordinatorUrl: route(record.coordinator.url),
|
|
917
|
+
get compound_token() { return structuredClone(current); },
|
|
918
|
+
get evidenceCt() { return grant.evidenceCt; },
|
|
919
|
+
get sessionGrant() { return grant.sessionGrant && structuredClone(grant.sessionGrant); },
|
|
920
|
+
verifierProofs: structuredClone(grant.verifierProofs),
|
|
921
|
+
verifier_proofs: grant.verifierProofs.map(p => ({ verifier_index: p.verifierIndex, operator: p.operator, pubkey: p.pubkey, proof: [...p.proof] })),
|
|
922
|
+
approveExecution,
|
|
923
|
+
async execute(work) {
|
|
924
|
+
// Pick up a refresh journaled through any handle or process (same token, same payment).
|
|
925
|
+
// An unreadable journal is left to the checkpoint below, which refuses it as before.
|
|
926
|
+
const latest = await loadRecord(store, requestId).catch(() => undefined);
|
|
927
|
+
if (latest?.grant && sameToken(latest.grant.compound_token, current))
|
|
928
|
+
current = structuredClone(latest.grant.compound_token);
|
|
929
|
+
// A refresh that answered a revocation refusal stops the grant, however fresh its
|
|
930
|
+
// attestations still are: a verifier saying "revoked now" is never outvoted by older ones.
|
|
931
|
+
const refused = latest ? latest.statusRefresh?.refused : refusedHere;
|
|
932
|
+
if (refused)
|
|
933
|
+
throw refreshRefusal(requestId, refused);
|
|
934
|
+
// Revocation-status preflight on the journaled grant, BEFORE the `executing` checkpoint:
|
|
935
|
+
// a refusal sends nothing and leaves the journal `authorized`. After the send, a keeper's
|
|
936
|
+
// refusal stays an uncertain execution like any other. Refreshing is explicit
|
|
937
|
+
// (`refreshStatus`), never automatic.
|
|
938
|
+
try {
|
|
939
|
+
verifyEvidenceBinding(current, grant.evidenceCt, compoundTokenHash(decodeCompoundToken(current)), new Map(record.members.map(m => [m.index, hexToBytes(m.publicKey)])), record.payment.verification_quorum);
|
|
940
|
+
statusPreflight(config, record, current);
|
|
941
|
+
}
|
|
942
|
+
catch (error) {
|
|
943
|
+
if (error instanceof RevocationStatusPreflightError)
|
|
944
|
+
throw statusRefusal(requestId, error);
|
|
945
|
+
throw error;
|
|
946
|
+
}
|
|
947
|
+
// Journal before sending: a lost reply leaves `executing`, which only recovery may read.
|
|
948
|
+
// The checkpoint re-checks the refusal mark under the journal lock (a refresh may land between).
|
|
949
|
+
await advance(store, requestId, 'authorized', { phase: 'executing' }, journal => {
|
|
950
|
+
if (journal.statusRefresh?.refused)
|
|
951
|
+
throw refreshRefusal(requestId, journal.statusRefresh.refused);
|
|
952
|
+
}).catch((error) => {
|
|
953
|
+
if (error instanceof RevocationStatusPreflightError)
|
|
954
|
+
throw error;
|
|
955
|
+
throw new PaidOperationRecoveryError(requestId, 'execution', error);
|
|
956
|
+
});
|
|
957
|
+
let result;
|
|
958
|
+
try {
|
|
959
|
+
result = await work(operation);
|
|
960
|
+
}
|
|
961
|
+
catch (error) {
|
|
962
|
+
throw new PaidOperationRecoveryError(requestId, 'execution', error);
|
|
963
|
+
}
|
|
964
|
+
await advance(store, requestId, 'executing', { phase: 'executed' });
|
|
965
|
+
return result;
|
|
966
|
+
},
|
|
967
|
+
async refreshStatus(options) {
|
|
968
|
+
let out;
|
|
969
|
+
try {
|
|
970
|
+
out = await refreshJournaledStatus(config, requestId, signer, 'authorized', options ?? {});
|
|
971
|
+
}
|
|
972
|
+
catch (error) {
|
|
973
|
+
if (error instanceof StatusRefreshError && error.code === 'status_refresh_refused') {
|
|
974
|
+
refusedHere = { seq: error.seq ?? 0, at: Math.floor(Date.now() / 1000), reasons: [...error.reasons] };
|
|
975
|
+
}
|
|
976
|
+
throw error;
|
|
977
|
+
}
|
|
978
|
+
refusedHere = undefined;
|
|
979
|
+
current = structuredClone(out.compound_token);
|
|
980
|
+
return out;
|
|
981
|
+
},
|
|
982
|
+
...recoveryReads(config, record, certificate, signer),
|
|
983
|
+
dispose: () => signer.dispose(),
|
|
984
|
+
};
|
|
985
|
+
return Object.freeze(operation);
|
|
986
|
+
}
|
|
987
|
+
/** `execute` after a refresh answered a revocation refusal: refused locally, nothing sent. */
|
|
988
|
+
function refreshRefusal(requestId, mark) {
|
|
989
|
+
const detail = mark.reasons.map(r => `${r.verifierIndex !== undefined ? `#${r.verifierIndex} ` : ''}${r.code}`).join('; ');
|
|
990
|
+
return new RevocationStatusPreflightError({ code: 'revocation_status_refused', requestId,
|
|
991
|
+
message: `Status refresh seq ${mark.seq} was refused: a verifier attests the holder's credential status is refused now${detail ? ` (${detail})` : ''}; nothing was sent - do not send this grant` });
|
|
992
|
+
}
|
|
993
|
+
/** Same token hash (every signed field equal); the attestations beside it may differ. */
|
|
994
|
+
function sameToken(a, b) {
|
|
995
|
+
try {
|
|
996
|
+
const x = compoundTokenHash(decodeCompoundToken(a)), y = compoundTokenHash(decodeCompoundToken(b));
|
|
997
|
+
return x.length === y.length && x.every((v, i) => v === y[i]);
|
|
998
|
+
}
|
|
999
|
+
catch {
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
/** The original trust a refresh is verified under: the anchored witnesses, quorum and hard caps. */
|
|
1004
|
+
function refreshGrant(record, wire) {
|
|
1005
|
+
return { token: wire, quorum: record.payment.verification_quorum, caps: [record.payment.expires],
|
|
1006
|
+
set: { registrySize: record.payment.verification_registry_size, pubkeys: new Map(record.members.map(m => [m.index, hexToBytes(m.publicKey)])) } };
|
|
1007
|
+
}
|
|
1008
|
+
/** Merge two verified attestation lists per verifier index; the later deadline wins. */
|
|
1009
|
+
function mergeAttestations(a, b) {
|
|
1010
|
+
const byIndex = new Map();
|
|
1011
|
+
for (const w of [...(a ?? []), ...b]) {
|
|
1012
|
+
const prior = byIndex.get(w.verifier_index);
|
|
1013
|
+
if (!prior || w.status_until > prior.status_until)
|
|
1014
|
+
byIndex.set(w.verifier_index, { ...w });
|
|
1015
|
+
}
|
|
1016
|
+
return [...byIndex.values()].sort((x, y) => x.verifier_index - y.verifier_index);
|
|
1017
|
+
}
|
|
1018
|
+
/**
|
|
1019
|
+
* One explicit status refresh of a journaled paid grant. The `seq` is allocated and journaled
|
|
1020
|
+
* under the journal lock BEFORE anything is signed or sent, so a crash never reuses it; the
|
|
1021
|
+
* outcome is journaled afterwards. The journal phase never changes here.
|
|
1022
|
+
*/
|
|
1023
|
+
async function refreshJournaledStatus(config, requestId, signer, mode, options) {
|
|
1024
|
+
const store = config.store, key = recordKey(requestId), signal = options.signal;
|
|
1025
|
+
const via = options.via ?? 'agent';
|
|
1026
|
+
if (via !== 'agent' && (typeof via !== 'object' || !Array.isArray(via.verifiers)))
|
|
1027
|
+
throw new TasraError('Invalid status refresh route');
|
|
1028
|
+
signal?.throwIfAborted();
|
|
1029
|
+
const allocated = await store.withLock(key, async () => {
|
|
1030
|
+
const record = await loadRecord(store, requestId);
|
|
1031
|
+
if (!record)
|
|
1032
|
+
throw new TasraError('No paid operation journal for this request');
|
|
1033
|
+
if (record.phase !== mode) {
|
|
1034
|
+
throw new TasraError(mode === 'authorized'
|
|
1035
|
+
? `Status refresh is allowed only before execution (journal is ${record.phase}); after a send use recoverPaidOperation(...).refreshStatus({explicitRecovery: true}), which never makes the execution certain`
|
|
1036
|
+
: `Status refresh in explicit recovery applies only to an uncertain execution (journal is ${record.phase})`);
|
|
1037
|
+
}
|
|
1038
|
+
if (!record.grant)
|
|
1039
|
+
throw new TasraError('Paid operation journal lacks its grant');
|
|
1040
|
+
const wire = record.grant.compound_token, token = decodeCompoundToken(wire), now = Math.floor(Date.now() / 1000);
|
|
1041
|
+
const trust = refreshGrant(record, wire);
|
|
1042
|
+
if (signersThatVerify(token, trust.set).length < trust.quorum)
|
|
1043
|
+
throw new TasraError('Journaled grant lacks a verified quorum under its anchored witnesses');
|
|
1044
|
+
if (!token.paymentHash || toHex(token.paymentHash).toLowerCase() !== paymentIntentHash(record.payment).toLowerCase())
|
|
1045
|
+
throw new TasraError('Journaled grant does not carry this payment');
|
|
1046
|
+
// Nothing usable can come back past a hard cap: refuse locally, nothing sent, no seq consumed.
|
|
1047
|
+
if (Math.min(Number(token.exp), record.payment.expires) - STATUS_SKEW_SECS <= now) {
|
|
1048
|
+
throw new StatusRefreshError({ code: 'status_refresh_expired', requestId,
|
|
1049
|
+
message: `Status refresh not sent: the grant or payment expires within the ${STATUS_SKEW_SECS} s keeper skew` });
|
|
1050
|
+
}
|
|
1051
|
+
if (via === 'agent' && (!record.grant.sessionId || !record.pollSecret)) {
|
|
1052
|
+
throw new TasraError('This journal predates recorded agent sessions; refresh it directly with via: {verifiers}');
|
|
1053
|
+
}
|
|
1054
|
+
const prior = record.statusRefresh;
|
|
1055
|
+
if ((prior?.attempts.length ?? 0) >= MAX_STATUS_REFRESH_ATTEMPTS)
|
|
1056
|
+
throw new TasraError('Paid operation reached its status refresh attempt bound');
|
|
1057
|
+
const seq = (prior?.seq ?? 0) + 1;
|
|
1058
|
+
if (!Number.isSafeInteger(seq))
|
|
1059
|
+
throw new TasraError('Status refresh sequence exhausted');
|
|
1060
|
+
const attempt = { seq, issuedAt: now, via: via === 'agent' ? 'agent' : 'direct',
|
|
1061
|
+
principal: options.holder ? 'holder_key' : 'client_execution', phase: mode };
|
|
1062
|
+
const next = { ...record, statusRefresh: { seq,
|
|
1063
|
+
original: prior ? prior.original : structuredClone(wire.status_attestations ?? null),
|
|
1064
|
+
attempts: [...(prior?.attempts ?? []), attempt],
|
|
1065
|
+
// A recorded revocation refusal survives every new attempt; only a success lifts it.
|
|
1066
|
+
...(prior?.refused ? { refused: prior.refused } : {}) } };
|
|
1067
|
+
await store.save(key, next);
|
|
1068
|
+
return { record: next, seq, issuedAt: now, trust, tokenHash: compoundTokenHash(token), paymentHash: token.paymentHash,
|
|
1069
|
+
relay: via === 'agent' ? { sessionId: record.grant.sessionId ?? '', bearer: record.pollSecret ?? '' } : undefined };
|
|
1070
|
+
});
|
|
1071
|
+
const { record, seq, issuedAt, trust, relay } = allocated;
|
|
1072
|
+
const settle = (outcome, statusUntil, refused) => store.withLock(key, async () => {
|
|
1073
|
+
const latest = await loadRecord(store, requestId);
|
|
1074
|
+
if (!latest?.statusRefresh)
|
|
1075
|
+
return;
|
|
1076
|
+
const attempts = latest.statusRefresh.attempts.map(a => a.seq === seq ? { ...a, outcome, ...(statusUntil !== undefined ? { statusUntil } : {}) } : a);
|
|
1077
|
+
await store.save(key, { ...latest, statusRefresh: { ...latest.statusRefresh, attempts, ...(refused ? { refused } : {}) } });
|
|
1078
|
+
});
|
|
1079
|
+
const fail = async (error) => {
|
|
1080
|
+
if (signal?.aborted) {
|
|
1081
|
+
await settle('aborted').catch(() => undefined);
|
|
1082
|
+
throw signal.reason ?? error;
|
|
1083
|
+
}
|
|
1084
|
+
if (error instanceof StatusRefreshError) {
|
|
1085
|
+
// A revocation refusal is journaled as a mark `execute` honours; the grant stays unchanged.
|
|
1086
|
+
const refused = error.code === 'status_refresh_refused' ? { seq, at: Math.floor(Date.now() / 1000), reasons: [...error.reasons] } : undefined;
|
|
1087
|
+
await settle(error.code, undefined, refused).catch(() => undefined);
|
|
1088
|
+
throw new StatusRefreshError({ code: error.code, message: error.message, httpStatus: error.httpStatus, retryAfterMs: error.retryAfterMs,
|
|
1089
|
+
reasons: error.reasons, requestId, seq, retryable: error.retryable, cause: error });
|
|
1090
|
+
}
|
|
1091
|
+
await settle('status_refresh_unreachable').catch(() => undefined);
|
|
1092
|
+
throw new StatusRefreshError({ code: 'status_refresh_unreachable', message: 'Status refresh got no verified answer', requestId, seq, cause: error });
|
|
1093
|
+
};
|
|
1094
|
+
let result;
|
|
1095
|
+
try {
|
|
1096
|
+
const proof = await createStatusRefreshProof({ chainId: record.payment.chain_id, tokenHash: allocated.tokenHash, paymentHash: allocated.paymentHash, seq, issuedAt,
|
|
1097
|
+
prover: options.holder ? { kind: 'holder_key', signer: options.holder } : { kind: 'client_execution', signer } });
|
|
1098
|
+
if (via === 'agent' && relay) {
|
|
1099
|
+
const active = AbortSignal.any([AbortSignal.timeout(RELAY_REFRESH_TIMEOUT_MS), ...(signal ? [signal] : [])]);
|
|
1100
|
+
let response;
|
|
1101
|
+
try {
|
|
1102
|
+
response = await config.agent.transport.paidAgentRequest(`${config.agent.profile.endpoint}/v1/sessions/${relay.sessionId}/status-refresh`, { method: 'POST', body: statusRefreshRelayBody(proof), bearer: relay.bearer, maxBytes: 64 * 1024, signal: active });
|
|
1103
|
+
}
|
|
1104
|
+
catch (error) {
|
|
1105
|
+
throw new StatusRefreshError({ code: 'status_refresh_unreachable', message: 'Status refresh relay did not answer', cause: error });
|
|
1106
|
+
}
|
|
1107
|
+
result = acceptStatusRefreshRelay(trust, { status: response.status, body: response.body,
|
|
1108
|
+
...(response.retryAfterMs !== undefined ? { retryAfterMs: response.retryAfterMs } : {}) });
|
|
1109
|
+
}
|
|
1110
|
+
else if (via !== 'agent') {
|
|
1111
|
+
result = await refreshStatusDirect({ ...trust, chainId: record.payment.chain_id, proof, verifiers: via.verifiers,
|
|
1112
|
+
...(via.fetch ? { fetch: via.fetch } : {}), allowHttp: config.allowLocalHttp === true && record.payment.chain_id === 43112, ...(signal ? { signal } : {}) });
|
|
1113
|
+
}
|
|
1114
|
+
else
|
|
1115
|
+
throw new TasraError('Invalid status refresh route');
|
|
1116
|
+
}
|
|
1117
|
+
catch (error) {
|
|
1118
|
+
return fail(error);
|
|
1119
|
+
}
|
|
1120
|
+
const done = result;
|
|
1121
|
+
// Apply under the lock, merged with the CURRENT journaled list (a concurrent refresh may have landed).
|
|
1122
|
+
return store.withLock(key, async () => {
|
|
1123
|
+
const latest = await loadRecord(store, requestId);
|
|
1124
|
+
if (!latest?.grant || !latest.statusRefresh)
|
|
1125
|
+
throw new TasraError('Paid operation journal changed concurrently');
|
|
1126
|
+
const applies = latest.phase === mode && sameToken(latest.grant.compound_token, done.token);
|
|
1127
|
+
const attempts = latest.statusRefresh.attempts.map(a => a.seq === seq ? { ...a, outcome: applies ? 'refreshed' : 'journal-changed', statusUntil: done.statusUntil } : a);
|
|
1128
|
+
if (!applies) {
|
|
1129
|
+
await store.save(key, { ...latest, statusRefresh: { ...latest.statusRefresh, attempts } });
|
|
1130
|
+
throw new TasraError(`Paid operation journal moved to ${latest.phase} while the status refresh was in flight; the refreshed attestations were not applied`);
|
|
1131
|
+
}
|
|
1132
|
+
// Only entries a keeper would count survive from the journal; the refreshed ones were verified above.
|
|
1133
|
+
const counted = signersThatVerify(decodeCompoundToken(latest.grant.compound_token), trust.set);
|
|
1134
|
+
const journaled = (latest.grant.compound_token.status_attestations ?? []).filter(w => {
|
|
1135
|
+
// An original withdrawn by its verifier's negative outcome (or left out of a relay's answer) stays out.
|
|
1136
|
+
if (done.ineligible.includes(w.verifier_index))
|
|
1137
|
+
return false;
|
|
1138
|
+
const pubkey = trust.set.pubkeys.get(w.verifier_index);
|
|
1139
|
+
return pubkey !== undefined && counted.includes(w.verifier_index) && verifyStatusAttestation(pubkey, allocated.tokenHash, { verifierIndex: w.verifier_index, statusUntil: w.status_until, signature: hexToBytes(w.signature) });
|
|
1140
|
+
});
|
|
1141
|
+
const merged = mergeAttestations(journaled, done.statusAttestations);
|
|
1142
|
+
const compound = { ...latest.grant.compound_token, status_attestations: merged };
|
|
1143
|
+
const decoded = decodeCompoundToken(compound);
|
|
1144
|
+
const statusUntil = verifyStatusAttestations({ tokenHash: compoundTokenHash(decoded), attestations: decoded.statusAttestations ?? [],
|
|
1145
|
+
counted: signersThatVerify(decoded, trust.set), set: trust.set, quorum: trust.quorum, now: Math.floor(Date.now() / 1000) });
|
|
1146
|
+
// Success: no verifier refuses now, so an earlier refusal mark is lifted.
|
|
1147
|
+
const { refused: _lifted, ...history } = latest.statusRefresh;
|
|
1148
|
+
await store.save(key, { ...latest, grant: { ...latest.grant, compound_token: compound }, statusRefresh: { ...history, attempts } });
|
|
1149
|
+
return { requestId: prepaidRequestId(record.payment), seq, statusUntil, compound_token: structuredClone(compound), refreshed: done.refreshed, failures: done.failures };
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
/** The read-only recovery half of a handle: retained keeper results, never new work. */
|
|
1153
|
+
function recoveryReads(config, record, certificate, signer) {
|
|
1154
|
+
const d = { ...config.deployment }, route = config.keeperUrl ?? ((url) => url);
|
|
1155
|
+
return {
|
|
1156
|
+
async recover(options) {
|
|
1157
|
+
let keeper = record.coordinator;
|
|
1158
|
+
let stage = options.stage ?? 'coordinator';
|
|
1159
|
+
if (options.contributorKey !== undefined) {
|
|
1160
|
+
const key = options.contributorKey;
|
|
1161
|
+
if (!HEX32.test(key) || options.stage !== undefined && options.stage !== 'contributor')
|
|
1162
|
+
throw new TasraError('Assigned contributor key and contributor stage required');
|
|
1163
|
+
const member = record.contributors?.find(candidate => candidate.publicKey.toLowerCase() === key.toLowerCase());
|
|
1164
|
+
if (!member || !record.payment.keeper_assignment.contributors.some(publicKey => toHex(Uint8Array.from(publicKey)).toLowerCase() === key.toLowerCase()))
|
|
1165
|
+
throw new TasraError('Recovery contributor is not in the original signed assignment');
|
|
1166
|
+
keeper = member;
|
|
1167
|
+
stage = 'contributor';
|
|
1168
|
+
}
|
|
1169
|
+
return recoverKeeperExecution({ client: config.chain.client, deployment: d, payment: record.payment, expected: record.expected,
|
|
1170
|
+
keeper: { ...keeper, url: route(keeper.url) }, target: { stage, executionKey: certificate.execution_key },
|
|
1171
|
+
signer, transport: options.transport, transportPolicy: { allowLocalHttp: config.allowLocalHttp }, signal: options.signal });
|
|
1172
|
+
},
|
|
1173
|
+
async recoverIbePartials(options) {
|
|
1174
|
+
if (record.payment.action !== 'ibe-extract')
|
|
1175
|
+
throw new TasraError('IBE partial recovery applies to an ibe-extract operation only');
|
|
1176
|
+
// Journals written before contributors were recorded (SDK before dfafff3) can only use `recover`.
|
|
1177
|
+
if (!record.contributors?.length)
|
|
1178
|
+
throw new TasraError('Paid operation journal lacks its assigned contributors');
|
|
1179
|
+
const binding = record.params.decryption;
|
|
1180
|
+
if (!binding || !options.recipient || options.identity === undefined || !options.verifyingShares)
|
|
1181
|
+
throw new TasraError('Original client recipient, identity and authenticated sharing required for sealed IBE recovery');
|
|
1182
|
+
const digest = recipientPayloadDigest(sha256(new TextEncoder().encode(options.identity)), binding.ciphertext_epoch, options.recipient.recipient);
|
|
1183
|
+
if (toHex(digest).toLowerCase() !== record.payloadDigest.toLowerCase())
|
|
1184
|
+
throw new TasraError('Recovery recipient or identity differs from original authorization');
|
|
1185
|
+
const concurrency = options.concurrency ?? 4, threshold = record.payment.keeper_assignment.threshold;
|
|
1186
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 16)
|
|
1187
|
+
throw new TasraError('IBE partial recovery concurrency must be 1..16');
|
|
1188
|
+
const queue = record.contributors.map(member => ({ ...member, url: route(member.url) }));
|
|
1189
|
+
const partials = [], failures = [];
|
|
1190
|
+
const read = async () => {
|
|
1191
|
+
for (let keeper = queue.shift(); keeper; keeper = queue.shift()) {
|
|
1192
|
+
if (partials.length >= threshold)
|
|
1193
|
+
return;
|
|
1194
|
+
options.signal?.throwIfAborted();
|
|
1195
|
+
try {
|
|
1196
|
+
const recovered = await recoverKeeperExecution({ client: config.chain.client, deployment: d, payment: record.payment, expected: record.expected,
|
|
1197
|
+
keeper, target: { stage: 'contributor', executionKey: certificate.execution_key }, signer, transport: options.transport,
|
|
1198
|
+
transportPolicy: { allowLocalHttp: config.allowLocalHttp }, signal: options.signal });
|
|
1199
|
+
const partial = await ibePartial(recovered.resultJson, keeper.url, record, options, d.chainId);
|
|
1200
|
+
if (partials.length >= threshold || partials.some(p => p.partial.identifier === partial.identifier))
|
|
1201
|
+
partial.value.fill(0);
|
|
1202
|
+
else
|
|
1203
|
+
partials.push({ keeper, partial, recovered });
|
|
1204
|
+
}
|
|
1205
|
+
catch (error) {
|
|
1206
|
+
options.signal?.throwIfAborted();
|
|
1207
|
+
failures.push({ operator: keeper.operator, message: error instanceof Error ? error.message : 'unreadable retained result' });
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
const reads = await Promise.allSettled(Array.from({ length: Math.min(concurrency, queue.length) }, read));
|
|
1212
|
+
const failed = reads.find(r => r.status === 'rejected');
|
|
1213
|
+
if (failed || partials.length < threshold) {
|
|
1214
|
+
for (const p of partials)
|
|
1215
|
+
p.partial.value.fill(0);
|
|
1216
|
+
if (failed?.status === 'rejected')
|
|
1217
|
+
throw failed.reason;
|
|
1218
|
+
throw new TasraError(`Recovered ${partials.length} of ${threshold} required IBE partials; ${failures.length} contributor(s) failed`);
|
|
1219
|
+
}
|
|
1220
|
+
return { threshold, partials: partials.slice(0, threshold), failures };
|
|
1221
|
+
},
|
|
1222
|
+
};
|
|
1223
|
+
}
|
|
1224
|
+
/**
|
|
1225
|
+
* Open the read-only recovery reads of a paid operation whose keeper work was sent, straight
|
|
1226
|
+
* from its journal: after {@link reconcilePaidOperation} reports `next: 'recover'` (phase
|
|
1227
|
+
* `executing`), or to re-read an `executed` result. No reservation, session or execution
|
|
1228
|
+
* happens, and no holder is needed. Refused for any other phase. Journals written before the
|
|
1229
|
+
* SDK recorded assigned contributors (before dfafff3) support `recover` but not
|
|
1230
|
+
* `recoverIbePartials`.
|
|
1231
|
+
* @param config The configuration the operation started with.
|
|
1232
|
+
* @param requestId Reservation identity.
|
|
1233
|
+
*/
|
|
1234
|
+
export async function recoverPaidOperation(config, requestId) {
|
|
1235
|
+
validateConfig(config);
|
|
1236
|
+
const record = await loadRecord(config.store, requestId);
|
|
1237
|
+
if (!record)
|
|
1238
|
+
throw new TasraError('No paid operation journal for this request');
|
|
1239
|
+
const sent = record.phase === 'abandoned' ? record.abandoned?.phase : record.phase;
|
|
1240
|
+
if (sent !== 'executing' && sent !== 'executed')
|
|
1241
|
+
throw new TasraError('Paid operation recovery applies only after its keeper work was sent (phase executing or executed)');
|
|
1242
|
+
if (!record.seed || !record.certificate)
|
|
1243
|
+
throw new TasraError('Paid operation journal lacks its execution consent');
|
|
1244
|
+
const signer = createLocalExecutionSigner(record.seed);
|
|
1245
|
+
return Object.freeze({ requestId: prepaidRequestId(record.payment), payment: structuredClone(record.payment), phase: record.phase,
|
|
1246
|
+
...recoveryReads(config, record, record.certificate, signer),
|
|
1247
|
+
refreshStatus: (options) => {
|
|
1248
|
+
if (options?.explicitRecovery !== true)
|
|
1249
|
+
return Promise.reject(new TasraError('Status refresh after a send requires explicitRecovery: true'));
|
|
1250
|
+
const { explicitRecovery: _explicit, ...rest } = options;
|
|
1251
|
+
return refreshJournaledStatus(config, requestId, signer, 'executing', rest);
|
|
1252
|
+
},
|
|
1253
|
+
dispose: () => signer.dispose() });
|
|
1254
|
+
}
|
|
1255
|
+
function loadRecord(store, requestId) {
|
|
1256
|
+
return store.load(recordKey(requestId)).then(record => {
|
|
1257
|
+
if (record === undefined)
|
|
1258
|
+
return undefined;
|
|
1259
|
+
if (!record || record.schema !== 1 || prepaidRequestId(record.payment).toLowerCase() !== requestId.toLowerCase())
|
|
1260
|
+
throw new TasraError('Paid operation journal does not match its request');
|
|
1261
|
+
return record;
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
/** Proven reservation state of a `reserving` record, advancing the journal only on proof. */
|
|
1265
|
+
async function reconcileReservation(config, requestId, record, options) {
|
|
1266
|
+
const d = { ...config.deployment }, store = config.store;
|
|
1267
|
+
let status = await reconcileApplicationReservation(config.chain.client, store, d, record.payment, record.expected, { payer: record.payer ?? config.gasPayer.account.address, confirmations: options.confirmations });
|
|
1268
|
+
if (status.state === 'uncertain' && status.payerLocked) {
|
|
1269
|
+
// A known hash can prove a mined original (success or revert) before the quote deadline.
|
|
1270
|
+
const journal = await loadPaidReservationJournal(store, requestId);
|
|
1271
|
+
const hash = journal?.transactionHash ?? options.transactionHash;
|
|
1272
|
+
if (journal && hash) {
|
|
1273
|
+
const resolution = await reconcileApplicationPayment(config.chain.client, store, d, requestId, record.expected, hash, options.confirmations).catch(() => undefined);
|
|
1274
|
+
if (resolution)
|
|
1275
|
+
status = { ...status, state: resolution.status === 'success' ? 'reserved' : 'not-reserved', payerLocked: false, transactionHash: hash,
|
|
1276
|
+
reason: resolution.status === 'success' ? undefined : 'the original reservation transaction reverted' };
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
let phase = 'reserving';
|
|
1280
|
+
if (status.state === 'reserved')
|
|
1281
|
+
phase = (await advance(store, requestId, 'reserving', { phase: 'reserved' })).phase;
|
|
1282
|
+
else if (status.state === 'not-reserved')
|
|
1283
|
+
phase = (await advance(store, requestId, 'reserving', { phase: 'failed', failure: { reason: status.reason ?? 'reservation never happened' } })).phase;
|
|
1284
|
+
return { status, phase };
|
|
1285
|
+
}
|
|
1286
|
+
const NEXT = { reserving: 'wait', reserved: 'resume', certified: 'resume', authorized: 'resume', executing: 'recover', executed: 'done', failed: 'abandon', abandoned: 'closed' };
|
|
1287
|
+
/** Reservation state implied by a phase past `reserving` (an abandoned unsent operation was never reserved). */
|
|
1288
|
+
function impliedReservation(record) {
|
|
1289
|
+
const phase = record.phase === 'abandoned' ? record.abandoned?.phase : record.phase;
|
|
1290
|
+
return phase === 'failed' ? 'not-reserved' : phase === 'reserving' ? 'none' : 'reserved';
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Reconcile a paid operation without any billable or keeper work: no reservation, no session
|
|
1294
|
+
* write, no execution. A `reserving` operation is checked on chain by its request ID and payer
|
|
1295
|
+
* nonce (no transaction hash needed) and advanced only on proof: `reserved` when the chain holds
|
|
1296
|
+
* it, `failed` when its quote deadline passed without one. Anything else stays `reserving`
|
|
1297
|
+
* with `next: 'wait'` and the payer locked.
|
|
1298
|
+
* @param config The configuration the operation started with.
|
|
1299
|
+
* @param requestId Reservation identity.
|
|
1300
|
+
* @param options Located transaction hash and observation depth.
|
|
1301
|
+
*/
|
|
1302
|
+
export async function reconcilePaidOperation(config, requestId, options = {}) {
|
|
1303
|
+
validateConfig(config);
|
|
1304
|
+
const record = await loadRecord(config.store, requestId);
|
|
1305
|
+
if (!record)
|
|
1306
|
+
throw new TasraError('No paid operation journal for this request');
|
|
1307
|
+
const payer = record.payer ? { payer: record.payer } : {};
|
|
1308
|
+
if (record.phase === 'reserving' && record.payment.allowance_id !== undefined) {
|
|
1309
|
+
// ADR-0090: a journaled voucher completes the debit; otherwise resume requests the same seq and request.
|
|
1310
|
+
const voucher = await journaledAllowanceVoucher(config.store, requestId);
|
|
1311
|
+
if (voucher) {
|
|
1312
|
+
const phase = (await advance(config.store, requestId, 'reserving', { phase: 'reserved', payment: { ...record.payment, debit_voucher: voucher } })).phase;
|
|
1313
|
+
return { requestId, phase, ...payer, reservation: 'reserved', payerLocked: false, next: NEXT[phase] };
|
|
1314
|
+
}
|
|
1315
|
+
return { requestId, phase: record.phase, ...payer, reservation: 'none', payerLocked: false, next: 'reserve', reason: 'allowance debit not completed; resume requests the same voucher' };
|
|
1316
|
+
}
|
|
1317
|
+
if (record.phase !== 'reserving') {
|
|
1318
|
+
return { requestId, phase: record.phase, ...payer, reservation: impliedReservation(record), payerLocked: false, next: NEXT[record.phase],
|
|
1319
|
+
...(record.abandoned ? { reason: record.abandoned.reason } : record.failure ? { reason: record.failure.reason } : {}) };
|
|
1320
|
+
}
|
|
1321
|
+
const { status, phase } = await reconcileReservation(config, requestId, record, options);
|
|
1322
|
+
return { requestId, phase, ...payer, reservation: status.state, payerLocked: status.payerLocked,
|
|
1323
|
+
next: status.state === 'none' ? 'reserve' : NEXT[phase],
|
|
1324
|
+
...(status.reason ? { reason: status.reason } : {}), ...(status.transactionHash ? { transactionHash: status.transactionHash } : {}) };
|
|
1325
|
+
}
|
|
1326
|
+
/**
|
|
1327
|
+
* Continue a paid operation from its journal after a PaidOperationRecoveryError or a restart.
|
|
1328
|
+
* A `reserving` operation is first reconciled on chain (see {@link reconcilePaidOperation}); it
|
|
1329
|
+
* is reserved only when nothing was ever prepared for it (no journal, no payer claim, nothing on
|
|
1330
|
+
* chain), and never again after any preparation. An unprovable reservation throws
|
|
1331
|
+
* PaidOperationRecoveryError and keeps the gas payer locked. A session is re-read, skipping
|
|
1332
|
+
* confirmed writes; an authorized or executing operation returns its handle (use `recover` for
|
|
1333
|
+
* an uncertain execution). With `reconcileOnly` it returns the status instead and does no work.
|
|
1334
|
+
* @param config The same configuration the operation started with.
|
|
1335
|
+
* @param requestId Reservation identity from the error or the journal.
|
|
1336
|
+
* @param options Holder strategy, located transaction hash, cancellation, request observation, reconcile-only.
|
|
1337
|
+
*/
|
|
1338
|
+
export async function resumePaidOperation(config, requestId, options = {}) {
|
|
1339
|
+
if (options.reconcileOnly)
|
|
1340
|
+
return reconcilePaidOperation(config, requestId, options);
|
|
1341
|
+
validateConfig(config);
|
|
1342
|
+
const signal = options.signal ?? new AbortController().signal, store = config.store;
|
|
1343
|
+
const record = await loadRecord(store, requestId);
|
|
1344
|
+
if (!record)
|
|
1345
|
+
throw new TasraError('No paid operation journal for this request');
|
|
1346
|
+
if (record.phase === 'failed')
|
|
1347
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', new Error(record.failure?.reason ?? 'reservation never happened'), { code: 'reservation-failed' });
|
|
1348
|
+
if (record.phase === 'abandoned')
|
|
1349
|
+
throw new TasraError('Paid operation was abandoned; it is never resumed');
|
|
1350
|
+
if (record.phase === 'reserving' && record.payment.allowance_id !== undefined) {
|
|
1351
|
+
// ADR-0090: no per-operation reservation to reconcile; resume the same journaled debit.
|
|
1352
|
+
await reserve(config, record, signal);
|
|
1353
|
+
}
|
|
1354
|
+
else if (record.phase === 'reserving') {
|
|
1355
|
+
// The reservation must use the payer the journal recorded (its claim and nonce live there).
|
|
1356
|
+
if (record.payer && record.payer.toLowerCase() !== config.gasPayer.account.address.toLowerCase()) {
|
|
1357
|
+
throw new TasraError(`Paid operation was journaled with gas payer ${record.payer}; resume it with that payer`);
|
|
1358
|
+
}
|
|
1359
|
+
let reconciled;
|
|
1360
|
+
try {
|
|
1361
|
+
reconciled = await reconcileReservation(config, requestId, record, options);
|
|
1362
|
+
}
|
|
1363
|
+
catch (error) {
|
|
1364
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', error);
|
|
1365
|
+
}
|
|
1366
|
+
const { status } = reconciled;
|
|
1367
|
+
if (status.state === 'none')
|
|
1368
|
+
await reserve(config, record, signal);
|
|
1369
|
+
else if (status.state === 'uncertain')
|
|
1370
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', new Error(status.reason ?? 'reservation outcome is not provable yet'));
|
|
1371
|
+
else if (status.state === 'not-reserved')
|
|
1372
|
+
throw new PaidOperationRecoveryError(requestId, 'reservation', new Error(status.reason ?? 'reservation never happened'), { code: 'reservation-failed' });
|
|
1373
|
+
}
|
|
1374
|
+
return continueOperation(config, requestId, options.holder, signal, options.observeRequest);
|
|
1375
|
+
}
|
|
1376
|
+
/**
|
|
1377
|
+
* Pay a final dual-control Sign without any presentation: no verifier-agent session and no
|
|
1378
|
+
* credential grant follows, because a static-key dual-control quorum authorizes the work at the
|
|
1379
|
+
* keeper. With `config.allowances` it is debited from an allowance lane and falls back
|
|
1380
|
+
* to a per-operation reservation exactly as {@link paidOperation} does; the journal, the execution
|
|
1381
|
+
* certificate and the keeper approvals are the ones paidOperation uses. Resume an interrupted one
|
|
1382
|
+
* with {@link resumePaidFinalSign}.
|
|
1383
|
+
* @param config - Paid operation configuration (its agent settings are not used).
|
|
1384
|
+
* @param request - Slot, message, lifetime and cancellation.
|
|
1385
|
+
*/
|
|
1386
|
+
export async function paidFinalSign(config, request) {
|
|
1387
|
+
validateConfig(config);
|
|
1388
|
+
if (!config.allowances?.enabled)
|
|
1389
|
+
return finalSignAttempt(config, request, false);
|
|
1390
|
+
try {
|
|
1391
|
+
return await finalSignAttempt(config, request, true);
|
|
1392
|
+
}
|
|
1393
|
+
catch (error) {
|
|
1394
|
+
if (!(error instanceof AllowanceFallback))
|
|
1395
|
+
throw error;
|
|
1396
|
+
return finalSignAttempt(config, request, false);
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
async function finalSignAttempt(config, request, useAllowance) {
|
|
1400
|
+
if (!(request.message instanceof Uint8Array) || request.message.length === 0)
|
|
1401
|
+
throw new TasraError('Final Sign requires the exact message');
|
|
1402
|
+
const requestId = await presentationlessAttempt(config, request, useAllowance, { marker: 'finalSign', action: 'sign', mode: 0,
|
|
1403
|
+
modeError: 'A final dual-control Sign requires a FROST slot', description: 'Paid final dual-control Sign',
|
|
1404
|
+
build: (d, nowSecs, ttlSecs) => {
|
|
1405
|
+
const built = presentationOperationTypedData({ action: 'sign', message: request.message, chainId: d.chainId, keyRegistry: d.keyRegistry, slotId: request.slot,
|
|
1406
|
+
description: 'Paid final dual-control Sign', nowSecs, ttlSecs });
|
|
1407
|
+
if (toHex(built.payloadDigest).toLowerCase() !== toHex(sha256(request.message)).toLowerCase())
|
|
1408
|
+
throw new TasraError('Final Sign payload differs from its message digest');
|
|
1409
|
+
return built;
|
|
1410
|
+
} });
|
|
1411
|
+
return continueFinalSign(config, requestId);
|
|
1412
|
+
}
|
|
1413
|
+
/** Pay one operation without any presentation (final dual Sign, session-grant decrypt): journaled, reserved, never presented. */
|
|
1414
|
+
async function presentationlessAttempt(config, request, useAllowance, spec) {
|
|
1415
|
+
const d = { ...config.deployment }, client = config.chain.client, signal = request.signal ?? new AbortController().signal;
|
|
1416
|
+
const slot = request.slot;
|
|
1417
|
+
if (!HEX32.test(slot))
|
|
1418
|
+
throw new TasraError('Invalid paid operation slot');
|
|
1419
|
+
if (config.billing)
|
|
1420
|
+
await config.billing.requirePrepaid(slot);
|
|
1421
|
+
const readiness = AbortSignal.any([signal, AbortSignal.timeout(config.snapshotWaitMs ?? 180_000)]);
|
|
1422
|
+
const context = await waitForPaidSnapshot(() => discoverPaidOperationContext(client, d, slot, { allowLocalHttp: config.allowLocalHttp, defaultVerificationPolicy: d.defaultVerificationPolicy, coordinator: request.coordinator, fundedByAllowance: useAllowance,
|
|
1423
|
+
...spec.draw ? { verificationEpoch: spec.draw.epoch } : {} }),
|
|
1424
|
+
// A moved draw (PaidDrawMovedError) is not an absent anchor: it is thrown, never waited on.
|
|
1425
|
+
readiness, () => sleep(1_000, readiness));
|
|
1426
|
+
if (context.creator.toLowerCase() !== config.creator.address.toLowerCase())
|
|
1427
|
+
throw new TasraError('Paid operations are signed by the slot creator; this signer is not it');
|
|
1428
|
+
if (context.mode !== spec.mode)
|
|
1429
|
+
throw new TasraError(spec.modeError);
|
|
1430
|
+
// Discovered without `undrawnDuringAnchorGap`: always drawn (refused, never zero fields, otherwise).
|
|
1431
|
+
if (context.undrawn)
|
|
1432
|
+
throw new TasraError('Paid operation discovery returned no verifier draw');
|
|
1433
|
+
if (spec.draw && (BigInt(context.intentFields.verification_epoch) !== spec.draw.epoch
|
|
1434
|
+
|| context.intentFields.verification_seed.toLowerCase() !== spec.draw.seed.toLowerCase())) {
|
|
1435
|
+
throw new TasraError('The session grant names a seed the beacon does not hold for its epoch');
|
|
1436
|
+
}
|
|
1437
|
+
spec.onContext?.(context);
|
|
1438
|
+
const ttlSecs = request.ttlSecs ?? 600;
|
|
1439
|
+
if (!Number.isSafeInteger(ttlSecs) || ttlSecs <= 0 || ttlSecs > 3600)
|
|
1440
|
+
throw new TasraError('Paid operation lifetime must be 1..3600 seconds');
|
|
1441
|
+
// The operation record keeps the presentation shape; nothing is signed or presented for it.
|
|
1442
|
+
const built = spec.build(d, Math.floor(Date.now() / 1000), ttlSecs);
|
|
1443
|
+
const payloadDigest = built.payloadDigest;
|
|
1444
|
+
const randomBytes = random32(), random = toHex(randomBytes);
|
|
1445
|
+
randomBytes.fill(0);
|
|
1446
|
+
const env = useAllowance ? allowanceEnv(config) : undefined;
|
|
1447
|
+
// A session message pays the GRANT's draw (all six fields: the keeper's
|
|
1448
|
+
// `require_payment_names_draw`), so only a lane drawn on it funds one, else a per-operation
|
|
1449
|
+
// reservation at it.
|
|
1450
|
+
const ticket = env ? await selectAllowanceLane(env, context, { action: spec.action, expires: built.operation.exp, drawPinned: spec.draw !== undefined }) : undefined;
|
|
1451
|
+
const unsigned = { ...ticket ? ticket.fields : context.intentFields, action: spec.action,
|
|
1452
|
+
payload_digest: toHex(payloadDigest), session_commitment: paymentSessionCommitment(random, config.agent.profile.clientId, built.operation.exp),
|
|
1453
|
+
nonce: toHex(random32()), max_cost: config.limits.maxCost.toString(), expires: built.operation.exp, ...ticket ? { allowance_id: ticket.allowanceId } : {} };
|
|
1454
|
+
const payment = { ...unsigned, signature: await config.creator.signTypedData(paymentIntentTypedData(unsigned)) };
|
|
1455
|
+
const expected = { slot, action: spec.action, payloadDigest: payment.payload_digest };
|
|
1456
|
+
const requestId = prepaidRequestId(payment);
|
|
1457
|
+
followPaidRequest(client, d, payment);
|
|
1458
|
+
await request.onRequestId?.(requestId);
|
|
1459
|
+
signal.throwIfAborted();
|
|
1460
|
+
const record = { schema: 1, phase: 'reserving', ...spec.marker === 'finalSign' ? { finalSign: true } : { sessionDecrypt: true }, payment, expected, members: [], rule: '', ruleSalt: `0x${'00'.repeat(32)}`,
|
|
1461
|
+
params: { operation: built.operation, operationSig: '0x', messageHex: built.messageHex, random, ...spec.decryption ? { decryption: spec.decryption } : {} },
|
|
1462
|
+
coordinator: context.coordinator, contributors: context.contributors, action: spec.action, payloadDigest: toHex(payloadDigest), payer: config.gasPayer.account.address, ...ticket ? { allowance: { lane: ticket.lane } } : {} };
|
|
1463
|
+
await journalNewOperation(config.store, requestId, record);
|
|
1464
|
+
try {
|
|
1465
|
+
await reserve(config, record, signal);
|
|
1466
|
+
}
|
|
1467
|
+
catch (error) {
|
|
1468
|
+
if (ticket && error instanceof PaidOperationRecoveryError && error.code === 'reservation-failed' && error.cause instanceof AllowanceRefusedError)
|
|
1469
|
+
throw new AllowanceFallback(requestId, error);
|
|
1470
|
+
throw error;
|
|
1471
|
+
}
|
|
1472
|
+
return requestId;
|
|
1473
|
+
}
|
|
1474
|
+
/**
|
|
1475
|
+
* Resume a journaled final Sign ({@link paidFinalSign}) after an interruption: a `reserving` one is
|
|
1476
|
+
* reconciled through the same debit or reservation path (never a second payment), then certified.
|
|
1477
|
+
* @param config - The original configuration.
|
|
1478
|
+
* @param requestId - The final Sign's request identity.
|
|
1479
|
+
* @param signal - Cancellation.
|
|
1480
|
+
*/
|
|
1481
|
+
export async function resumePaidFinalSign(config, requestId, signal) {
|
|
1482
|
+
validateConfig(config);
|
|
1483
|
+
const record = await config.store.load(recordKey(requestId));
|
|
1484
|
+
if (!record || record.schema !== 1 || !record.finalSign)
|
|
1485
|
+
throw new TasraError('No final Sign journal for this request');
|
|
1486
|
+
if (record.phase === 'reserving')
|
|
1487
|
+
await reserve(config, record, signal ?? new AbortController().signal);
|
|
1488
|
+
return continueFinalSign(config, requestId);
|
|
1489
|
+
}
|
|
1490
|
+
async function continueFinalSign(config, requestId) {
|
|
1491
|
+
const d = { ...config.deployment }, store = config.store;
|
|
1492
|
+
let record = await store.load(recordKey(requestId));
|
|
1493
|
+
if (!record || record.schema !== 1 || !record.finalSign || prepaidRequestId(record.payment).toLowerCase() !== requestId.toLowerCase())
|
|
1494
|
+
throw new TasraError('No final Sign journal for this request');
|
|
1495
|
+
if (record.phase === 'reserved') {
|
|
1496
|
+
const { policy } = await readClientExecutionPolicy(config.chain.client, { ...d, defaultVerificationPolicy: d.defaultVerificationPolicy }, record.payment, record.expected);
|
|
1497
|
+
const seed = random32(), signer = createLocalExecutionSigner(seed);
|
|
1498
|
+
try {
|
|
1499
|
+
const certificate = await createExecutionCertificate({ payment: record.payment, policy, publicKey: signer.publicKey, expires: record.payment.expires, creator: config.creator });
|
|
1500
|
+
record = await advance(store, requestId, 'reserved', { phase: 'certified', seed: Uint8Array.from(seed), certificate, pollSecret: toHex(random32()).slice(2) });
|
|
1501
|
+
}
|
|
1502
|
+
finally {
|
|
1503
|
+
signer.dispose();
|
|
1504
|
+
seed.fill(0);
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
if (record.phase !== 'certified' || !record.seed || !record.certificate)
|
|
1508
|
+
throw new TasraError(`Final Sign journal is ${record.phase}, not payable`);
|
|
1509
|
+
const signer = createLocalExecutionSigner(record.seed);
|
|
1510
|
+
const approveExecution = createKeeperExecutionApprover({ client: config.chain.client, deployment: d, payment: record.payment, expected: record.expected,
|
|
1511
|
+
certificate: record.certificate, signer, keeperUrl: config.keeperUrl, transportPolicy: { allowLocalHttp: config.allowLocalHttp } });
|
|
1512
|
+
const route = config.keeperUrl ?? ((url) => url);
|
|
1513
|
+
return { requestId, payment: structuredClone(record.payment), coordinatorUrl: route(record.coordinator.url), approveExecution, dispose: () => signer.dispose() };
|
|
1514
|
+
}
|
|
1515
|
+
/**
|
|
1516
|
+
* Pay one KEM decrypt that a session grant authorizes: no presentation and no
|
|
1517
|
+
* verifier round, because the grant and the session-key proof authorize the keeper work. With
|
|
1518
|
+
* `config.allowances` it is debited from an allowance lane and falls back to a per-operation
|
|
1519
|
+
* reservation exactly as {@link paidOperation}; journal, certificate and keeper approvals are the
|
|
1520
|
+
* ones every paid operation uses. Resume an interrupted one with {@link resumePaidSessionDecrypt}.
|
|
1521
|
+
* @param config - Paid operation configuration (its agent settings are not used).
|
|
1522
|
+
* @param request - Slot, recipient binding, lifetime and cancellation.
|
|
1523
|
+
*/
|
|
1524
|
+
export async function paidSessionDecrypt(config, request) {
|
|
1525
|
+
validateConfig(config);
|
|
1526
|
+
const grant = request.grant;
|
|
1527
|
+
if (grant !== undefined && (!Number.isSafeInteger(grant.epoch) || grant.epoch < 0 || typeof grant.seed !== 'string' || !HEX32.test(grant.seed))) {
|
|
1528
|
+
throw new TasraError('Invalid session grant draw');
|
|
1529
|
+
}
|
|
1530
|
+
const draw = grant ? { epoch: BigInt(grant.epoch), seed: grant.seed } : undefined;
|
|
1531
|
+
let beaconEpoch;
|
|
1532
|
+
const attempt = (useAllowance) => presentationlessAttempt(config, request, useAllowance, { marker: 'sessionDecrypt', action: 'decrypt', mode: 1,
|
|
1533
|
+
modeError: 'A session-grant decrypt requires a BLS slot', description: 'Paid session-grant decrypt', decryption: structuredClone(request.decryption),
|
|
1534
|
+
build: (d, nowSecs, ttlSecs) => presentationOperationTypedData({ action: 'decrypt', decryption: request.decryption, chainId: d.chainId, keyRegistry: d.keyRegistry,
|
|
1535
|
+
slotId: request.slot, description: 'Paid session-grant decrypt', nowSecs, ttlSecs }),
|
|
1536
|
+
...draw ? { draw } : {}, onContext: context => {
|
|
1537
|
+
beaconEpoch = context.beaconEpoch;
|
|
1538
|
+
if (beaconEpoch !== undefined)
|
|
1539
|
+
try {
|
|
1540
|
+
request.onBeaconEpoch?.(beaconEpoch);
|
|
1541
|
+
}
|
|
1542
|
+
catch { /* an observer never fails the payment */ }
|
|
1543
|
+
} });
|
|
1544
|
+
if (!request.decryption || typeof request.decryption.content_digest !== 'string')
|
|
1545
|
+
throw new TasraError('A session-grant decrypt requires the complete recipient binding');
|
|
1546
|
+
let requestId;
|
|
1547
|
+
if (!config.allowances?.enabled)
|
|
1548
|
+
requestId = await attempt(false);
|
|
1549
|
+
else {
|
|
1550
|
+
try {
|
|
1551
|
+
requestId = await attempt(true);
|
|
1552
|
+
}
|
|
1553
|
+
catch (error) {
|
|
1554
|
+
if (!(error instanceof AllowanceFallback))
|
|
1555
|
+
throw error;
|
|
1556
|
+
requestId = await attempt(false);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
const paid = await continueSessionDecrypt(config, requestId);
|
|
1560
|
+
return beaconEpoch === undefined ? paid : { ...paid, beaconEpoch };
|
|
1561
|
+
}
|
|
1562
|
+
/**
|
|
1563
|
+
* Resume a journaled session-grant decrypt payment ({@link paidSessionDecrypt}): a `reserving`
|
|
1564
|
+
* one is reconciled through the same debit or reservation path (never a second payment).
|
|
1565
|
+
* @param config - The original configuration.
|
|
1566
|
+
* @param requestId - The decrypt's request identity.
|
|
1567
|
+
* @param signal - Cancellation.
|
|
1568
|
+
*/
|
|
1569
|
+
export async function resumePaidSessionDecrypt(config, requestId, signal) {
|
|
1570
|
+
validateConfig(config);
|
|
1571
|
+
const record = await config.store.load(recordKey(requestId));
|
|
1572
|
+
if (!record || record.schema !== 1 || !record.sessionDecrypt)
|
|
1573
|
+
throw new TasraError('No session-grant decrypt journal for this request');
|
|
1574
|
+
if (record.phase === 'reserving')
|
|
1575
|
+
await reserve(config, record, signal ?? new AbortController().signal);
|
|
1576
|
+
return continueSessionDecrypt(config, requestId);
|
|
1577
|
+
}
|
|
1578
|
+
async function continueSessionDecrypt(config, requestId) {
|
|
1579
|
+
const d = { ...config.deployment }, store = config.store;
|
|
1580
|
+
let record = await store.load(recordKey(requestId));
|
|
1581
|
+
if (!record || record.schema !== 1 || !record.sessionDecrypt || prepaidRequestId(record.payment).toLowerCase() !== requestId.toLowerCase())
|
|
1582
|
+
throw new TasraError('No session-grant decrypt journal for this request');
|
|
1583
|
+
if (record.phase === 'reserved') {
|
|
1584
|
+
const { policy } = await readClientExecutionPolicy(config.chain.client, { ...d, defaultVerificationPolicy: d.defaultVerificationPolicy }, record.payment, record.expected);
|
|
1585
|
+
const seed = random32(), signer = createLocalExecutionSigner(seed);
|
|
1586
|
+
try {
|
|
1587
|
+
const certificate = await createExecutionCertificate({ payment: record.payment, policy, publicKey: signer.publicKey, expires: record.payment.expires, creator: config.creator });
|
|
1588
|
+
record = await advance(store, requestId, 'reserved', { phase: 'certified', seed: Uint8Array.from(seed), certificate, pollSecret: toHex(random32()).slice(2) });
|
|
1589
|
+
}
|
|
1590
|
+
finally {
|
|
1591
|
+
signer.dispose();
|
|
1592
|
+
seed.fill(0);
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
if (record.phase !== 'certified' || !record.seed || !record.certificate)
|
|
1596
|
+
throw new TasraError(`Session-grant decrypt journal is ${record.phase}, not payable`);
|
|
1597
|
+
const signer = createLocalExecutionSigner(record.seed);
|
|
1598
|
+
const approveExecution = createKeeperExecutionApprover({ client: config.chain.client, deployment: d, payment: record.payment, expected: record.expected,
|
|
1599
|
+
certificate: record.certificate, signer, keeperUrl: config.keeperUrl, transportPolicy: { allowLocalHttp: config.allowLocalHttp } });
|
|
1600
|
+
const reads = recoveryReads(config, record, record.certificate, signer), route = config.keeperUrl ?? ((url) => url);
|
|
1601
|
+
const norm = (url) => url.replace(/\/$/, '');
|
|
1602
|
+
const recoverPartial = async ({ nodeUrl, transport, signal }) => {
|
|
1603
|
+
const member = record.contributors?.find(m => norm(route(m.url)) === norm(nodeUrl));
|
|
1604
|
+
if (!member)
|
|
1605
|
+
throw new TasraError('Recovery keeper is not an assigned contributor of this decrypt');
|
|
1606
|
+
const recovered = await reads.recover({ transport, contributorKey: member.publicKey, signal });
|
|
1607
|
+
return JSON.parse(recovered.resultJson);
|
|
1608
|
+
};
|
|
1609
|
+
return { requestId, payment: structuredClone(record.payment), approveExecution, recoverPartial, dispose: () => signer.dispose() };
|
|
1610
|
+
}
|
|
1611
|
+
/**
|
|
1612
|
+
* The journaled phase of a paid operation, or `undefined` when the store holds no record of it.
|
|
1613
|
+
* @param store - Application store holding the operation journal.
|
|
1614
|
+
* @param requestId - Payment request id of the operation.
|
|
1615
|
+
*/
|
|
1616
|
+
export async function paidOperationPhase(store, requestId) {
|
|
1617
|
+
const record = await store.load(recordKey(requestId));
|
|
1618
|
+
return record?.phase;
|
|
1619
|
+
}
|
|
1620
|
+
/**
|
|
1621
|
+
* List the paid operations journaled in a store, oldest first, without relying on its key scheme.
|
|
1622
|
+
* Abandoned operations are left out unless asked for. Operations journaled before this index
|
|
1623
|
+
* existed are listed only after a one-time `backfill`; otherwise read them with `paidOperationPhase`.
|
|
1624
|
+
* @param store Store the operations were journaled in.
|
|
1625
|
+
* @param filter Phases to keep, whether to include abandoned operations, and the one-time backfill.
|
|
1626
|
+
*/
|
|
1627
|
+
export async function listPaidOperations(store, filter = {}) {
|
|
1628
|
+
const phases = filter.phase === undefined ? undefined : typeof filter.phase === 'string' ? [filter.phase] : [...filter.phase];
|
|
1629
|
+
const abandoned = filter.includeAbandoned === true || phases?.includes('abandoned') === true;
|
|
1630
|
+
if (filter.backfill)
|
|
1631
|
+
await backfillIndex(store);
|
|
1632
|
+
const out = [];
|
|
1633
|
+
for (const requestId of await loadIndex(store)) {
|
|
1634
|
+
const record = await loadRecord(store, requestId);
|
|
1635
|
+
if (!record || (phases && !phases.includes(record.phase)) || (record.phase === 'abandoned' && !abandoned))
|
|
1636
|
+
continue;
|
|
1637
|
+
out.push({ requestId, phase: record.phase, slot: record.payment.slot, action: record.payment.action, expires: record.payment.expires,
|
|
1638
|
+
...(record.payer ? { payer: record.payer } : {}), ...(record.abandoned ? { abandoned: { ...record.abandoned } } : {}) });
|
|
1639
|
+
}
|
|
1640
|
+
return out;
|
|
1641
|
+
}
|
|
1642
|
+
/** Seconds past payment expiry before an unfinished operation may be abandoned (clock skew between this host, keepers and the chain). */
|
|
1643
|
+
const ABANDON_EXPIRY_MARGIN_SECS = 120;
|
|
1644
|
+
/** {@link abandonPaidOperation} refused: something could still land under this operation. */
|
|
1645
|
+
export class PaidOperationAbandonRefusedError extends TasraError {
|
|
1646
|
+
requestId;
|
|
1647
|
+
phase;
|
|
1648
|
+
notBefore;
|
|
1649
|
+
constructor(
|
|
1650
|
+
/** Reservation identity. */ requestId,
|
|
1651
|
+
/** Journaled phase that blocks abandoning. */ phase,
|
|
1652
|
+
/** Why it cannot be abandoned yet; safe to log. */ reason,
|
|
1653
|
+
/** Unix seconds from which abandoning succeeds (payment expiry plus a skew margin), when time alone unblocks it. */ notBefore) {
|
|
1654
|
+
super(`Paid operation ${requestId.slice(0, 12)}… cannot be abandoned: ${reason}`, { retryable: notBefore !== undefined });
|
|
1655
|
+
this.requestId = requestId;
|
|
1656
|
+
this.phase = phase;
|
|
1657
|
+
this.notBefore = notBefore;
|
|
1658
|
+
}
|
|
1659
|
+
}
|
|
1660
|
+
/** The accountants accept a client-pinned reservation quote block at most this old (accountant `MAX_QUOTE_AGE`). */
|
|
1661
|
+
const RESERVATION_QUOTE_MAX_AGE_SECS = 30;
|
|
1662
|
+
/**
|
|
1663
|
+
* Close a paid operation for good, only when nothing can still land under it: no reservation,
|
|
1664
|
+
* session write or keeper work can still be accepted. The journal is kept (phase `abandoned`),
|
|
1665
|
+
* left out of {@link listPaidOperations} by default and refused by {@link resumePaidOperation}.
|
|
1666
|
+
* Abandoning an already abandoned operation returns its original record.
|
|
1667
|
+
*
|
|
1668
|
+
* Allowed when the journal proves it:
|
|
1669
|
+
* - `reserving` with no reservation ever prepared, once the payment has expired plus the quote
|
|
1670
|
+
* window (MAX_QUOTE_AGE, 30 s) and the skew margin: until then the signed intent the accountants
|
|
1671
|
+
* saw could still be reserved by whoever holds it;
|
|
1672
|
+
* - `failed` (the reservation provably never happened);
|
|
1673
|
+
* - `executed` (completed and recorded);
|
|
1674
|
+
* - `reserved`, `certified`, `authorized` or `executing` once the creator-signed payment has
|
|
1675
|
+
* expired (plus a skew margin): keepers, verifiers and the agent refuse it from then on.
|
|
1676
|
+
* Retained results of an `executing` operation stay readable with {@link recoverPaidOperation}.
|
|
1677
|
+
*
|
|
1678
|
+
* Refused (PaidOperationAbandonRefusedError) otherwise. A `reserving` operation whose
|
|
1679
|
+
* reservation was prepared must first be settled by {@link reconcilePaidOperation} (it becomes
|
|
1680
|
+
* `failed` or `reserved`), which also releases the gas payer.
|
|
1681
|
+
* @param store Store the operation was journaled in.
|
|
1682
|
+
* @param requestId Reservation identity.
|
|
1683
|
+
* @param options Reason to journal.
|
|
1684
|
+
*/
|
|
1685
|
+
export async function abandonPaidOperation(store, requestId, options) {
|
|
1686
|
+
const reason = options?.reason;
|
|
1687
|
+
if (typeof reason !== 'string' || !reason.trim() || reason.length > 512)
|
|
1688
|
+
throw new TasraError('Abandoning a paid operation needs a reason of 1..512 characters');
|
|
1689
|
+
const key = recordKey(requestId);
|
|
1690
|
+
return store.withLock(key, async () => {
|
|
1691
|
+
const record = await loadRecord(store, requestId);
|
|
1692
|
+
if (!record)
|
|
1693
|
+
throw new TasraError('No paid operation journal for this request');
|
|
1694
|
+
const id = requestId.toLowerCase();
|
|
1695
|
+
if (record.phase === 'abandoned' && record.abandoned)
|
|
1696
|
+
return { requestId: id, from: record.abandoned.phase, reason: record.abandoned.reason, at: record.abandoned.at };
|
|
1697
|
+
const from = record.phase, now = Math.floor(Date.now() / 1000);
|
|
1698
|
+
const refuse = (why, notBefore) => new PaidOperationAbandonRefusedError(id, from, why, notBefore);
|
|
1699
|
+
if (from === 'reserving') {
|
|
1700
|
+
// Under this lock no reservation can start (reserve() holds it); a prepared one may have been broadcast.
|
|
1701
|
+
if (await loadPaidReservationJournal(store, requestId).catch(() => 'unreadable') !== undefined) {
|
|
1702
|
+
throw refuse('its reservation was prepared and may have been sent; reconcile it first');
|
|
1703
|
+
}
|
|
1704
|
+
// Even with nothing of ours prepared, the signed intent reached the accountants: anyone holding
|
|
1705
|
+
// it can still have it reserved at a quote block up to MAX_QUOTE_AGE old, and never once the
|
|
1706
|
+
// payment has expired (its quote block cannot postdate the expiry). Wait out both.
|
|
1707
|
+
const notBefore = record.payment.expires + RESERVATION_QUOTE_MAX_AGE_SECS + ABANDON_EXPIRY_MARGIN_SECS;
|
|
1708
|
+
if (now < notBefore)
|
|
1709
|
+
throw refuse('its signed intent can still be reserved by its holder; reconcile it, or abandon it after the payment and quote windows', notBefore);
|
|
1710
|
+
}
|
|
1711
|
+
else if (from !== 'failed' && from !== 'executed') {
|
|
1712
|
+
const notBefore = record.payment.expires + ABANDON_EXPIRY_MARGIN_SECS;
|
|
1713
|
+
if (now < notBefore)
|
|
1714
|
+
throw refuse('its payment has not expired, so its reservation, session or keeper work can still be accepted', notBefore);
|
|
1715
|
+
}
|
|
1716
|
+
const abandoned = { reason, at: now, phase: from };
|
|
1717
|
+
await store.save(key, { ...record, phase: 'abandoned', abandoned });
|
|
1718
|
+
return { requestId: id, from, reason, at: now };
|
|
1719
|
+
});
|
|
1720
|
+
}
|