@ocap/tx-protocols 1.31.1 → 1.31.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/esm/bridge-release-crypto.d.mts +39 -0
  2. package/esm/bridge-release-crypto.mjs +88 -0
  3. package/esm/bridge-release-window.d.mts +47 -0
  4. package/esm/bridge-release-window.mjs +62 -0
  5. package/esm/bridge-reserve.d.mts +24 -0
  6. package/esm/bridge-reserve.mjs +41 -0
  7. package/esm/execute.d.mts +1 -1
  8. package/esm/execute.mjs +58 -5
  9. package/esm/gas-security-guard.d.mts +6 -2
  10. package/esm/gas-security-guard.mjs +16 -9
  11. package/esm/index.d.mts +37 -18
  12. package/esm/index.mjs +6 -2
  13. package/esm/pipes/ensure-cost.mjs +7 -1
  14. package/esm/pipes/write-ledger.d.mts +2 -2
  15. package/esm/pipes/write-ledger.mjs +6 -3
  16. package/esm/protocols/account/delegate.mjs +6 -4
  17. package/esm/protocols/account/migrate.mjs +5 -3
  18. package/esm/protocols/account/revoke-delegate.mjs +5 -3
  19. package/esm/protocols/asset/acquire-v2.mjs +3 -1
  20. package/esm/protocols/asset/acquire-v3.mjs +4 -2
  21. package/esm/protocols/asset/consume.mjs +3 -1
  22. package/esm/protocols/asset/create.mjs +4 -2
  23. package/esm/protocols/asset/mint.mjs +4 -2
  24. package/esm/protocols/asset/pipes/exec-mint-hook.mjs +1 -1
  25. package/esm/protocols/asset/pipes/verify-itx-address.mjs +1 -1
  26. package/esm/protocols/asset/pipes/verify-itx-assets.mjs +1 -1
  27. package/esm/protocols/asset/update.mjs +4 -2
  28. package/esm/protocols/bridge/release.d.mts +34 -0
  29. package/esm/protocols/bridge/release.mjs +385 -0
  30. package/esm/protocols/factory/create.mjs +4 -2
  31. package/esm/protocols/governance/claim-stake.mjs +4 -2
  32. package/esm/protocols/governance/return-stake.mjs +4 -2
  33. package/esm/protocols/governance/revoke-ledger.mjs +1 -1
  34. package/esm/protocols/governance/revoke-stake.d.mts +7 -2
  35. package/esm/protocols/governance/revoke-stake.mjs +49 -28
  36. package/esm/protocols/governance/slash-stake.mjs +5 -3
  37. package/esm/protocols/governance/stake.mjs +6 -4
  38. package/esm/protocols/rollup/bridge-create.d.mts +13 -0
  39. package/esm/protocols/rollup/bridge-create.mjs +206 -0
  40. package/esm/protocols/rollup/bridge-membership.d.mts +10 -0
  41. package/esm/protocols/rollup/bridge-membership.mjs +154 -0
  42. package/esm/protocols/rollup/bridge-migrate.d.mts +10 -0
  43. package/esm/protocols/rollup/bridge-migrate.mjs +208 -0
  44. package/esm/protocols/rollup/bridge-v2.d.mts +113 -0
  45. package/esm/protocols/rollup/bridge-v2.mjs +219 -0
  46. package/esm/protocols/rollup/claim-reward.mjs +4 -2
  47. package/esm/protocols/rollup/close.d.mts +2 -1
  48. package/esm/protocols/rollup/close.mjs +59 -6
  49. package/esm/protocols/rollup/create-block.mjs +4 -2
  50. package/esm/protocols/rollup/create.d.mts +3 -0
  51. package/esm/protocols/rollup/create.mjs +45 -6
  52. package/esm/protocols/rollup/join.d.mts +2 -1
  53. package/esm/protocols/rollup/join.mjs +31 -23
  54. package/esm/protocols/rollup/leave.d.mts +2 -1
  55. package/esm/protocols/rollup/leave.mjs +32 -24
  56. package/esm/protocols/rollup/migrate.d.mts +2 -1
  57. package/esm/protocols/rollup/migrate.mjs +19 -10
  58. package/esm/protocols/rollup/pause.d.mts +4 -1
  59. package/esm/protocols/rollup/pause.mjs +50 -6
  60. package/esm/protocols/rollup/pipes/verify-evidence.mjs +2 -2
  61. package/esm/protocols/rollup/resume.d.mts +2 -1
  62. package/esm/protocols/rollup/resume.mjs +26 -6
  63. package/esm/protocols/rollup/update.d.mts +5 -1
  64. package/esm/protocols/rollup/update.mjs +56 -9
  65. package/esm/protocols/token/create.mjs +4 -2
  66. package/esm/protocols/token/deposit-v2.mjs +5 -3
  67. package/esm/protocols/token/withdraw-v2.mjs +5 -3
  68. package/esm/protocols/token-factory/burn.mjs +4 -2
  69. package/esm/protocols/token-factory/create.mjs +8 -4
  70. package/esm/protocols/token-factory/mint.mjs +4 -2
  71. package/esm/protocols/token-factory/update.mjs +20 -5
  72. package/esm/protocols/trade/exchange-v2.d.mts +5 -1
  73. package/esm/protocols/trade/exchange-v2.mjs +89 -4
  74. package/esm/protocols/trade/transfer-v2.mjs +15 -4
  75. package/esm/protocols/trade/transfer-v3.mjs +5 -3
  76. package/esm/stateless-prefix.d.mts +16 -0
  77. package/esm/stateless-prefix.mjs +82 -0
  78. package/esm/tx-timer.d.mts +1 -1
  79. package/esm/tx-timer.mjs +1 -1
  80. package/esm/util.mjs +2 -2
  81. package/lib/bridge-release-crypto.cjs +93 -0
  82. package/lib/bridge-release-crypto.d.cts +39 -0
  83. package/lib/bridge-release-window.cjs +69 -0
  84. package/lib/bridge-release-window.d.cts +47 -0
  85. package/lib/bridge-reserve.cjs +45 -0
  86. package/lib/bridge-reserve.d.cts +24 -0
  87. package/lib/execute.cjs +58 -5
  88. package/lib/gas-security-guard.cjs +16 -9
  89. package/lib/gas-security-guard.d.cts +6 -2
  90. package/lib/index.cjs +8 -1
  91. package/lib/index.d.cts +36 -17
  92. package/lib/pipes/ensure-cost.cjs +7 -1
  93. package/lib/pipes/write-ledger.cjs +6 -3
  94. package/lib/pipes/write-ledger.d.cts +2 -2
  95. package/lib/protocols/account/delegate.cjs +6 -4
  96. package/lib/protocols/account/migrate.cjs +5 -3
  97. package/lib/protocols/account/revoke-delegate.cjs +5 -3
  98. package/lib/protocols/asset/acquire-v2.cjs +3 -1
  99. package/lib/protocols/asset/acquire-v3.cjs +4 -2
  100. package/lib/protocols/asset/consume.cjs +3 -1
  101. package/lib/protocols/asset/create.cjs +4 -2
  102. package/lib/protocols/asset/mint.cjs +4 -2
  103. package/lib/protocols/asset/pipes/exec-mint-hook.cjs +1 -1
  104. package/lib/protocols/asset/pipes/verify-itx-address.cjs +1 -1
  105. package/lib/protocols/asset/pipes/verify-itx-assets.cjs +1 -1
  106. package/lib/protocols/asset/update.cjs +4 -2
  107. package/lib/protocols/bridge/release.cjs +390 -0
  108. package/lib/protocols/bridge/release.d.cts +34 -0
  109. package/lib/protocols/factory/create.cjs +4 -2
  110. package/lib/protocols/governance/claim-stake.cjs +4 -2
  111. package/lib/protocols/governance/return-stake.cjs +4 -2
  112. package/lib/protocols/governance/revoke-ledger.cjs +1 -1
  113. package/lib/protocols/governance/revoke-stake.cjs +49 -28
  114. package/lib/protocols/governance/revoke-stake.d.cts +7 -2
  115. package/lib/protocols/governance/slash-stake.cjs +5 -3
  116. package/lib/protocols/governance/stake.cjs +6 -4
  117. package/lib/protocols/rollup/bridge-create.cjs +209 -0
  118. package/lib/protocols/rollup/bridge-create.d.cts +13 -0
  119. package/lib/protocols/rollup/bridge-membership.cjs +157 -0
  120. package/lib/protocols/rollup/bridge-membership.d.cts +10 -0
  121. package/lib/protocols/rollup/bridge-migrate.cjs +212 -0
  122. package/lib/protocols/rollup/bridge-migrate.d.cts +10 -0
  123. package/lib/protocols/rollup/bridge-v2.cjs +244 -0
  124. package/lib/protocols/rollup/bridge-v2.d.cts +113 -0
  125. package/lib/protocols/rollup/claim-reward.cjs +4 -2
  126. package/lib/protocols/rollup/close.cjs +59 -6
  127. package/lib/protocols/rollup/close.d.cts +2 -1
  128. package/lib/protocols/rollup/create-block.cjs +4 -2
  129. package/lib/protocols/rollup/create.cjs +45 -6
  130. package/lib/protocols/rollup/create.d.cts +3 -0
  131. package/lib/protocols/rollup/join.cjs +31 -23
  132. package/lib/protocols/rollup/join.d.cts +2 -1
  133. package/lib/protocols/rollup/leave.cjs +32 -24
  134. package/lib/protocols/rollup/leave.d.cts +2 -1
  135. package/lib/protocols/rollup/migrate.cjs +19 -10
  136. package/lib/protocols/rollup/migrate.d.cts +2 -1
  137. package/lib/protocols/rollup/pause.cjs +50 -6
  138. package/lib/protocols/rollup/pause.d.cts +4 -1
  139. package/lib/protocols/rollup/pipes/verify-evidence.cjs +2 -2
  140. package/lib/protocols/rollup/resume.cjs +26 -6
  141. package/lib/protocols/rollup/resume.d.cts +2 -1
  142. package/lib/protocols/rollup/update.cjs +56 -9
  143. package/lib/protocols/rollup/update.d.cts +5 -1
  144. package/lib/protocols/token/create.cjs +4 -2
  145. package/lib/protocols/token/deposit-v2.cjs +5 -3
  146. package/lib/protocols/token/withdraw-v2.cjs +5 -3
  147. package/lib/protocols/token-factory/burn.cjs +4 -2
  148. package/lib/protocols/token-factory/create.cjs +8 -4
  149. package/lib/protocols/token-factory/mint.cjs +4 -2
  150. package/lib/protocols/token-factory/update.cjs +20 -5
  151. package/lib/protocols/trade/exchange-v2.cjs +90 -3
  152. package/lib/protocols/trade/exchange-v2.d.cts +5 -1
  153. package/lib/protocols/trade/transfer-v2.cjs +15 -4
  154. package/lib/protocols/trade/transfer-v3.cjs +5 -3
  155. package/lib/stateless-prefix.cjs +88 -0
  156. package/lib/stateless-prefix.d.cts +16 -0
  157. package/lib/tx-timer.cjs +1 -1
  158. package/lib/tx-timer.d.cts +1 -1
  159. package/lib/util.cjs +2 -2
  160. package/package.json +16 -16
  161. package/tools/fixtures.ts +9 -4
@@ -0,0 +1,39 @@
1
+ //#region src/bridge-release-crypto.d.ts
2
+ interface BridgeDomainInput {
3
+ /** EVM chain id, decimal string */
4
+ ethChainId: string;
5
+ /** BridgeGateway address */
6
+ gateway: string;
7
+ }
8
+ interface OcapReleaseMessage {
9
+ kind: number;
10
+ evidence: string;
11
+ ordinal: number;
12
+ ocapChainId: string;
13
+ /** OCAP bridge (RollupState) address */
14
+ bridge: string;
15
+ to: string;
16
+ amount: string;
17
+ epoch: number;
18
+ ethSender: string;
19
+ }
20
+ declare const ZERO_ETH_ADDRESS: string;
21
+ /** EIP-712 digest validators sign for a release. */
22
+ declare function getOcapReleaseDigest(domain: BridgeDomainInput, m: OcapReleaseMessage): string;
23
+ interface DepositClaimMessage {
24
+ ethTxHash: string;
25
+ ocapChainId: string;
26
+ recipient: string;
27
+ amount: string;
28
+ }
29
+ /** EIP-712 digest the depositor signs to claim a mode-B deposit. */
30
+ declare function getDepositClaimDigest(domain: BridgeDomainInput, m: DepositClaimMessage): string;
31
+ /**
32
+ * Lowercase signer address of a 65-byte `r || s || v` signature over `digest`, or `null` when it is not a canonical
33
+ * signature: wrong length or encoding, `v` other than 27 / 28, high `s`, or no recoverable key.
34
+ */
35
+ declare function recoverEthSigner(digest: string, signature: string): string | null;
36
+ /** Strict `0x` + 40 hex, any case. */
37
+ declare const isEthAddress: (value: unknown) => value is string;
38
+ //#endregion
39
+ export { BridgeDomainInput, DepositClaimMessage, OcapReleaseMessage, ZERO_ETH_ADDRESS, getDepositClaimDigest, getOcapReleaseDigest, isEthAddress, recoverEthSigner };
@@ -0,0 +1,88 @@
1
+ import { Hasher, Signer } from "@ocap/mcrypto";
2
+
3
+ //#region src/bridge-release-crypto.ts
4
+ /**
5
+ * EIP-712 digests and signature recovery for `release_bridge_token` (#1466, bridge/docs/ocap-protocols.md §3).
6
+ *
7
+ * The structs mirror `@arcblock/bridge-types` (`OcapRelease`, `DepositClaim`; domain `ArcBridge` v1). The chain can
8
+ * not depend on that package (it is private and pulls in viem), so the encoding is re-implemented here and pinned to
9
+ * the shared test vectors (`bridge/types/vectors/eip712.json`) by `tests/bridge-release-crypto.spec.ts`.
10
+ */
11
+ const DOMAIN_NAME = "ArcBridge";
12
+ const DOMAIN_VERSION = "1";
13
+ const keccak = (data) => Buffer.from(Hasher.Keccak.hash256(data, 1, "Uint8Array"));
14
+ const keccakText = (text) => keccak(Buffer.from(text, "utf8"));
15
+ const TYPEHASH_DOMAIN = keccakText("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
16
+ const TYPEHASH_RELEASE = keccakText("OcapRelease(uint8 kind,bytes32 evidence,uint32 ordinal,string ocapChainId,string bridge,string to,uint256 amount,uint64 epoch,address ethSender)");
17
+ const TYPEHASH_CLAIM = keccakText("DepositClaim(bytes32 ethTxHash,string ocapChainId,string recipient,uint256 amount)");
18
+ const UINT256_MAX = (1n << 256n) - 1n;
19
+ const word = (value) => {
20
+ if (value < 0n || value > UINT256_MAX) throw new Error("uint256 out of range");
21
+ return Buffer.from(value.toString(16).padStart(64, "0"), "hex");
22
+ };
23
+ const addressWord = (address) => {
24
+ if (!/^0x[0-9a-fA-F]{40}$/.test(address)) throw new Error("invalid address");
25
+ return Buffer.concat([Buffer.alloc(12), Buffer.from(address.slice(2), "hex")]);
26
+ };
27
+ const bytes32 = (hex) => {
28
+ if (!/^0x[0-9a-fA-F]{64}$/.test(hex)) throw new Error("invalid bytes32");
29
+ return Buffer.from(hex.slice(2), "hex");
30
+ };
31
+ const domainSeparator = ({ ethChainId, gateway }) => keccak(Buffer.concat([
32
+ TYPEHASH_DOMAIN,
33
+ keccakText(DOMAIN_NAME),
34
+ keccakText(DOMAIN_VERSION),
35
+ word(BigInt(ethChainId)),
36
+ addressWord(gateway)
37
+ ]));
38
+ const toDigest = (domain, structHash) => `0x${keccak(Buffer.concat([
39
+ Buffer.from([25, 1]),
40
+ domainSeparator(domain),
41
+ structHash
42
+ ])).toString("hex")}`;
43
+ const ZERO_ETH_ADDRESS = `0x${"0".repeat(40)}`;
44
+ /** EIP-712 digest validators sign for a release. */
45
+ function getOcapReleaseDigest(domain, m) {
46
+ return toDigest(domain, keccak(Buffer.concat([
47
+ TYPEHASH_RELEASE,
48
+ word(BigInt(m.kind)),
49
+ bytes32(m.evidence),
50
+ word(BigInt(m.ordinal)),
51
+ keccakText(m.ocapChainId),
52
+ keccakText(m.bridge),
53
+ keccakText(m.to),
54
+ word(BigInt(m.amount)),
55
+ word(BigInt(m.epoch)),
56
+ addressWord(m.ethSender)
57
+ ])));
58
+ }
59
+ /** EIP-712 digest the depositor signs to claim a mode-B deposit. */
60
+ function getDepositClaimDigest(domain, m) {
61
+ return toDigest(domain, keccak(Buffer.concat([
62
+ TYPEHASH_CLAIM,
63
+ bytes32(m.ethTxHash),
64
+ keccakText(m.ocapChainId),
65
+ keccakText(m.recipient),
66
+ word(BigInt(m.amount))
67
+ ])));
68
+ }
69
+ const SIGNATURE_PATTERN = /^0x[0-9a-fA-F]{130}$/;
70
+ /**
71
+ * Lowercase signer address of a 65-byte `r || s || v` signature over `digest`, or `null` when it is not a canonical
72
+ * signature: wrong length or encoding, `v` other than 27 / 28, high `s`, or no recoverable key.
73
+ */
74
+ function recoverEthSigner(digest, signature) {
75
+ if (typeof signature !== "string" || !SIGNATURE_PATTERN.test(signature)) return null;
76
+ const v = Number.parseInt(signature.slice(130, 132), 16);
77
+ if (v !== 27 && v !== 28) return null;
78
+ try {
79
+ return Signer.Ethereum.ethRecover(digest, signature).toLowerCase();
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ /** Strict `0x` + 40 hex, any case. */
85
+ const isEthAddress = (value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value);
86
+
87
+ //#endregion
88
+ export { ZERO_ETH_ADDRESS, getDepositClaimDigest, getOcapReleaseDigest, isEthAddress, recoverEthSigner };
@@ -0,0 +1,47 @@
1
+ //#region src/bridge-release-window.d.ts
2
+ /**
3
+ * Rolling 24 h release window (#1466, bridge/docs/ocap-protocols.md §3 check 7).
4
+ *
5
+ * One ring is 24 hourly slots. Slot `s = hour mod 24` holds `"<hourIndex>:<amountInBaseUnits>"`. The clock is the tx
6
+ * time, never wall time, and it never runs backwards inside a ring: `h = max(hour(txTime), max stored hourIndex)`.
7
+ * Pure functions, no state access, so the arithmetic is testable on its own.
8
+ */
9
+ declare const HOUR_MS = 3600000;
10
+ declare const WINDOW_HOURS = 24;
11
+ /**
12
+ * How far (hours) a stored slot may be ahead of the tx hour before the release is refused. The clock of a ring never
13
+ * moves backwards, so a slot stamped in the far future (a node clock that ran ahead once) would otherwise be adopted
14
+ * for good: every later release would be judged at that hour and the window would stop following real time. Small skews
15
+ * (a few seconds of drift across an hour boundary, two nodes' clocks) are tolerated; beyond this the release fails
16
+ * closed until the tx time catches up.
17
+ */
18
+ declare const MAX_RING_SKEW_HOURS = 2;
19
+ interface RingSlot {
20
+ hourIndex: number;
21
+ amount: bigint;
22
+ }
23
+ /** Parses a stored slot. Anything but the exact canonical form is corruption and throws (the release fails closed). */
24
+ declare function parseRingSlot(data: unknown): RingSlot;
25
+ declare const formatRingSlot: (slot: RingSlot) => string;
26
+ declare const hourOf: (timeMs: number) => number;
27
+ interface RingEvaluation {
28
+ /** the clock after this release: `max(hour(txTime), max stored hourIndex)` */
29
+ hour: number;
30
+ /** slot to write: `hour mod 24` */
31
+ slot: number;
32
+ /** sum of the slots inside the window `hour - 24 < hourIndex <= hour`, before this release */
33
+ used: bigint;
34
+ /** hours the newest stored slot is ahead of the tx hour (0 when it is not) */
35
+ skew: number;
36
+ /** whether `used + amount <= cap` */
37
+ allowed: boolean;
38
+ /** what the slot must hold after this release */
39
+ next: RingSlot;
40
+ }
41
+ /**
42
+ * Evaluates one release against a ring. `slots[i]` is the stored slot `i` (or `null` when it was never written).
43
+ * Does not check `allowed`: the caller rejects when it is false.
44
+ */
45
+ declare function evaluateRing(slots: ReadonlyArray<RingSlot | null>, txTimeMs: number, amount: bigint, cap: bigint): RingEvaluation;
46
+ //#endregion
47
+ export { HOUR_MS, MAX_RING_SKEW_HOURS, RingEvaluation, RingSlot, WINDOW_HOURS, evaluateRing, formatRingSlot, hourOf, parseRingSlot };
@@ -0,0 +1,62 @@
1
+ //#region src/bridge-release-window.ts
2
+ /**
3
+ * Rolling 24 h release window (#1466, bridge/docs/ocap-protocols.md §3 check 7).
4
+ *
5
+ * One ring is 24 hourly slots. Slot `s = hour mod 24` holds `"<hourIndex>:<amountInBaseUnits>"`. The clock is the tx
6
+ * time, never wall time, and it never runs backwards inside a ring: `h = max(hour(txTime), max stored hourIndex)`.
7
+ * Pure functions, no state access, so the arithmetic is testable on its own.
8
+ */
9
+ const HOUR_MS = 36e5;
10
+ const WINDOW_HOURS = 24;
11
+ /**
12
+ * How far (hours) a stored slot may be ahead of the tx hour before the release is refused. The clock of a ring never
13
+ * moves backwards, so a slot stamped in the far future (a node clock that ran ahead once) would otherwise be adopted
14
+ * for good: every later release would be judged at that hour and the window would stop following real time. Small skews
15
+ * (a few seconds of drift across an hour boundary, two nodes' clocks) are tolerated; beyond this the release fails
16
+ * closed until the tx time catches up.
17
+ */
18
+ const MAX_RING_SKEW_HOURS = 2;
19
+ const SLOT_DATA_PATTERN = /^(0|[1-9]\d{0,14}):(0|[1-9]\d{0,77})$/;
20
+ /** Parses a stored slot. Anything but the exact canonical form is corruption and throws (the release fails closed). */
21
+ function parseRingSlot(data) {
22
+ if (typeof data !== "string") throw new Error("release window slot is not a string");
23
+ const match = SLOT_DATA_PATTERN.exec(data);
24
+ if (!match) throw new Error(`release window slot is malformed: ${String(data).slice(0, 80)}`);
25
+ return {
26
+ hourIndex: Number(match[1]),
27
+ amount: BigInt(match[2])
28
+ };
29
+ }
30
+ const formatRingSlot = (slot) => `${slot.hourIndex}:${slot.amount.toString(10)}`;
31
+ const hourOf = (timeMs) => Math.floor(timeMs / HOUR_MS);
32
+ /**
33
+ * Evaluates one release against a ring. `slots[i]` is the stored slot `i` (or `null` when it was never written).
34
+ * Does not check `allowed`: the caller rejects when it is false.
35
+ */
36
+ function evaluateRing(slots, txTimeMs, amount, cap) {
37
+ const txHour = hourOf(txTimeMs);
38
+ let hour = txHour;
39
+ for (const slot of slots) if (slot && slot.hourIndex > hour) hour = slot.hourIndex;
40
+ let used = 0n;
41
+ for (const slot of slots) if (slot && hour - WINDOW_HOURS < slot.hourIndex && slot.hourIndex <= hour) used += slot.amount;
42
+ const index = hour % WINDOW_HOURS;
43
+ const current = slots[index] ?? null;
44
+ const next = current && current.hourIndex === hour ? {
45
+ hourIndex: hour,
46
+ amount: current.amount + amount
47
+ } : {
48
+ hourIndex: hour,
49
+ amount
50
+ };
51
+ return {
52
+ hour,
53
+ slot: index,
54
+ skew: hour - txHour,
55
+ used,
56
+ allowed: used + amount <= cap,
57
+ next
58
+ };
59
+ }
60
+
61
+ //#endregion
62
+ export { HOUR_MS, MAX_RING_SKEW_HOURS, WINDOW_HOURS, evaluateRing, formatRingSlot, hourOf, parseRingSlot };
@@ -0,0 +1,24 @@
1
+ //#region src/bridge-reserve.d.ts
2
+ /**
3
+ * Early rejection (R5) of a bridge reserve as an acting party (#1464, #1505, bridge/docs/ocap-protocols.md §1, §v2.3).
4
+ *
5
+ * A reserve is every account with the `ROLE_BRIDGE_RESERVE` DID role (one per bridge, derived, keyless). The role is
6
+ * read from the address itself, so no config and no state lookup is needed, and a crafted role-25 address that maps to
7
+ * no bridge is refused as well. The reserve must never be sender, delegator, multisig signer or gas sponsor.
8
+ * The checks are defence in depth for the paths that spend an account's balance before the post-execution invariant
9
+ * gate is installed (gas, paymaster), and for any future signature scheme.
10
+ * Pure function of the tx: no state, no counters.
11
+ */
12
+ declare const BRIDGE_RESERVE_ACTOR_FORBIDDEN = "BRIDGE_RESERVE_ACTOR_FORBIDDEN";
13
+ /** Whether `address` is a bridge reserve address (syntactic: the DID role). */
14
+ declare const isBridgeReserve: (address: unknown) => boolean;
15
+ declare function assertBridgeReserveNotActor(context: {
16
+ tx?: {
17
+ from?: string;
18
+ delegator?: string;
19
+ } | null;
20
+ }): void;
21
+ /** Paymaster / gas sponsor. The sponsor header is not covered by the tx signature, so the failure strikes nobody. */
22
+ declare function assertBridgeReserveNotSponsor(sponsorAddress: string): void;
23
+ //#endregion
24
+ export { BRIDGE_RESERVE_ACTOR_FORBIDDEN, assertBridgeReserveNotActor, assertBridgeReserveNotSponsor, isBridgeReserve };
@@ -0,0 +1,41 @@
1
+ import { isBridgeReserveRole } from "@ocap/tx-pipeline";
2
+ import { CustomError } from "@ocap/util/lib/error";
3
+ import { getListField } from "@ocap/util/lib/get-list-field";
4
+
5
+ //#region src/bridge-reserve.ts
6
+ /**
7
+ * Early rejection (R5) of a bridge reserve as an acting party (#1464, #1505, bridge/docs/ocap-protocols.md §1, §v2.3).
8
+ *
9
+ * A reserve is every account with the `ROLE_BRIDGE_RESERVE` DID role (one per bridge, derived, keyless). The role is
10
+ * read from the address itself, so no config and no state lookup is needed, and a crafted role-25 address that maps to
11
+ * no bridge is refused as well. The reserve must never be sender, delegator, multisig signer or gas sponsor.
12
+ * The checks are defence in depth for the paths that spend an account's balance before the post-execution invariant
13
+ * gate is installed (gas, paymaster), and for any future signature scheme.
14
+ * Pure function of the tx: no state, no counters.
15
+ */
16
+ const BRIDGE_RESERVE_ACTOR_FORBIDDEN = "BRIDGE_RESERVE_ACTOR_FORBIDDEN";
17
+ /** Whether `address` is a bridge reserve address (syntactic: the DID role). */
18
+ const isBridgeReserve = (address) => isBridgeReserveRole(address);
19
+ const forbidden = (role) => new CustomError(BRIDGE_RESERVE_ACTOR_FORBIDDEN, `A bridge reserve can not act as ${role}`, { persist: false });
20
+ function assertBridgeReserveNotActor(context) {
21
+ const { tx } = context;
22
+ if (!tx) return;
23
+ if (isBridgeReserve(tx.from)) throw forbidden("transaction sender");
24
+ if (isBridgeReserve(tx.delegator)) throw forbidden("delegator");
25
+ const signatures = getListField(tx, "signatures") || [];
26
+ for (const sig of signatures) {
27
+ if (isBridgeReserve(sig?.signer)) throw forbidden("multisig signer");
28
+ if (isBridgeReserve(sig?.delegator)) throw forbidden("multisig delegator");
29
+ }
30
+ }
31
+ /** Paymaster / gas sponsor. The sponsor header is not covered by the tx signature, so the failure strikes nobody. */
32
+ function assertBridgeReserveNotSponsor(sponsorAddress) {
33
+ if (isBridgeReserve(sponsorAddress)) {
34
+ const err = forbidden("gas sponsor");
35
+ err._unauthenticatedExtraFailure = true;
36
+ throw err;
37
+ }
38
+ }
39
+
40
+ //#endregion
41
+ export { BRIDGE_RESERVE_ACTOR_FORBIDDEN, assertBridgeReserveNotActor, assertBridgeReserveNotSponsor, isBridgeReserve };
package/esm/execute.d.mts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ITxGasQuotaTelemetry, ITxSecurityWarning } from "./gas-security-guard.mjs";
2
2
  import { TxTimer } from "./tx-timer.mjs";
3
- import { Blacklist } from "@ocap/state";
4
3
  import { CustomError } from "@ocap/util/lib/error";
4
+ import { Blacklist } from "@ocap/state";
5
5
  import { IAccountState, IBaseContext, IGasContext } from "@ocap/types";
6
6
 
7
7
  //#region src/execute.d.ts
package/esm/execute.mjs CHANGED
@@ -1,18 +1,20 @@
1
+ import { assertBridgeReserveNotActor, assertBridgeReserveNotSponsor } from "./bridge-reserve.mjs";
1
2
  import { classifyErrorStrikeCategory, evaluateStakeForGasEligibility, extractTransactionTargets, normalizeShortTxType, recordActorSecurityStrike, resolveGasSecurityConfig, resolveVerifiedStrikeActors, restoreActorSecurityRecords, snapshotActorSecurityRecords, verifyAndConsumeUnlinkableGasPass, verifyPaymasterConstraints } from "./gas-security-guard.mjs";
2
3
  import { getRewardLocker, isGasStakeAddress, isGasStakeInput, isGasStakeValid } from "./util.mjs";
3
4
  import ensure_cost_default from "./pipes/ensure-cost.mjs";
4
5
  import ensure_gas_default from "./pipes/ensure-gas.mjs";
5
6
  import { WriteLedger } from "./pipes/write-ledger.mjs";
7
+ import { assertStatelessTxRules } from "./stateless-prefix.mjs";
6
8
  import { TxTimer } from "./tx-timer.mjs";
9
+ import { toTxHash, types } from "@ocap/mcrypto";
10
+ import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, prepareBridgeReserveGate, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
11
+ import { CustomError } from "@ocap/util/lib/error";
12
+ import { getListField } from "@ocap/util/lib/get-list-field";
7
13
  import { isFromPublicKey, toAddress, toTypeInfo } from "@arcblock/did";
8
14
  import { toDelegateAddress, toStakeAddress } from "@arcblock/did-util";
9
15
  import * as JWT from "@arcblock/jwt";
10
- import { toTxHash, types } from "@ocap/mcrypto";
11
16
  import { account, evidence, parseNonceBn } from "@ocap/state";
12
- import { Runner, inspectPostExecutionInvariants, installStateWriteInterceptor, pipes, rollbackTrackedStateWrites, verifyImplicitAssetOwnership } from "@ocap/tx-pipeline";
13
17
  import { BN, fromTokenToUnit, isSameDid, toBase58, toBase64, toBuffer } from "@ocap/util";
14
- import { CustomError } from "@ocap/util/lib/error";
15
- import { getListField } from "@ocap/util/lib/get-list-field";
16
18
  import { getRelatedAddresses } from "@ocap/util/lib/get-related-addr";
17
19
  import camelCase from "lodash/camelCase.js";
18
20
  import cloneDeep from "lodash/cloneDeep.js";
@@ -160,6 +162,20 @@ const createExecute = ({ filter, runAsLambda }) => {
160
162
  resolve();
161
163
  })).catch(reject);
162
164
  });
165
+ /**
166
+ * Append the tx to the verifiable ledger at the point where its tx state is written (#1419).
167
+ *
168
+ * Invariant: a ledger row exists only for a tx that also gets a `statedb.tx` row, i.e. a successful tx or a
169
+ * failed tx that went through the failed-tx gas charge (`ensureGasFeePaid`). The append used to run in the
170
+ * pre-execute pipeline, ahead of the protocol runner, so every protocol-phase rejection that is not persisted
171
+ * (itx schema errors, `VerifyInfo` defaults, every `VerifyDelegation` rejection, multisig signature failures,
172
+ * a failed-tx gas charge nobody can pay) left an uncharged row in the append-only ledger.
173
+ *
174
+ * The append still precedes `statedb.tx.create` and the statedb commit, so the ledger stays write-ahead of the
175
+ * committed state, and `WriteLedger` is idempotent per context (`ledgerSequence`), so `runAsLambda` retries
176
+ * reuse the sequence allocated by the first attempt (#973).
177
+ */
178
+ const appendLedgerEntry = (context) => runSinglePipe(WriteLedger, context);
163
179
  const hasCommittedUnsignedTx = async (context) => {
164
180
  if (!context.unsignedTxHash || !hasEvidenceStore(context.statedb)) return false;
165
181
  const unsignedKey = toUnsignedEvidenceKey(context.unsignedTxHash);
@@ -481,6 +497,7 @@ const createExecute = ({ filter, runAsLambda }) => {
481
497
  hdrErr._unauthenticatedExtraFailure = true;
482
498
  throw hdrErr;
483
499
  }
500
+ assertBridgeReserveNotSponsor(sponsorAddress);
484
501
  let jwtVerified = false;
485
502
  try {
486
503
  jwtVerified = Boolean(await JWT.verify(token$1, pk, {
@@ -718,6 +735,22 @@ const createExecute = ({ filter, runAsLambda }) => {
718
735
  if (protocolsMap && context.txType && !protocolsMap[getTxName(context.txType)]) return next(new CustomError("UNSUPPORTED_TX", `Unsupported tx type ${context.txType}`, { persist: false }));
719
736
  return next();
720
737
  });
738
+ pre.use((context, next) => {
739
+ try {
740
+ assertBridgeReserveNotActor(context);
741
+ return next();
742
+ } catch (err) {
743
+ return next(err);
744
+ }
745
+ });
746
+ pre.use(async (context, next) => {
747
+ try {
748
+ await assertStatelessTxRules(context, context._protocols);
749
+ return next();
750
+ } catch (err) {
751
+ return next(err);
752
+ }
753
+ });
721
754
  pre.use((context, next) => {
722
755
  if (context._preFlightSnapshotApplied) return next();
723
756
  return pipes.VerifyServiceFee(context, next);
@@ -776,7 +809,6 @@ const createExecute = ({ filter, runAsLambda }) => {
776
809
  if (!senderState) await assertNonExistentSenderAdmissible(context);
777
810
  if (context.txHash) syncState.inFlightTxHashes.set(context.txHash, execId);
778
811
  if (context.unsignedTxHash) syncState.inFlightUnsignedTxHashes.set(context.unsignedTxHash, execId);
779
- await runSinglePipe(WriteLedger, context);
780
812
  });
781
813
  return next();
782
814
  } catch (err) {
@@ -888,6 +920,7 @@ const createExecute = ({ filter, runAsLambda }) => {
888
920
  let error = rawError;
889
921
  context.timer?.mark("protocol");
890
922
  if (!error) try {
923
+ await prepareBridgeReserveGate(context);
891
924
  inspectPostExecutionInvariants(context);
892
925
  } catch (invariantErr) {
893
926
  error = invariantErr;
@@ -909,6 +942,20 @@ const createExecute = ({ filter, runAsLambda }) => {
909
942
  await ensureGasFeePaid(context);
910
943
  txState = states.tx.create(context, txStatus);
911
944
  }
945
+ try {
946
+ await appendLedgerEntry(context);
947
+ } catch (ledgerErr) {
948
+ if (!error) {
949
+ await rollbackTrackedStateWrites(context);
950
+ context.events = [];
951
+ }
952
+ context.logger?.error("Failed to append transaction to ledger", {
953
+ error: ledgerErr,
954
+ txError: error,
955
+ txHash: context.txHash
956
+ });
957
+ return reject(error || ledgerErr);
958
+ }
912
959
  await context.statedb.tx.create(txState.hash, txState, context);
913
960
  await recordUnsignedTxInStateDb(context, txState.hash);
914
961
  context.timer?.mark("txstate");
@@ -977,6 +1024,7 @@ const createExecute = ({ filter, runAsLambda }) => {
977
1024
  ctx.timer?.mark("lockWait");
978
1025
  try {
979
1026
  await execute(ctx, protocols, true);
1027
+ await appendLedgerEntry(ctx);
980
1028
  } finally {
981
1029
  if (ctx.ledgerSequence && !savedLedgerSequence) {
982
1030
  savedLedgerSequence = ctx.ledgerSequence;
@@ -1063,6 +1111,11 @@ const createExecute = ({ filter, runAsLambda }) => {
1063
1111
  try {
1064
1112
  await ensureGasFeePaid(ctx);
1065
1113
  await attachSecurityStrikeToError(err, ctx);
1114
+ await appendLedgerEntry(ctx);
1115
+ if (ctx.ledgerSequence && !savedLedgerSequence) {
1116
+ savedLedgerSequence = ctx.ledgerSequence;
1117
+ context.ledgerSequence = ctx.ledgerSequence;
1118
+ }
1066
1119
  const state = getStates(context).tx.create(ctx, txStatus);
1067
1120
  await ctx.statedb.tx.create(state.hash, state, ctx);
1068
1121
  await recordUnsignedTxInStateDb(ctx, state.hash);
@@ -18,7 +18,7 @@ declare const DEFAULT_FISHERMAN_BOUNTY_BPS = 1000;
18
18
  /**
19
19
  * High-overhead creator, factory, token-issuance, rollup, and batch transaction types
20
20
  * that ALWAYS require direct gas payment (`requiresDirectGas: true`) and cannot waive
21
- * gas via self-staked `Stake-for-Gas` or Unlinkable Gas Pass.
21
+ * gas via self-staked `Stake-for-Gas`, Unlinkable Gas Pass or a third-party sponsor's stake (#1420).
22
22
  */
23
23
  declare const DIRECT_GAS_REQUIRED_TX_TYPES: ReadonlySet<string>;
24
24
  /**
@@ -150,7 +150,11 @@ interface IStakeForGasEligibilityResult {
150
150
  }
151
151
  /**
152
152
  * 3D `Stake-for-Gas` Eligibility Gate:
153
- * 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only).
153
+ * 0. `txType` must not be in `DIRECT_GAS_REQUIRED_TX_TYPES`. This holds for every stake-based waiver: self
154
+ * stake, gas pass and third-party sponsor stake (#1420). Only an operator-configured
155
+ * `txGas.freeGasAllowedTxTypes` entry can lift it.
156
+ * 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only). Third-party sponsors are
157
+ * exempt from this allowlist unless `enforceSponsor3DEligibility` is on.
154
158
  * 2. `txSize` must be <= `maxFreeGasTxSize` (default 4096 bytes).
155
159
  * 3. `stateOps` (`estimate.create + estimate.update`) must be <= `maxFreeGasStateOps` (default 6).
156
160
  * 4. Failed transactions (`isFailedTxGasCharge === true`) NEVER waive gas.
@@ -1,11 +1,11 @@
1
- import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
2
- import { toStakeAddress } from "@arcblock/did-util";
3
1
  import { getHasher, getSigner } from "@ocap/mcrypto";
4
- import { account, evidence, parseNonceBn, stake } from "@ocap/state";
5
2
  import { pipes } from "@ocap/tx-pipeline";
6
- import { BN, fromTokenToUnit, isSameDid, toAddress as toAddress$1 } from "@ocap/util";
7
3
  import { CustomError } from "@ocap/util/lib/error";
8
4
  import { getListField } from "@ocap/util/lib/get-list-field";
5
+ import { isFromPublicKey, toTypeInfo } from "@arcblock/did";
6
+ import { toStakeAddress } from "@arcblock/did-util";
7
+ import { account, evidence, parseNonceBn, stake } from "@ocap/state";
8
+ import { BN, fromTokenToUnit, isSameDid, toAddress as toAddress$1 } from "@ocap/util";
9
9
  import cloneDeep from "lodash/cloneDeep.js";
10
10
  import { createHash } from "node:crypto";
11
11
  import { fromPublicKey as fromPublicKey$1 } from "@ocap/wallet";
@@ -32,7 +32,7 @@ const MAX_FREE_VARIANTS = 2;
32
32
  /**
33
33
  * High-overhead creator, factory, token-issuance, rollup, and batch transaction types
34
34
  * that ALWAYS require direct gas payment (`requiresDirectGas: true`) and cannot waive
35
- * gas via self-staked `Stake-for-Gas` or Unlinkable Gas Pass.
35
+ * gas via self-staked `Stake-for-Gas`, Unlinkable Gas Pass or a third-party sponsor's stake (#1420).
36
36
  */
37
37
  const DIRECT_GAS_REQUIRED_TX_TYPES = new Set([
38
38
  "create_token",
@@ -189,7 +189,11 @@ function getOrCreateActorRecord(reg, rawActor, nowMs, cfg) {
189
189
  }
190
190
  /**
191
191
  * 3D `Stake-for-Gas` Eligibility Gate:
192
- * 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only).
192
+ * 0. `txType` must not be in `DIRECT_GAS_REQUIRED_TX_TYPES`. This holds for every stake-based waiver: self
193
+ * stake, gas pass and third-party sponsor stake (#1420). Only an operator-configured
194
+ * `txGas.freeGasAllowedTxTypes` entry can lift it.
195
+ * 1. `txType` must be in `FREE_GAS_ELIGIBLE_TX_TYPES` (everyday user actions only). Third-party sponsors are
196
+ * exempt from this allowlist unless `enforceSponsor3DEligibility` is on.
193
197
  * 2. `txSize` must be <= `maxFreeGasTxSize` (default 4096 bytes).
194
198
  * 3. `stateOps` (`estimate.create + estimate.update`) must be <= `maxFreeGasStateOps` (default 6).
195
199
  * 4. Failed transactions (`isFailedTxGasCharge === true`) NEVER waive gas.
@@ -202,13 +206,15 @@ function evaluateStakeForGasEligibility(params) {
202
206
  };
203
207
  const shortType = normalizeShortTxType(params.txType);
204
208
  const customAllowlist = (params.config?.transaction?.txGas)?.freeGasAllowedTxTypes;
205
- if ((!params.isThirdPartySponsor || params.enforceSponsor3DEligibility === true) && shortType) {
209
+ const enforceAllowlist = !params.isThirdPartySponsor || params.enforceSponsor3DEligibility === true;
210
+ if (shortType) {
211
+ const requiresDirectGas = DIRECT_GAS_REQUIRED_TX_TYPES.has(shortType);
206
212
  if (Array.isArray(customAllowlist) && customAllowlist.length > 0) {
207
- if (!customAllowlist.some((t) => normalizeShortTxType(t) === shortType || t === params.txType)) return {
213
+ if (!customAllowlist.some((t) => normalizeShortTxType(t) === shortType || t === params.txType) && (enforceAllowlist || requiresDirectGas)) return {
208
214
  eligible: false,
209
215
  reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
210
216
  };
211
- } else if (DIRECT_GAS_REQUIRED_TX_TYPES.has(shortType) || typeof params.txType === "string" && params.txType.startsWith("fg:t:") && !FREE_GAS_ELIGIBLE_TX_TYPES.has(shortType)) return {
217
+ } else if (requiresDirectGas || enforceAllowlist && typeof params.txType === "string" && params.txType.startsWith("fg:t:") && !FREE_GAS_ELIGIBLE_TX_TYPES.has(shortType)) return {
212
218
  eligible: false,
213
219
  reason: "TX_TYPE_REQUIRES_DIRECT_GAS"
214
220
  };
@@ -565,6 +571,7 @@ const BENIGN_REJECT_CODES = new Set([
565
571
  "INVALID_TX_TIME",
566
572
  "EXPIRED",
567
573
  "TX_EXPIRED",
574
+ "EXPIRED_TX",
568
575
  "NOT_FOUND",
569
576
  "STAKE_NOT_FOUND",
570
577
  "INVALID_LOCK_STATUS",