@ocap/tx-pipeline 1.31.1 → 1.31.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/bridge-release-keys.d.mts +33 -0
- package/esm/bridge-release-keys.mjs +81 -0
- package/esm/bridge-reserves.d.mts +107 -0
- package/esm/bridge-reserves.mjs +242 -0
- package/esm/helpers/bridge-withdraw.d.mts +86 -0
- package/esm/helpers/bridge-withdraw.mjs +123 -0
- package/esm/helpers/replay-guard.d.mts +19 -1
- package/esm/helpers/replay-guard.mjs +39 -1
- package/esm/index.d.mts +3 -1
- package/esm/index.mjs +8 -6
- package/esm/legacy-protocol-sunset.d.mts +2 -2
- package/esm/legacy-protocol-sunset.mjs +5 -5
- package/esm/legacy-rollup-archive.d.mts +67 -0
- package/esm/legacy-rollup-archive.mjs +199 -0
- package/esm/library.d.mts +4 -4
- package/esm/library.mjs +3 -3
- package/esm/native-abt-exchange.d.mts +3 -0
- package/esm/native-abt-exchange.mjs +93 -46
- package/esm/pipes/bridge-release-gate.d.mts +30 -0
- package/esm/pipes/bridge-release-gate.mjs +143 -0
- package/esm/pipes/bridge-reserve-v2-gate.d.mts +53 -0
- package/esm/pipes/bridge-reserve-v2-gate.mjs +264 -0
- package/esm/pipes/decode-tx.mjs +29 -4
- package/esm/pipes/extract-signer.mjs +1 -1
- package/esm/pipes/extract-state.mjs +2 -2
- package/esm/pipes/post-execution-invariant-gate.d.mts +19 -2
- package/esm/pipes/post-execution-invariant-gate.mjs +121 -6
- package/esm/pipes/pre-flight-waf.d.mts +18 -1
- package/esm/pipes/pre-flight-waf.mjs +48 -13
- package/esm/pipes/update-owner.mjs +1 -1
- package/esm/pipes/verify-account-migration.mjs +1 -1
- package/esm/pipes/verify-delegation.mjs +49 -25
- package/esm/pipes/verify-multisig-v2.mjs +5 -4
- package/esm/pipes/verify-multisig.mjs +5 -4
- package/esm/pipes/verify-signature.d.mts +7 -1
- package/esm/pipes/verify-signature.mjs +119 -16
- package/esm/pipes/verify-signer.mjs +2 -2
- package/esm/pipes/verify-token-access.mjs +1 -1
- package/esm/pipes/verify-token-balance.mjs +1 -1
- package/esm/pipes/verify-tx-input.mjs +1 -1
- package/esm/pipes/verify-tx-size.mjs +1 -1
- package/esm/pipes/verify-tx.mjs +12 -5
- package/esm/super-suites-foundation.mjs +6 -6
- package/esm/transaction-block.d.mts +6 -2
- package/esm/transaction-block.mjs +282 -40
- package/esm/uniswap-router.d.mts +247 -1
- package/esm/uniswap-router.mjs +573 -2
- package/lib/bridge-release-keys.cjs +88 -0
- package/lib/bridge-release-keys.d.cts +33 -0
- package/lib/bridge-reserves.cjs +257 -0
- package/lib/bridge-reserves.d.cts +107 -0
- package/lib/helpers/bridge-withdraw.cjs +136 -0
- package/lib/helpers/bridge-withdraw.d.cts +86 -0
- package/lib/helpers/replay-guard.cjs +39 -0
- package/lib/helpers/replay-guard.d.cts +20 -2
- package/lib/index.cjs +25 -5
- package/lib/index.d.cts +3 -1
- package/lib/legacy-protocol-sunset.cjs +7 -7
- package/lib/legacy-protocol-sunset.d.cts +2 -2
- package/lib/legacy-rollup-archive.cjs +208 -0
- package/lib/legacy-rollup-archive.d.cts +67 -0
- package/lib/library.cjs +14 -68
- package/lib/library.d.cts +4 -4
- package/lib/native-abt-exchange.cjs +93 -46
- package/lib/native-abt-exchange.d.cts +3 -0
- package/lib/pipes/bridge-release-gate.cjs +145 -0
- package/lib/pipes/bridge-release-gate.d.cts +30 -0
- package/lib/pipes/bridge-reserve-v2-gate.cjs +273 -0
- package/lib/pipes/bridge-reserve-v2-gate.d.cts +53 -0
- package/lib/pipes/decode-itx.d.cts +1 -1
- package/lib/pipes/decode-tx.cjs +28 -3
- package/lib/pipes/decode-tx.d.cts +1 -1
- package/lib/pipes/extract-signer.cjs +1 -1
- package/lib/pipes/extract-state.cjs +3 -3
- package/lib/pipes/post-execution-invariant-gate.cjs +121 -4
- package/lib/pipes/post-execution-invariant-gate.d.cts +19 -2
- package/lib/pipes/pre-flight-waf.cjs +51 -13
- package/lib/pipes/pre-flight-waf.d.cts +19 -2
- package/lib/pipes/update-owner.cjs +1 -1
- package/lib/pipes/update-owner.d.cts +1 -1
- package/lib/pipes/verify-account-migration.cjs +1 -1
- package/lib/pipes/verify-delegation.cjs +50 -26
- package/lib/pipes/verify-multisig-v2.cjs +5 -4
- package/lib/pipes/verify-multisig.cjs +5 -4
- package/lib/pipes/verify-service-fee.d.cts +1 -1
- package/lib/pipes/verify-signature.cjs +118 -14
- package/lib/pipes/verify-signature.d.cts +8 -2
- package/lib/pipes/verify-signer.cjs +2 -2
- package/lib/pipes/verify-token-access.cjs +1 -1
- package/lib/pipes/verify-token-balance.cjs +1 -1
- package/lib/pipes/verify-tx-input.cjs +1 -1
- package/lib/pipes/verify-tx-size.cjs +1 -1
- package/lib/pipes/verify-tx-size.d.cts +1 -1
- package/lib/pipes/verify-tx.cjs +11 -5
- package/lib/pipes/verify-tx.d.cts +1 -1
- package/lib/super-suites-foundation.cjs +6 -6
- package/lib/transaction-block.cjs +282 -40
- package/lib/transaction-block.d.cts +6 -2
- package/lib/uniswap-router.cjs +576 -1
- package/lib/uniswap-router.d.cts +247 -1
- package/package.json +10 -10
- package/esm/evm-simplified-bridge.d.mts +0 -1370
- package/esm/evm-simplified-bridge.mjs +0 -3875
- package/lib/evm-simplified-bridge.cjs +0 -3943
- package/lib/evm-simplified-bridge.d.cts +0 -1370
|
@@ -1,3943 +0,0 @@
|
|
|
1
|
-
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
|
-
let _ocap_mcrypto = require("@ocap/mcrypto");
|
|
3
|
-
let _ocap_util_lib_error = require("@ocap/util/lib/error");
|
|
4
|
-
let node_crypto = require("node:crypto");
|
|
5
|
-
let elliptic = require("elliptic");
|
|
6
|
-
elliptic = require_rolldown_runtime.__toESM(elliptic);
|
|
7
|
-
|
|
8
|
-
//#region src/evm-simplified-bridge.ts
|
|
9
|
-
const keccak256 = _ocap_mcrypto.Hasher.Keccak.hash256;
|
|
10
|
-
const secp256k1Curve = new elliptic.default.ec("secp256k1");
|
|
11
|
-
const ErrorCode = {
|
|
12
|
-
InvalidBridge: "INVALID_EVM_SIMPLIFIED_BRIDGE",
|
|
13
|
-
ForbiddenBridge: "FORBIDDEN_EVM_SIMPLIFIED_BRIDGE"
|
|
14
|
-
};
|
|
15
|
-
const DEFAULT_MIN_EVM_CONFIRMATIONS = 12;
|
|
16
|
-
const DEFAULT_MAX_ROLLUP_BLOCK_SIZE = 256;
|
|
17
|
-
const MAX_EDGE_WEBHOOK_SKEW_SECONDS = 300;
|
|
18
|
-
const MAX_EDGE_WEBHOOK_BODY_BYTES = 65536;
|
|
19
|
-
const MAX_TRACKED_WEBHOOK_NONCES = 4096;
|
|
20
|
-
const MIN_DIRECT_VOUCHER_TTL_SECONDS = 300;
|
|
21
|
-
const MAX_DIRECT_VOUCHER_TTL_SECONDS = 604800;
|
|
22
|
-
const DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS = 86400;
|
|
23
|
-
const DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT = 1;
|
|
24
|
-
const DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS = Object.freeze([
|
|
25
|
-
"fg:t:create_rollup",
|
|
26
|
-
"fg:t:update_rollup",
|
|
27
|
-
"fg:t:join_rollup",
|
|
28
|
-
"fg:t:leave_rollup",
|
|
29
|
-
"fg:t:create_rollup_block",
|
|
30
|
-
"fg:t:claim_block_reward",
|
|
31
|
-
"fg:t:pause_rollup",
|
|
32
|
-
"fg:t:resume_rollup"
|
|
33
|
-
]);
|
|
34
|
-
const EIP712_BRIDGE_DOMAIN_NAME = "ArcEvmBridgeGateway";
|
|
35
|
-
const EIP712_BRIDGE_DOMAIN_VERSION = "1";
|
|
36
|
-
const DEFAULT_VERIFYING_CONTRACT_ADDRESS = "0x0000000000000000000000000000000000001241";
|
|
37
|
-
const EMPTY_ROLLUP_MERKLE_ROOT = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
|
|
38
|
-
const ZERO_BYTES32_HASH = "0x0000000000000000000000000000000000000000000000000000000000000000";
|
|
39
|
-
const ZERO_EVM_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
40
|
-
const BYTES32_HEX_REGEX = /^0x[0-9a-fA-F]{64}$/;
|
|
41
|
-
const EVM_ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;
|
|
42
|
-
const CANONICAL_UINT256_DECIMAL_REGEX = /^(0|[1-9]\d{0,77})$/;
|
|
43
|
-
/**
|
|
44
|
-
* Issue #1241 & #1243:
|
|
45
|
-
* Redesigned Simplified EVM Bridge Contract Specification (`ArcEvmBridgeGateway.sol`).
|
|
46
|
-
* Implements the Dual-Track KISS architecture + 3-Layer Anti-Vault-Drain Security + EIP-712 Typed Data Signing:
|
|
47
|
-
* 1. `payForOcapService`: Pay-Where-You-Are direct cashier (ERC-20 ABT / USDC stays on EVM, service delivered on OCAP).
|
|
48
|
-
* 2. `depositForNativeAbt` & `claimWithdrawWithDirectVoucher` (Zero-Rollup-Block EIP-712 Pull Mode) / `claimWithdrawWithMerkleProof`.
|
|
49
|
-
*/
|
|
50
|
-
const ARC_EVM_BRIDGE_GATEWAY_SOLIDITY_SPEC = `// SPDX-License-Identifier: MIT
|
|
51
|
-
pragma solidity ^0.8.24;
|
|
52
|
-
|
|
53
|
-
interface IERC20Minimal {
|
|
54
|
-
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
|
|
55
|
-
function transfer(address recipient, uint256 amount) external returns (bool);
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
contract ArcEvmBridgeGateway {
|
|
59
|
-
bytes32 public constant EIP712_DOMAIN_TYPEHASH =
|
|
60
|
-
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
|
|
61
|
-
bytes32 public constant DIRECT_WITHDRAW_TYPEHASH =
|
|
62
|
-
keccak256("DirectWithdrawVoucher(bytes32 bridgeIdHash,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 expiresAt)");
|
|
63
|
-
|
|
64
|
-
address public immutable canonicalAbtToken;
|
|
65
|
-
address public immutable guardian;
|
|
66
|
-
bytes32 public immutable bridgeIdHash;
|
|
67
|
-
bytes32 public immutable DOMAIN_SEPARATOR;
|
|
68
|
-
uint256 public immutable minValidatorSignatures;
|
|
69
|
-
uint256 public immutable maxDailyWithdrawCap;
|
|
70
|
-
uint256 public immutable largeWithdrawThreshold;
|
|
71
|
-
uint256 public constant TIMELOCK_DELAY = 24 hours;
|
|
72
|
-
|
|
73
|
-
bool public paused;
|
|
74
|
-
uint256 public latestBlockHeight;
|
|
75
|
-
bytes32 public latestBlockHash;
|
|
76
|
-
uint256 public cumulativeDepositedAbt;
|
|
77
|
-
uint256 public cumulativeWithdrawnAbt;
|
|
78
|
-
|
|
79
|
-
mapping(address => bool) public isBridgeValidator;
|
|
80
|
-
mapping(uint256 => bytes32) public blockMerkleRoots;
|
|
81
|
-
mapping(bytes32 => bool) public processedServiceOrders;
|
|
82
|
-
mapping(bytes32 => bool) public claimedWithdrawTxs;
|
|
83
|
-
mapping(bytes32 => bool) public cancelledWithdrawTxs;
|
|
84
|
-
mapping(bytes32 => uint256) public timelockUnlockAt;
|
|
85
|
-
mapping(uint256 => uint256) public dailyWithdrawnAbt;
|
|
86
|
-
mapping(address => bool) public supportedServiceTokens;
|
|
87
|
-
|
|
88
|
-
event OcapServicePaid(
|
|
89
|
-
bytes32 indexed orderId,
|
|
90
|
-
address indexed payer,
|
|
91
|
-
string recipientDid,
|
|
92
|
-
string serviceDid,
|
|
93
|
-
address paymentToken,
|
|
94
|
-
uint256 amount
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
event NativeAbtDepositLocked(
|
|
98
|
-
address indexed depositor,
|
|
99
|
-
string recipientDid,
|
|
100
|
-
uint256 amount,
|
|
101
|
-
uint256 cumulativeDepositedAbt
|
|
102
|
-
);
|
|
103
|
-
|
|
104
|
-
event RollupBlockSubmitted(
|
|
105
|
-
uint256 indexed height,
|
|
106
|
-
bytes32 previousHash,
|
|
107
|
-
bytes32 merkleRoot,
|
|
108
|
-
bytes32 txsHash,
|
|
109
|
-
bytes32 blockHash
|
|
110
|
-
);
|
|
111
|
-
|
|
112
|
-
event LargeWithdrawTimelocked(
|
|
113
|
-
bytes32 indexed ocapTxHash,
|
|
114
|
-
address indexed recipient,
|
|
115
|
-
uint256 amount,
|
|
116
|
-
uint256 unlockAt
|
|
117
|
-
);
|
|
118
|
-
|
|
119
|
-
event NativeAbtWithdrawClaimed(
|
|
120
|
-
bytes32 indexed ocapTxHash,
|
|
121
|
-
address indexed recipient,
|
|
122
|
-
uint256 amount,
|
|
123
|
-
uint256 blockHeight
|
|
124
|
-
);
|
|
125
|
-
|
|
126
|
-
constructor(
|
|
127
|
-
address _canonicalAbtToken,
|
|
128
|
-
address _guardian,
|
|
129
|
-
bytes32 _bridgeIdHash,
|
|
130
|
-
bytes32 _genesisBlockHash,
|
|
131
|
-
address[] memory _validators,
|
|
132
|
-
uint256 _minValidatorSignatures,
|
|
133
|
-
uint256 _maxDailyWithdrawCap,
|
|
134
|
-
uint256 _largeWithdrawThreshold
|
|
135
|
-
) {
|
|
136
|
-
require(_canonicalAbtToken != address(0) && _guardian != address(0), "ZERO_ADDRESS");
|
|
137
|
-
require(_validators.length >= 2 && _minValidatorSignatures >= 2 && _minValidatorSignatures <= _validators.length, "MULTI_SIGNER_QUORUM_REQUIRED");
|
|
138
|
-
require(_maxDailyWithdrawCap > 0 && _largeWithdrawThreshold > 0, "INVALID_CAPS");
|
|
139
|
-
canonicalAbtToken = _canonicalAbtToken;
|
|
140
|
-
guardian = _guardian;
|
|
141
|
-
bridgeIdHash = _bridgeIdHash;
|
|
142
|
-
minValidatorSignatures = _minValidatorSignatures;
|
|
143
|
-
maxDailyWithdrawCap = _maxDailyWithdrawCap;
|
|
144
|
-
largeWithdrawThreshold = _largeWithdrawThreshold;
|
|
145
|
-
DOMAIN_SEPARATOR = keccak256(
|
|
146
|
-
abi.encode(
|
|
147
|
-
EIP712_DOMAIN_TYPEHASH,
|
|
148
|
-
keccak256(bytes("ArcEvmBridgeGateway")),
|
|
149
|
-
keccak256(bytes("1")),
|
|
150
|
-
block.chainid,
|
|
151
|
-
address(this)
|
|
152
|
-
)
|
|
153
|
-
);
|
|
154
|
-
supportedServiceTokens[_canonicalAbtToken] = true;
|
|
155
|
-
latestBlockHash = _genesisBlockHash;
|
|
156
|
-
for (uint256 i = 0; i < _validators.length; i++) {
|
|
157
|
-
require(_validators[i] != address(0) && !isBridgeValidator[_validators[i]], "INVALID_VALIDATOR");
|
|
158
|
-
isBridgeValidator[_validators[i]] = true;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function setPaused(bool _paused) external {
|
|
163
|
-
require(msg.sender == guardian, "ONLY_GUARDIAN");
|
|
164
|
-
paused = _paused;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
function cancelFraudulentWithdraw(bytes32 ocapTxHash) external {
|
|
168
|
-
require(msg.sender == guardian, "ONLY_GUARDIAN");
|
|
169
|
-
require(!claimedWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED");
|
|
170
|
-
cancelledWithdrawTxs[ocapTxHash] = true;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// Track 1: Pay-Where-You-Are Direct Service Cashier (Zero Foreign Asset Bridge)
|
|
174
|
-
function payForOcapService(
|
|
175
|
-
bytes32 orderId,
|
|
176
|
-
string calldata recipientDid,
|
|
177
|
-
string calldata serviceDid,
|
|
178
|
-
address paymentToken,
|
|
179
|
-
uint256 amount
|
|
180
|
-
) external {
|
|
181
|
-
require(!paused, "BRIDGE_PAUSED");
|
|
182
|
-
require(orderId != bytes32(0) && !processedServiceOrders[orderId], "INVALID_OR_DUPLICATE_ORDER");
|
|
183
|
-
require(supportedServiceTokens[paymentToken], "UNSUPPORTED_PAYMENT_TOKEN");
|
|
184
|
-
require(amount > 0 && bytes(recipientDid).length > 0 && bytes(serviceDid).length > 0, "INVALID_ARGS");
|
|
185
|
-
|
|
186
|
-
processedServiceOrders[orderId] = true;
|
|
187
|
-
require(IERC20Minimal(paymentToken).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILED");
|
|
188
|
-
emit OcapServicePaid(orderId, msg.sender, recipientDid, serviceDid, paymentToken, amount);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
// Track 2A: Canonical ERC-20 ABT -> OCAP Native ABT 1:1 Deposit
|
|
192
|
-
function depositForNativeAbt(string calldata recipientDid, uint256 amount) external {
|
|
193
|
-
require(!paused, "BRIDGE_PAUSED");
|
|
194
|
-
require(amount > 0 && bytes(recipientDid).length > 0, "INVALID_DEPOSIT");
|
|
195
|
-
cumulativeDepositedAbt += amount;
|
|
196
|
-
require(IERC20Minimal(canonicalAbtToken).transferFrom(msg.sender, address(this), amount), "TRANSFER_FAILED");
|
|
197
|
-
emit NativeAbtDepositLocked(msg.sender, recipientDid, amount, cumulativeDepositedAbt);
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// Track 2B (Primary — Zero-Rollup-Block EIP-712 Pull Mode):
|
|
201
|
-
// Direct Threshold-Signed Withdraw Voucher (User-Pays-Claim-Gas, 0 RollupBlock / 0 Operator ETH Gas)
|
|
202
|
-
function claimWithdrawWithDirectVoucher(
|
|
203
|
-
bytes32 ocapTxHash,
|
|
204
|
-
address to,
|
|
205
|
-
uint256 amount,
|
|
206
|
-
uint256 expiresAt,
|
|
207
|
-
bytes32 voucherDigest,
|
|
208
|
-
uint8[] calldata v,
|
|
209
|
-
bytes32[] calldata r,
|
|
210
|
-
bytes32[] calldata s
|
|
211
|
-
) external {
|
|
212
|
-
require(!paused, "BRIDGE_PAUSED");
|
|
213
|
-
require(!claimedWithdrawTxs[ocapTxHash] && !cancelledWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED_OR_CANCELLED");
|
|
214
|
-
require(to != address(0) && amount > 0, "INVALID_RECIPIENT_OR_AMOUNT");
|
|
215
|
-
require(block.timestamp <= expiresAt, "VOUCHER_EXPIRED");
|
|
216
|
-
require(cumulativeWithdrawnAbt + amount <= cumulativeDepositedAbt, "CANARY_RESERVE_WATERMARK_EXCEEDED");
|
|
217
|
-
|
|
218
|
-
bytes32 structHash = keccak256(
|
|
219
|
-
abi.encode(DIRECT_WITHDRAW_TYPEHASH, bridgeIdHash, ocapTxHash, to, amount, expiresAt)
|
|
220
|
-
);
|
|
221
|
-
bytes32 expectedDigest = keccak256(abi.encodePacked("\\x19\\x01", DOMAIN_SEPARATOR, structHash));
|
|
222
|
-
require(voucherDigest == expectedDigest, "INVALID_EIP712_VOUCHER_DIGEST");
|
|
223
|
-
_verifyValidatorQuorum(voucherDigest, v, r, s);
|
|
224
|
-
|
|
225
|
-
if (amount >= largeWithdrawThreshold) {
|
|
226
|
-
uint256 unlockAt = timelockUnlockAt[ocapTxHash];
|
|
227
|
-
if (unlockAt == 0) {
|
|
228
|
-
timelockUnlockAt[ocapTxHash] = block.timestamp + TIMELOCK_DELAY;
|
|
229
|
-
emit LargeWithdrawTimelocked(ocapTxHash, to, amount, timelockUnlockAt[ocapTxHash]);
|
|
230
|
-
return;
|
|
231
|
-
}
|
|
232
|
-
require(block.timestamp >= unlockAt, "TIMELOCK_ACTIVE");
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
uint256 currentDay = block.timestamp / 1 days;
|
|
236
|
-
require(dailyWithdrawnAbt[currentDay] + amount <= maxDailyWithdrawCap, "DAILY_WITHDRAW_CAP_EXCEEDED");
|
|
237
|
-
dailyWithdrawnAbt[currentDay] += amount;
|
|
238
|
-
|
|
239
|
-
claimedWithdrawTxs[ocapTxHash] = true;
|
|
240
|
-
cumulativeWithdrawnAbt += amount;
|
|
241
|
-
require(IERC20Minimal(canonicalAbtToken).transfer(to, amount), "TRANSFER_FAILED");
|
|
242
|
-
emit NativeAbtWithdrawClaimed(ocapTxHash, to, amount, 0);
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
// Track 2B (Legacy Compatibility): Submit Rollup Merkle Block & Claim with Merkle Proof
|
|
246
|
-
function submitRollupBlock(
|
|
247
|
-
uint256 height,
|
|
248
|
-
bytes32 previousHash,
|
|
249
|
-
bytes32 merkleRoot,
|
|
250
|
-
bytes32 txsHash,
|
|
251
|
-
uint8[] calldata v,
|
|
252
|
-
bytes32[] calldata r,
|
|
253
|
-
bytes32[] calldata s
|
|
254
|
-
) external {
|
|
255
|
-
require(!paused, "BRIDGE_PAUSED");
|
|
256
|
-
require(height == latestBlockHeight + 1, "INVALID_HEIGHT");
|
|
257
|
-
require(previousHash == latestBlockHash, "INVALID_PREVIOUS_HASH");
|
|
258
|
-
bytes32 blockHash = keccak256(abi.encodePacked(height, previousHash, merkleRoot, txsHash));
|
|
259
|
-
_verifyValidatorQuorum(blockHash, v, r, s);
|
|
260
|
-
|
|
261
|
-
latestBlockHeight = height;
|
|
262
|
-
latestBlockHash = blockHash;
|
|
263
|
-
blockMerkleRoots[height] = merkleRoot;
|
|
264
|
-
emit RollupBlockSubmitted(height, previousHash, merkleRoot, txsHash, blockHash);
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
function claimWithdrawWithMerkleProof(
|
|
268
|
-
bytes32 ocapTxHash,
|
|
269
|
-
address to,
|
|
270
|
-
uint256 amount,
|
|
271
|
-
uint256 blockHeight,
|
|
272
|
-
bytes32[] calldata proof
|
|
273
|
-
) external {
|
|
274
|
-
require(!paused, "BRIDGE_PAUSED");
|
|
275
|
-
require(!claimedWithdrawTxs[ocapTxHash] && !cancelledWithdrawTxs[ocapTxHash], "ALREADY_CLAIMED_OR_CANCELLED");
|
|
276
|
-
require(to != address(0) && amount > 0, "INVALID_RECIPIENT_OR_AMOUNT");
|
|
277
|
-
require(cumulativeWithdrawnAbt + amount <= cumulativeDepositedAbt, "CANARY_RESERVE_WATERMARK_EXCEEDED");
|
|
278
|
-
|
|
279
|
-
bytes32 root = blockMerkleRoots[blockHeight];
|
|
280
|
-
require(root != bytes32(0) && root != bytes32(type(uint256).max), "INVALID_BLOCK_ROOT");
|
|
281
|
-
bytes32 leaf = keccak256(abi.encodePacked(ocapTxHash, to, amount));
|
|
282
|
-
require(_verifyMerkleProof(proof, root, leaf), "INVALID_MERKLE_PROOF");
|
|
283
|
-
|
|
284
|
-
if (amount >= largeWithdrawThreshold) {
|
|
285
|
-
uint256 unlockAt = timelockUnlockAt[ocapTxHash];
|
|
286
|
-
if (unlockAt == 0) {
|
|
287
|
-
timelockUnlockAt[ocapTxHash] = block.timestamp + TIMELOCK_DELAY;
|
|
288
|
-
emit LargeWithdrawTimelocked(ocapTxHash, to, amount, timelockUnlockAt[ocapTxHash]);
|
|
289
|
-
return;
|
|
290
|
-
}
|
|
291
|
-
require(block.timestamp >= unlockAt, "TIMELOCK_ACTIVE");
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
uint256 currentDay = block.timestamp / 1 days;
|
|
295
|
-
require(dailyWithdrawnAbt[currentDay] + amount <= maxDailyWithdrawCap, "DAILY_WITHDRAW_CAP_EXCEEDED");
|
|
296
|
-
dailyWithdrawnAbt[currentDay] += amount;
|
|
297
|
-
|
|
298
|
-
claimedWithdrawTxs[ocapTxHash] = true;
|
|
299
|
-
cumulativeWithdrawnAbt += amount;
|
|
300
|
-
require(IERC20Minimal(canonicalAbtToken).transfer(to, amount), "TRANSFER_FAILED");
|
|
301
|
-
emit NativeAbtWithdrawClaimed(ocapTxHash, to, amount, blockHeight);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
function _verifyValidatorQuorum(
|
|
305
|
-
bytes32 digest,
|
|
306
|
-
uint8[] calldata v,
|
|
307
|
-
bytes32[] calldata r,
|
|
308
|
-
bytes32[] calldata s
|
|
309
|
-
) internal view {
|
|
310
|
-
require(v.length >= minValidatorSignatures && v.length == r.length && v.length == s.length, "QUORUM_NOT_MET");
|
|
311
|
-
address lastSigner = address(0);
|
|
312
|
-
for (uint256 i = 0; i < v.length; i++) {
|
|
313
|
-
address signer = ecrecover(digest, v[i], r[i], s[i]);
|
|
314
|
-
require(signer > lastSigner && isBridgeValidator[signer], "INVALID_OR_UNSORTED_SIGNER");
|
|
315
|
-
lastSigner = signer;
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
function _verifyMerkleProof(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
|
|
320
|
-
bytes32 computedHash = leaf;
|
|
321
|
-
for (uint256 i = 0; i < proof.length; i++) {
|
|
322
|
-
bytes32 proofElement = proof[i];
|
|
323
|
-
if (computedHash <= proofElement) {
|
|
324
|
-
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
|
|
325
|
-
} else {
|
|
326
|
-
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
return computedHash == root;
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
`;
|
|
333
|
-
function assertCleanString(value, label) {
|
|
334
|
-
if (typeof value !== "string" || value.trim().length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a non-empty string`);
|
|
335
|
-
const trimmed = value.trim();
|
|
336
|
-
if (trimmed !== value || /[\s/\\?#%]|::|->/.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} contains invalid characters`);
|
|
337
|
-
return trimmed;
|
|
338
|
-
}
|
|
339
|
-
function assertBytes32Hex(value, label) {
|
|
340
|
-
if (typeof value !== "string" || !BYTES32_HEX_REGEX.test(value)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a 32-byte 0x-prefixed hex string`);
|
|
341
|
-
return value.toLowerCase();
|
|
342
|
-
}
|
|
343
|
-
function assertEvmAddress(value, label) {
|
|
344
|
-
if (typeof value !== "string" || !EVM_ADDRESS_REGEX.test(value)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a 20-byte 0x-prefixed EVM address`);
|
|
345
|
-
const normalized = value.toLowerCase();
|
|
346
|
-
if (normalized === ZERO_EVM_ADDRESS) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: ${label} cannot be the zero address`);
|
|
347
|
-
return normalized;
|
|
348
|
-
}
|
|
349
|
-
function uint256ToHex64(value) {
|
|
350
|
-
const big = typeof value === "number" ? BigInt(value) : value;
|
|
351
|
-
if (big < 0n || big >= 1n << 256n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: uint256 out of range");
|
|
352
|
-
return big.toString(16).padStart(64, "0");
|
|
353
|
-
}
|
|
354
|
-
function parseStrictUint256JsonValue(value, label) {
|
|
355
|
-
if (typeof value === "bigint") {
|
|
356
|
-
if (value < 0n || value >= 1n << 256n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} out of uint256 range`);
|
|
357
|
-
return value;
|
|
358
|
-
}
|
|
359
|
-
if (typeof value === "string" && CANONICAL_UINT256_DECIMAL_REGEX.test(value)) {
|
|
360
|
-
const big = BigInt(value);
|
|
361
|
-
if (big < 0n || big >= 1n << 256n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} out of uint256 range`);
|
|
362
|
-
return big;
|
|
363
|
-
}
|
|
364
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} must be a canonical base-10 uint256 string`);
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* Computes the `@ocap/merkle-tree` compatible packed withdraw leaf preimage:
|
|
368
|
-
* `encodePacked(bytes32 txHash, address to, uint256 amount)`
|
|
369
|
-
*/
|
|
370
|
-
function encodeEvmBridgeWithdrawPackedPreimage(txHash, toEvmAddress, amount) {
|
|
371
|
-
return `0x${assertBytes32Hex(txHash, "txHash").slice(2)}${assertEvmAddress(toEvmAddress, "toEvmAddress").slice(2)}${uint256ToHex64(amount)}`;
|
|
372
|
-
}
|
|
373
|
-
/**
|
|
374
|
-
* Computes the `@ocap/merkle-tree` leaf hash (`keccak256(encodePacked(bytes32, address, uint256))`).
|
|
375
|
-
*/
|
|
376
|
-
function computeEvmBridgeWithdrawLeafHash(txHash, toEvmAddress, amount) {
|
|
377
|
-
return keccak256(encodeEvmBridgeWithdrawPackedPreimage(txHash, toEvmAddress, amount)).toLowerCase();
|
|
378
|
-
}
|
|
379
|
-
/**
|
|
380
|
-
* Computes the `@ocap/merkle-tree` compatible `getListHash(txHashes)`.
|
|
381
|
-
*/
|
|
382
|
-
function computeEvmBridgeTxsHash(txHashes) {
|
|
383
|
-
if (txHashes.length === 0) return ZERO_BYTES32_HASH;
|
|
384
|
-
return keccak256(`0x${txHashes.map((h) => assertBytes32Hex(h, "txHash").slice(2)).join("")}`).toLowerCase();
|
|
385
|
-
}
|
|
386
|
-
/**
|
|
387
|
-
* Computes the `@ocap/merkle-tree` compatible `getBlockHash`:
|
|
388
|
-
* `keccak256(encodePacked(uint256 height, bytes32 previousHash, bytes32 merkleRoot, bytes32 txsHash))`
|
|
389
|
-
*/
|
|
390
|
-
function computeEvmBridgeBlockHash(block) {
|
|
391
|
-
if (!Number.isSafeInteger(block.height) || block.height <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: block height must be a positive safe integer");
|
|
392
|
-
return keccak256(`0x${uint256ToHex64(block.height)}${assertBytes32Hex(block.previousHash, "previousHash").slice(2)}${assertBytes32Hex(block.merkleRoot, "merkleRoot").slice(2)}${assertBytes32Hex(block.txsHash, "txsHash").slice(2)}`).toLowerCase();
|
|
393
|
-
}
|
|
394
|
-
/**
|
|
395
|
-
* Deterministic sorted-pair Keccak-256 Merkle tree compatible with `@ocap/merkle-tree` and OpenZeppelin `MerkleProof`.
|
|
396
|
-
*/
|
|
397
|
-
function buildEvmBridgeMerkleTree(withdrawTxs) {
|
|
398
|
-
if (withdrawTxs.length === 0) return {
|
|
399
|
-
merkleRoot: EMPTY_ROLLUP_MERKLE_ROOT,
|
|
400
|
-
leaves: [],
|
|
401
|
-
getProofForLeaf: () => []
|
|
402
|
-
};
|
|
403
|
-
const rawLeafBuffers = withdrawTxs.map((tx) => Buffer.from(computeEvmBridgeWithdrawLeafHash(tx.ocapTxHash, tx.recipientEvmAddress, tx.amount).slice(2), "hex"));
|
|
404
|
-
rawLeafBuffers.sort(Buffer.compare);
|
|
405
|
-
const uniqueLeaves = rawLeafBuffers.filter((el, idx) => idx === 0 || !rawLeafBuffers[idx - 1].equals(el));
|
|
406
|
-
const layers = [uniqueLeaves];
|
|
407
|
-
while (layers[layers.length - 1].length > 1) {
|
|
408
|
-
const current = layers[layers.length - 1];
|
|
409
|
-
const nextLayer = [];
|
|
410
|
-
for (let i = 0; i < current.length; i += 2) {
|
|
411
|
-
const left = current[i];
|
|
412
|
-
const right = current[i + 1];
|
|
413
|
-
if (!right) nextLayer.push(left);
|
|
414
|
-
else {
|
|
415
|
-
const parentHex = keccak256(`0x${Buffer.concat([left, right].sort(Buffer.compare)).toString("hex")}`).slice(2);
|
|
416
|
-
nextLayer.push(Buffer.from(parentHex, "hex"));
|
|
417
|
-
}
|
|
418
|
-
}
|
|
419
|
-
layers.push(nextLayer);
|
|
420
|
-
}
|
|
421
|
-
const merkleRoot = `0x${layers[layers.length - 1][0].toString("hex").toLowerCase()}`;
|
|
422
|
-
const leaves = uniqueLeaves.map((b) => `0x${b.toString("hex").toLowerCase()}`);
|
|
423
|
-
const getProofForLeaf = (leafHash) => {
|
|
424
|
-
const targetBuf = Buffer.from(assertBytes32Hex(leafHash, "leafHash").slice(2), "hex");
|
|
425
|
-
let idx = uniqueLeaves.findIndex((b) => b.equals(targetBuf));
|
|
426
|
-
if (idx === -1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: leaf ${leafHash} not found in Merkle tree`);
|
|
427
|
-
const proof = [];
|
|
428
|
-
for (const layer of layers) {
|
|
429
|
-
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1;
|
|
430
|
-
if (pairIdx < layer.length) proof.push(`0x${layer[pairIdx].toString("hex").toLowerCase()}`);
|
|
431
|
-
idx = Math.floor(idx / 2);
|
|
432
|
-
}
|
|
433
|
-
return proof;
|
|
434
|
-
};
|
|
435
|
-
return {
|
|
436
|
-
merkleRoot,
|
|
437
|
-
leaves,
|
|
438
|
-
getProofForLeaf
|
|
439
|
-
};
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Verifies a sorted-pair Keccak-256 Merkle proof against `merkleRoot`.
|
|
443
|
-
*/
|
|
444
|
-
function verifyEvmBridgeMerkleProof(proof, merkleRoot, leafHash) {
|
|
445
|
-
if (!Array.isArray(proof) || !BYTES32_HEX_REGEX.test(merkleRoot) || !BYTES32_HEX_REGEX.test(leafHash)) return false;
|
|
446
|
-
if (merkleRoot.toLowerCase() === EMPTY_ROLLUP_MERKLE_ROOT) return false;
|
|
447
|
-
let computed = Buffer.from(leafHash.slice(2).toLowerCase(), "hex");
|
|
448
|
-
for (const p of proof) {
|
|
449
|
-
if (typeof p !== "string" || !BYTES32_HEX_REGEX.test(p)) return false;
|
|
450
|
-
const sibling = Buffer.from(p.slice(2).toLowerCase(), "hex");
|
|
451
|
-
const parentHex = keccak256(`0x${Buffer.concat([computed, sibling].sort(Buffer.compare)).toString("hex")}`).slice(2);
|
|
452
|
-
computed = Buffer.from(parentHex, "hex");
|
|
453
|
-
}
|
|
454
|
-
return `0x${computed.toString("hex").toLowerCase()}` === merkleRoot.toLowerCase();
|
|
455
|
-
}
|
|
456
|
-
/**
|
|
457
|
-
* Computes the expected validator signature digest for a Rollup block.
|
|
458
|
-
*/
|
|
459
|
-
function computeValidatorBlockSignatureDigest(bridgeId, rollupAddress, blockHash, validatorDid) {
|
|
460
|
-
const payload = `ocap:evm-simplified-bridge:v1:${bridgeId}:${rollupAddress}:${blockHash.toLowerCase()}:${validatorDid}`;
|
|
461
|
-
return keccak256(`0x${Buffer.from(payload, "utf8").toString("hex")}`).toLowerCase();
|
|
462
|
-
}
|
|
463
|
-
function utf8Keccak256Hex(text) {
|
|
464
|
-
return keccak256(`0x${Buffer.from(text, "utf8").toString("hex")}`).toLowerCase();
|
|
465
|
-
}
|
|
466
|
-
const EIP712_DOMAIN_TYPEHASH = utf8Keccak256Hex("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
|
|
467
|
-
const DIRECT_WITHDRAW_TYPEHASH = utf8Keccak256Hex("DirectWithdrawVoucher(bytes32 bridgeIdHash,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 expiresAt)");
|
|
468
|
-
/**
|
|
469
|
-
* Computes the standard EIP-712 `DOMAIN_SEPARATOR` matching `ArcEvmBridgeGateway.sol`:
|
|
470
|
-
* `keccak256(abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), chainId, verifyingContract))`
|
|
471
|
-
*/
|
|
472
|
-
function computeEip712BridgeDomainSeparator(params) {
|
|
473
|
-
const name = params.name ?? EIP712_BRIDGE_DOMAIN_NAME;
|
|
474
|
-
const version = params.version ?? EIP712_BRIDGE_DOMAIN_VERSION;
|
|
475
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
476
|
-
const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
|
|
477
|
-
const nameHashHex = utf8Keccak256Hex(name).slice(2);
|
|
478
|
-
const versionHashHex = utf8Keccak256Hex(version).slice(2);
|
|
479
|
-
const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
|
|
480
|
-
const contractWordHex64 = verifyingContractAddress.slice(2).padStart(64, "0");
|
|
481
|
-
return keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHashHex}${versionHashHex}${chainIdHex64}${contractWordHex64}`).toLowerCase();
|
|
482
|
-
}
|
|
483
|
-
/**
|
|
484
|
-
* Computes the standard EIP-712 `structHash` for `DirectWithdrawVoucher` matching `ArcEvmBridgeGateway.sol`:
|
|
485
|
-
* `keccak256(abi.encode(DIRECT_WITHDRAW_TYPEHASH, keccak256(bytes(bridgeId)), ocapTxHash, recipient, amount, expiresAt))`
|
|
486
|
-
*/
|
|
487
|
-
function computeEip712WithdrawStructHash(params) {
|
|
488
|
-
const bridgeId = assertCleanString(params.bridgeId, "bridgeId");
|
|
489
|
-
const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
490
|
-
if (ocapTxHash === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
|
|
491
|
-
const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
|
|
492
|
-
if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: voucher amount must be > 0n");
|
|
493
|
-
if (!Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: expiresAtUnixSeconds must be a positive integer");
|
|
494
|
-
const bridgeIdHashHex = utf8Keccak256Hex(bridgeId).slice(2);
|
|
495
|
-
const recipientWordHex64 = recipientEvmAddress.slice(2).padStart(64, "0");
|
|
496
|
-
const amountHex64 = uint256ToHex64(params.amount);
|
|
497
|
-
const expiresHex64 = uint256ToHex64(params.expiresAtUnixSeconds);
|
|
498
|
-
return keccak256(`0x${DIRECT_WITHDRAW_TYPEHASH.slice(2)}${bridgeIdHashHex}${ocapTxHash.slice(2)}${recipientWordHex64}${amountHex64}${expiresHex64}`).toLowerCase();
|
|
499
|
-
}
|
|
500
|
-
/**
|
|
501
|
-
* Computes the deterministic EIP-712 Zero-Rollup-Block Direct Withdraw Voucher Digest (`\x19\x01 || DOMAIN_SEPARATOR || structHash`):
|
|
502
|
-
* binds `(bridgeId, evmChainId, verifyingContractAddress, ocapTxHash, recipientEvmAddress, amount, expiresAtUnixSeconds)`
|
|
503
|
-
* so the withdrawing user can claim ERC-20 ABT directly on Ethereum/Base (`claimWithdrawWithDirectVoucher`)
|
|
504
|
-
* without waiting for any RollupBlock batch or operator-paid Ethereum transactions.
|
|
505
|
-
*/
|
|
506
|
-
function computeDirectWithdrawVoucherDigest(params) {
|
|
507
|
-
const domainSeparator = computeEip712BridgeDomainSeparator({
|
|
508
|
-
evmChainId: params.evmChainId,
|
|
509
|
-
verifyingContractAddress: params.verifyingContractAddress
|
|
510
|
-
});
|
|
511
|
-
const structHash = computeEip712WithdrawStructHash({
|
|
512
|
-
bridgeId: params.bridgeId,
|
|
513
|
-
ocapTxHash: params.ocapTxHash,
|
|
514
|
-
recipientEvmAddress: params.recipientEvmAddress,
|
|
515
|
-
amount: params.amount,
|
|
516
|
-
expiresAtUnixSeconds: params.expiresAtUnixSeconds
|
|
517
|
-
});
|
|
518
|
-
return keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
|
|
519
|
-
}
|
|
520
|
-
/**
|
|
521
|
-
* Computes the expected validator signature digest for a Zero-Rollup-Block Direct Withdraw Voucher.
|
|
522
|
-
*/
|
|
523
|
-
function computeValidatorVoucherSignatureDigest(bridgeId, voucherDigest, validatorDid) {
|
|
524
|
-
const payload = `ocap:evm-direct-withdraw-sig:v1:${assertCleanString(bridgeId, "bridgeId")}:${assertBytes32Hex(voucherDigest, "voucherDigest")}:${assertCleanString(validatorDid, "validatorDid")}`;
|
|
525
|
-
return keccak256(`0x${Buffer.from(payload, "utf8").toString("hex")}`).toLowerCase();
|
|
526
|
-
}
|
|
527
|
-
/**
|
|
528
|
-
* Verifies a `DirectWithdrawVoucher` against the bridge EIP-712 domain, validator set, and quorum threshold.
|
|
529
|
-
*/
|
|
530
|
-
function verifyDirectWithdrawVoucher(voucher, options) {
|
|
531
|
-
try {
|
|
532
|
-
if (!voucher || typeof voucher !== "object" || voucher.cancelled === true) return false;
|
|
533
|
-
if (!Number.isSafeInteger(options.minValidatorSignatures) || options.minValidatorSignatures < 1 || options.minValidatorSignatures > options.validatorDids.length) return false;
|
|
534
|
-
if (voucher.bridgeId !== options.bridgeId) return false;
|
|
535
|
-
const expectedVerifyingContract = assertEvmAddress(options.verifyingContractAddress ?? voucher.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
|
|
536
|
-
if (voucher.verifyingContractAddress && voucher.verifyingContractAddress.toLowerCase() !== expectedVerifyingContract) return false;
|
|
537
|
-
assertCleanString(voucher.fromDid, "fromDid");
|
|
538
|
-
if (!options.allowedEvmChainIds.includes(voucher.evmChainId)) return false;
|
|
539
|
-
if (!Number.isSafeInteger(voucher.issuedAtUnixSeconds) || voucher.issuedAtUnixSeconds <= 0 || !Number.isSafeInteger(voucher.expiresAtUnixSeconds)) return false;
|
|
540
|
-
const ttl = voucher.expiresAtUnixSeconds - voucher.issuedAtUnixSeconds;
|
|
541
|
-
if (ttl < MIN_DIRECT_VOUCHER_TTL_SECONDS || ttl > MAX_DIRECT_VOUCHER_TTL_SECONDS) return false;
|
|
542
|
-
if (options.nowUnixSeconds !== void 0 && options.nowUnixSeconds > voucher.expiresAtUnixSeconds) return false;
|
|
543
|
-
if (!Array.isArray(voucher.validatorSignatures) || !Array.isArray(voucher.validatorSigners) || voucher.validatorSigners.length !== voucher.validatorSignatures.length) return false;
|
|
544
|
-
const expectedDomainSeparator = computeEip712BridgeDomainSeparator({
|
|
545
|
-
evmChainId: voucher.evmChainId,
|
|
546
|
-
verifyingContractAddress: expectedVerifyingContract
|
|
547
|
-
});
|
|
548
|
-
const expectedStructHash = computeEip712WithdrawStructHash({
|
|
549
|
-
bridgeId: voucher.bridgeId,
|
|
550
|
-
ocapTxHash: voucher.ocapTxHash,
|
|
551
|
-
recipientEvmAddress: voucher.recipientEvmAddress,
|
|
552
|
-
amount: voucher.amount,
|
|
553
|
-
expiresAtUnixSeconds: voucher.expiresAtUnixSeconds
|
|
554
|
-
});
|
|
555
|
-
const expectedDigest = keccak256(`0x1901${expectedDomainSeparator.slice(2)}${expectedStructHash.slice(2)}`).toLowerCase();
|
|
556
|
-
if (voucher.voucherDigest.toLowerCase() !== expectedDigest) return false;
|
|
557
|
-
if (voucher.eip712DomainSeparator && voucher.eip712DomainSeparator.toLowerCase() !== expectedDomainSeparator) return false;
|
|
558
|
-
if (voucher.eip712StructHash && voucher.eip712StructHash.toLowerCase() !== expectedStructHash) return false;
|
|
559
|
-
const validatorSet = new Set(options.validatorDids);
|
|
560
|
-
const seen = /* @__PURE__ */ new Set();
|
|
561
|
-
for (let i = 0; i < voucher.validatorSignatures.length; i++) {
|
|
562
|
-
const sig = voucher.validatorSignatures[i];
|
|
563
|
-
if (!sig || voucher.validatorSigners[i] !== sig.validatorDid) return false;
|
|
564
|
-
if (!validatorSet.has(sig.validatorDid) || seen.has(sig.validatorDid)) return false;
|
|
565
|
-
const expectedSig = computeValidatorVoucherSignatureDigest(voucher.bridgeId, expectedDigest, sig.validatorDid);
|
|
566
|
-
if (sig.signatureDigest.toLowerCase() !== expectedSig) return false;
|
|
567
|
-
seen.add(sig.validatorDid);
|
|
568
|
-
}
|
|
569
|
-
return seen.size >= options.minValidatorSignatures;
|
|
570
|
-
} catch {
|
|
571
|
-
return false;
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
const DEPRECATED_ROLLUP_PROTOCOL_SET = new Set(DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS);
|
|
575
|
-
function normalizeRollupProtocolTypeUrl(rawTypeUrl) {
|
|
576
|
-
if (typeof rawTypeUrl !== "string") return "";
|
|
577
|
-
const trimmed = rawTypeUrl.trim();
|
|
578
|
-
if (!trimmed) return "";
|
|
579
|
-
const snakeCased = trimmed.replace(/^(?:type\.googleapis\.com\/)?(?:forge_abi\.)?(?:fg:t:|fg:x:tx:)?/i, "").replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/_tx$/, "");
|
|
580
|
-
if (!snakeCased) return "";
|
|
581
|
-
return `fg:t:${snakeCased}`;
|
|
582
|
-
}
|
|
583
|
-
/**
|
|
584
|
-
* Issue #1245:
|
|
585
|
-
* Returns true if `typeUrl` belongs to the 8 deprecated Rollup write protocols
|
|
586
|
-
* (`create_rollup`, `update_rollup`, `join_rollup`, `leave_rollup`, `create_rollup_block`,
|
|
587
|
-
* `claim_block_reward`, `pause_rollup`, `resume_rollup`).
|
|
588
|
-
* Normalizes case, whitespace, camelCase/PascalCase, protobuf type URLs, and bare protocol names (`RT-1245-3`).
|
|
589
|
-
*/
|
|
590
|
-
function isDeprecatedRollupWriteProtocol(typeUrl) {
|
|
591
|
-
const normalized = normalizeRollupProtocolTypeUrl(typeUrl);
|
|
592
|
-
return DEPRECATED_ROLLUP_PROTOCOL_SET.has(normalized);
|
|
593
|
-
}
|
|
594
|
-
/**
|
|
595
|
-
* Issue #1245:
|
|
596
|
-
* Sunset guard for active transaction pipeline execution:
|
|
597
|
-
* - Blocks all 8 deprecated Rollup write protocols when `currentBlockHeight >= rollupSunsetActivationHeight`.
|
|
598
|
-
* - Allows historical block replay when `currentBlockHeight < rollupSunsetActivationHeight`.
|
|
599
|
-
*/
|
|
600
|
-
function assertRollupProtocolNotSunset(params) {
|
|
601
|
-
if (!params || typeof params !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: sunset guard params must be an object");
|
|
602
|
-
if (typeof params.typeUrl !== "string" || params.typeUrl.trim().length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: typeUrl must be a non-empty string");
|
|
603
|
-
if (!Number.isSafeInteger(params.currentBlockHeight) || params.currentBlockHeight < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: currentBlockHeight must be a non-negative safe integer");
|
|
604
|
-
const activationHeight = params.rollupSunsetActivationHeight ?? DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT;
|
|
605
|
-
if (!Number.isSafeInteger(activationHeight) || activationHeight < 1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: rollupSunsetActivationHeight must be a positive safe integer (>= 1)");
|
|
606
|
-
if (isDeprecatedRollupWriteProtocol(params.typeUrl)) {
|
|
607
|
-
if (params.currentBlockHeight >= activationHeight) {
|
|
608
|
-
const canonicalTypeUrl = normalizeRollupProtocolTypeUrl(params.typeUrl);
|
|
609
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy Rollup write protocol ${canonicalTypeUrl} is deprecated and disabled at block height ${params.currentBlockHeight} (>= sunset height ${activationHeight}); use Zero-Rollup-Block EIP-712 DirectWithdrawVoucher instead`);
|
|
610
|
-
}
|
|
611
|
-
return;
|
|
612
|
-
}
|
|
613
|
-
assertCleanString(params.typeUrl, "typeUrl");
|
|
614
|
-
}
|
|
615
|
-
/**
|
|
616
|
-
* Issue #1245:
|
|
617
|
-
* Strictly read-only historical parser for legacy `RollupState`, `RollupBlock`, `deposit_token_v2`,
|
|
618
|
-
* and `withdraw_token_v2` records so block explorers, indexers, and audit tools can inspect historical
|
|
619
|
-
* chain data after the active Rollup write protocols are removed.
|
|
620
|
-
*/
|
|
621
|
-
function parseLegacyRollupReadOnlyRecord(rawRecord) {
|
|
622
|
-
if (!rawRecord || typeof rawRecord !== "object" || Array.isArray(rawRecord)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy Rollup record must be a plain object");
|
|
623
|
-
if (Object.prototype.hasOwnProperty.call(rawRecord, "__proto__") || Object.prototype.hasOwnProperty.call(rawRecord, "constructor") || Object.prototype.hasOwnProperty.call(rawRecord, "prototype")) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: prototype pollution keys rejected in legacy Rollup record");
|
|
624
|
-
const rawKind = String(rawRecord.recordKind ?? rawRecord.typeUrl ?? "").trim();
|
|
625
|
-
const normalizedKind = rawKind.startsWith("fg:t:") ? rawKind.slice(5) : rawKind;
|
|
626
|
-
if (normalizedKind === "RollupState") {
|
|
627
|
-
const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.address ?? ""), "rollupAddress");
|
|
628
|
-
const tokenAddress = assertCleanString(String(rawRecord.tokenAddress ?? ""), "tokenAddress");
|
|
629
|
-
const rawValidators = Array.isArray(rawRecord.validatorDids ?? rawRecord.validators) ? rawRecord.validatorDids ?? rawRecord.validators : [];
|
|
630
|
-
if (rawValidators.length > 64) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupState validator list too large");
|
|
631
|
-
const validatorDids = Object.freeze(rawValidators.map((v) => assertCleanString(String(v ?? ""), "validatorDid")));
|
|
632
|
-
const latestHeight = rawRecord.blockHeight !== void 0 ? Number(rawRecord.blockHeight) : Number(rawRecord.latestBlockHeight ?? 0);
|
|
633
|
-
if (!Number.isSafeInteger(latestHeight) || latestHeight < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid legacy RollupState blockHeight");
|
|
634
|
-
return Object.freeze({
|
|
635
|
-
recordKind: "RollupState",
|
|
636
|
-
mode: "READ_ONLY_LEGACY_ARCHIVE",
|
|
637
|
-
rollupAddress,
|
|
638
|
-
tokenAddress,
|
|
639
|
-
blockHeight: latestHeight,
|
|
640
|
-
validatorDids
|
|
641
|
-
});
|
|
642
|
-
}
|
|
643
|
-
if (normalizedKind === "RollupBlock" || normalizedKind === "create_rollup_block") {
|
|
644
|
-
const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.rollup ?? ""), "rollupAddress");
|
|
645
|
-
const blockHeight = Number(rawRecord.blockHeight ?? rawRecord.height);
|
|
646
|
-
if (!Number.isSafeInteger(blockHeight) || blockHeight <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupBlock height must be >= 1");
|
|
647
|
-
const previousHash = rawRecord.previousHash ? assertBytes32Hex(String(rawRecord.previousHash), "previousHash") : ZERO_BYTES32_HASH;
|
|
648
|
-
const merkleRoot = assertBytes32Hex(String(rawRecord.merkleRoot ?? ""), "merkleRoot");
|
|
649
|
-
const hasExplicitTxArray = rawRecord.txHashes !== void 0 || rawRecord.txs !== void 0;
|
|
650
|
-
const rawTxs = Array.isArray(rawRecord.txHashes ?? rawRecord.txs) ? rawRecord.txHashes ?? rawRecord.txs : [];
|
|
651
|
-
if (rawTxs.length > DEFAULT_MAX_ROLLUP_BLOCK_SIZE) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy RollupBlock txHashes exceeds max size");
|
|
652
|
-
const txHashes = Object.freeze(rawTxs.map((h) => assertBytes32Hex(String(h ?? ""), "txHash")));
|
|
653
|
-
const computedTxsHash = computeEvmBridgeTxsHash([...txHashes]);
|
|
654
|
-
const txsHash = rawRecord.txsHash ? assertBytes32Hex(String(rawRecord.txsHash), "txsHash") : computedTxsHash;
|
|
655
|
-
if (rawRecord.txsHash && hasExplicitTxArray && txsHash !== computedTxsHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy RollupBlock #${blockHeight} txsHash mismatch against txHashes`);
|
|
656
|
-
const computedBlockHash = computeEvmBridgeBlockHash({
|
|
657
|
-
height: blockHeight,
|
|
658
|
-
previousHash,
|
|
659
|
-
merkleRoot,
|
|
660
|
-
txsHash
|
|
661
|
-
});
|
|
662
|
-
const blockHash = rawRecord.blockHash ? assertBytes32Hex(String(rawRecord.blockHash), "blockHash") : computedBlockHash;
|
|
663
|
-
if (blockHash !== computedBlockHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: legacy RollupBlock #${blockHeight} blockHash mismatch`);
|
|
664
|
-
const proposerDid = rawRecord.proposerDid ? assertCleanString(String(rawRecord.proposerDid), "proposerDid") : void 0;
|
|
665
|
-
return Object.freeze({
|
|
666
|
-
recordKind: "RollupBlock",
|
|
667
|
-
mode: "READ_ONLY_LEGACY_ARCHIVE",
|
|
668
|
-
rollupAddress,
|
|
669
|
-
blockHeight,
|
|
670
|
-
previousHash,
|
|
671
|
-
merkleRoot,
|
|
672
|
-
txsHash,
|
|
673
|
-
blockHash,
|
|
674
|
-
txHashes,
|
|
675
|
-
proposerDid
|
|
676
|
-
});
|
|
677
|
-
}
|
|
678
|
-
if (normalizedKind === "deposit_token_v2" || normalizedKind === "withdraw_token_v2") {
|
|
679
|
-
const rollupAddress = assertCleanString(String(rawRecord.rollupAddress ?? rawRecord.rollup ?? ""), "rollupAddress");
|
|
680
|
-
const tokenAddress = assertCleanString(String(rawRecord.tokenAddress ?? ""), "tokenAddress");
|
|
681
|
-
const fromDid = rawRecord.fromDid ? assertCleanString(String(rawRecord.fromDid), "fromDid") : void 0;
|
|
682
|
-
const recipientAddress = assertCleanString(String(rawRecord.recipientAddress ?? rawRecord.to ?? ""), "recipientAddress");
|
|
683
|
-
const amount = parseStrictUint256JsonValue(rawRecord.amount ?? rawRecord.value, "amount");
|
|
684
|
-
if (amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: legacy transfer amount must be > 0n");
|
|
685
|
-
const evidenceHash = rawRecord.evidenceHash ? assertBytes32Hex(String(rawRecord.evidenceHash), "evidenceHash") : void 0;
|
|
686
|
-
return Object.freeze({
|
|
687
|
-
recordKind: normalizedKind,
|
|
688
|
-
mode: "READ_ONLY_LEGACY_ARCHIVE",
|
|
689
|
-
rollupAddress,
|
|
690
|
-
tokenAddress,
|
|
691
|
-
fromDid,
|
|
692
|
-
recipientAddress,
|
|
693
|
-
amount,
|
|
694
|
-
evidenceHash
|
|
695
|
-
});
|
|
696
|
-
}
|
|
697
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: unsupported legacy Rollup record kind (${rawKind || "empty"})`);
|
|
698
|
-
}
|
|
699
|
-
function computeSolidityFunctionSelector(signature) {
|
|
700
|
-
return `0x${utf8Keccak256Hex(signature).slice(2, 10)}`;
|
|
701
|
-
}
|
|
702
|
-
function encodeAbiDynamicUtf8String(value) {
|
|
703
|
-
const buf = Buffer.from(value, "utf8");
|
|
704
|
-
const lenWord = uint256ToHex64(buf.length);
|
|
705
|
-
const paddedLen = Math.ceil(buf.length / 32) * 32;
|
|
706
|
-
return `${lenWord}${buf.toString("hex").padEnd(paddedLen * 2, "0")}`;
|
|
707
|
-
}
|
|
708
|
-
function decodeAbiDynamicUtf8String(hexDataWithoutSelector, byteOffset) {
|
|
709
|
-
const charOffset = byteOffset * 2;
|
|
710
|
-
if (charOffset + 64 > hexDataWithoutSelector.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ABI dynamic string offset");
|
|
711
|
-
const strByteLen = Number(BigInt(`0x${hexDataWithoutSelector.slice(charOffset, charOffset + 64)}`));
|
|
712
|
-
const startChar = charOffset + 64;
|
|
713
|
-
const endChar = startChar + strByteLen * 2;
|
|
714
|
-
if (strByteLen < 0 || endChar > hexDataWithoutSelector.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ABI dynamic string length");
|
|
715
|
-
return Buffer.from(hexDataWithoutSelector.slice(startChar, endChar), "hex").toString("utf8");
|
|
716
|
-
}
|
|
717
|
-
/**
|
|
718
|
-
* Derives the canonical 20-byte lowercase `0x`-prefixed Ethereum address from a 32-byte `secp256k1` private key.
|
|
719
|
-
*/
|
|
720
|
-
function deriveEvmAddressFromPrivateKeyHex(privateKeyHex) {
|
|
721
|
-
const cleanPriv = assertBytes32Hex(privateKeyHex.startsWith("0x") ? privateKeyHex : `0x${privateKeyHex}`, "privateKeyHex").slice(2);
|
|
722
|
-
if (/^0+$/.test(cleanPriv)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: secp256k1 private key cannot be zero");
|
|
723
|
-
return `0x${keccak256(`0x${secp256k1Curve.keyFromPrivate(cleanPriv, "hex").getPublic(false, "hex").slice(2)}`).slice(-40).toLowerCase()}`;
|
|
724
|
-
}
|
|
725
|
-
/**
|
|
726
|
-
* Signs a 32-byte digest (`0x...`) using a real `secp256k1` private key and returns Ethereum `(v, r, s)` + `signerEvmAddress`.
|
|
727
|
-
*/
|
|
728
|
-
function signDigestWithSecp256k1PrivateKey(digestHex, privateKeyHex) {
|
|
729
|
-
const cleanDigest = assertBytes32Hex(digestHex, "digestHex").slice(2);
|
|
730
|
-
const cleanPriv = assertBytes32Hex(privateKeyHex.startsWith("0x") ? privateKeyHex : `0x${privateKeyHex}`, "privateKeyHex").slice(2);
|
|
731
|
-
const signerEvmAddress = deriveEvmAddressFromPrivateKeyHex(`0x${cleanPriv}`);
|
|
732
|
-
const sig = secp256k1Curve.keyFromPrivate(cleanPriv, "hex").sign(cleanDigest, { canonical: true });
|
|
733
|
-
return {
|
|
734
|
-
v: (sig.recoveryParam ?? 0) + 27,
|
|
735
|
-
r: `0x${sig.r.toString("hex").padStart(64, "0").toLowerCase()}`,
|
|
736
|
-
s: `0x${sig.s.toString("hex").padStart(64, "0").toLowerCase()}`,
|
|
737
|
-
signerEvmAddress
|
|
738
|
-
};
|
|
739
|
-
}
|
|
740
|
-
const SECP256K1_N = BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141");
|
|
741
|
-
const SECP256K1_HALF_N = SECP256K1_N / 2n;
|
|
742
|
-
/**
|
|
743
|
-
* Recovers the 20-byte Ethereum signer address from `(digestHex, v, r, s)` identically to OpenZeppelin `ECDSA.recover` (EIP-2 low-`s` enforced).
|
|
744
|
-
*/
|
|
745
|
-
function ecrecoverEvmAddress(digestHex, v, rHex, sHex) {
|
|
746
|
-
const cleanDigest = assertBytes32Hex(digestHex, "digestHex").slice(2);
|
|
747
|
-
if (v !== 27 && v !== 28) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: invalid ecrecover v (${v}); expected 27 or 28`);
|
|
748
|
-
const cleanR = assertBytes32Hex(rHex, "r").slice(2);
|
|
749
|
-
const cleanS = assertBytes32Hex(sHex, "s").slice(2);
|
|
750
|
-
const rBig = BigInt(`0x${cleanR}`);
|
|
751
|
-
const sBig = BigInt(`0x${cleanS}`);
|
|
752
|
-
if (rBig <= 0n || rBig >= SECP256K1_N) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid ECDSA signature r out of range");
|
|
753
|
-
if (sBig <= 0n || sBig > SECP256K1_HALF_N) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid or malleable ECDSA signature s (EIP-2 low-s required)");
|
|
754
|
-
try {
|
|
755
|
-
return `0x${keccak256(`0x${secp256k1Curve.recoverPubKey(Buffer.from(cleanDigest, "hex"), {
|
|
756
|
-
r: cleanR,
|
|
757
|
-
s: cleanS
|
|
758
|
-
}, v - 27, "hex").encode("hex", false).slice(2)}`).slice(-40).toLowerCase()}`;
|
|
759
|
-
} catch (err) {
|
|
760
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ECDSA public key recovery failed (${err instanceof Error ? err.message : String(err)})`);
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
function cloneDirectWithdrawVoucher(voucher) {
|
|
764
|
-
return {
|
|
765
|
-
...voucher,
|
|
766
|
-
validatorSigners: [...voucher.validatorSigners],
|
|
767
|
-
validatorSignatures: voucher.validatorSignatures.map((s) => ({ ...s }))
|
|
768
|
-
};
|
|
769
|
-
}
|
|
770
|
-
/**
|
|
771
|
-
* Computes the HMAC-SHA256 signature for Cloudflare Edge webhook requests.
|
|
772
|
-
*/
|
|
773
|
-
function computeEdgeWebhookHmac(secret, timestampSeconds, nonce, path, bodyJson) {
|
|
774
|
-
return (0, node_crypto.createHmac)("sha256", secret).update(`${timestampSeconds}:${nonce}:${path}:${bodyJson}`).digest("hex");
|
|
775
|
-
}
|
|
776
|
-
/**
|
|
777
|
-
* Issue #1241:
|
|
778
|
-
* Next-Gen Simplified EVM Bridge Node (`OcapSimplifiedEvmBridgeNode`).
|
|
779
|
-
* - Pure ARC-native & Cloudflare Workers / Durable Objects ready (zero native C++ addons, full snapshot import/export).
|
|
780
|
-
* - Implements Track 1 (`Pay-Where-You-Are` Direct Service Cashier) and Track 2 (`1:1 Canonical ABT Gateway`).
|
|
781
|
-
* - 100% backward-compatible with OCAP `RollupState`, `deposit_token_v2`, `withdraw_token_v2`, and `@ocap/merkle-tree`.
|
|
782
|
-
*/
|
|
783
|
-
var OcapSimplifiedEvmBridgeNode = class OcapSimplifiedEvmBridgeNode {
|
|
784
|
-
constructor(config) {
|
|
785
|
-
this.paused = false;
|
|
786
|
-
this.latestBlockHeight = 0;
|
|
787
|
-
this.cumulativeDepositedAbt = 0n;
|
|
788
|
-
this.cumulativeWithdrawnAbt = 0n;
|
|
789
|
-
this.processedEventKeys = /* @__PURE__ */ new Set();
|
|
790
|
-
this.processedServiceOrderIds = /* @__PURE__ */ new Set();
|
|
791
|
-
this.processedWithdrawTxHashes = /* @__PURE__ */ new Set();
|
|
792
|
-
this.cancelledWithdrawTxHashes = /* @__PURE__ */ new Set();
|
|
793
|
-
this.dailyWithdrawnByDay = /* @__PURE__ */ new Map();
|
|
794
|
-
this.processedWebhookNonces = /* @__PURE__ */ new Map();
|
|
795
|
-
this.pendingWithdrawQueue = [];
|
|
796
|
-
this.sealedBlocks = /* @__PURE__ */ new Map();
|
|
797
|
-
this.withdrawTxToBlockHeight = /* @__PURE__ */ new Map();
|
|
798
|
-
this.issuedDirectVouchers = /* @__PURE__ */ new Map();
|
|
799
|
-
const bridgeId = assertCleanString(config.bridgeId, "bridgeId");
|
|
800
|
-
const rollupAddress = assertCleanString(config.rollupAddress, "rollupAddress");
|
|
801
|
-
const bridgeProposerDid = assertCleanString(config.bridgeProposerDid, "bridgeProposerDid");
|
|
802
|
-
const guardianDid = assertCleanString(config.guardianDid ?? bridgeProposerDid, "guardianDid");
|
|
803
|
-
const verifyingContractAddress = assertEvmAddress(config.verifyingContractAddress ?? DEFAULT_VERIFYING_CONTRACT_ADDRESS, "verifyingContractAddress");
|
|
804
|
-
const ocapNativeAbtTokenAddress = assertCleanString(config.ocapNativeAbtTokenAddress, "ocapNativeAbtTokenAddress");
|
|
805
|
-
const canonicalErc20AbtAddress = assertEvmAddress(config.canonicalErc20AbtAddress, "canonicalErc20AbtAddress");
|
|
806
|
-
if (!Array.isArray(config.allowedEvmChainIds) || config.allowedEvmChainIds.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowedEvmChainIds must be non-empty");
|
|
807
|
-
const allowedEvmChainIds = config.allowedEvmChainIds.map((c) => assertCleanString(c, "allowedEvmChainId"));
|
|
808
|
-
if (!Array.isArray(config.allowedServicePaymentTokens) || config.allowedServicePaymentTokens.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowedServicePaymentTokens must be non-empty");
|
|
809
|
-
const allowedServicePaymentTokens = Array.from(new Set([canonicalErc20AbtAddress, ...config.allowedServicePaymentTokens.map((t) => assertEvmAddress(t, "allowedServicePaymentToken"))]));
|
|
810
|
-
const allowSingleSignerForTesting = config.allowSingleSignerForTesting === true;
|
|
811
|
-
const rawValidatorDids = config.validatorDids ?? [bridgeProposerDid];
|
|
812
|
-
if (!Array.isArray(rawValidatorDids) || rawValidatorDids.length === 0 || rawValidatorDids.length > 16) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorDids must contain 1..16 DIDs");
|
|
813
|
-
const validatorDids = Array.from(new Set(rawValidatorDids.map((v) => assertCleanString(v, "validatorDid"))));
|
|
814
|
-
if (validatorDids.length !== rawValidatorDids.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: duplicate validatorDids are not allowed");
|
|
815
|
-
if (!validatorDids.includes(bridgeProposerDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: bridgeProposerDid must be included in validatorDids");
|
|
816
|
-
const defaultMinSigs = allowSingleSignerForTesting && validatorDids.length === 1 ? 1 : 2;
|
|
817
|
-
const minValidatorSignatures = config.minValidatorSignatures ?? defaultMinSigs;
|
|
818
|
-
if (!Number.isSafeInteger(minValidatorSignatures) || minValidatorSignatures < 1 || minValidatorSignatures > validatorDids.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: minValidatorSignatures must be in 1..validatorDids.length");
|
|
819
|
-
if (!allowSingleSignerForTesting && minValidatorSignatures < 2) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: multi-domain quorum requires minValidatorSignatures >= 2 unless allowSingleSignerForTesting is explicitly true");
|
|
820
|
-
const minConfirmations = config.minConfirmations ?? DEFAULT_MIN_EVM_CONFIRMATIONS;
|
|
821
|
-
if (!Number.isSafeInteger(minConfirmations) || minConfirmations < 1 || minConfirmations > 100) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: minConfirmations must be in 1..100");
|
|
822
|
-
const maxBlockSize = config.maxBlockSize ?? DEFAULT_MAX_ROLLUP_BLOCK_SIZE;
|
|
823
|
-
if (!Number.isSafeInteger(maxBlockSize) || maxBlockSize < 1 || maxBlockSize > DEFAULT_MAX_ROLLUP_BLOCK_SIZE) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: maxBlockSize must be in 1..${DEFAULT_MAX_ROLLUP_BLOCK_SIZE}`);
|
|
824
|
-
if (typeof config.minDepositAmount !== "bigint" || typeof config.maxDepositAmount !== "bigint" || config.minDepositAmount <= 0n || config.maxDepositAmount < config.minDepositAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid deposit amount bounds");
|
|
825
|
-
if (typeof config.minWithdrawAmount !== "bigint" || typeof config.maxWithdrawAmount !== "bigint" || config.minWithdrawAmount <= 0n || config.maxWithdrawAmount < config.minWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid withdraw amount bounds");
|
|
826
|
-
const maxDailyWithdrawAbt = config.maxDailyWithdrawAbt ?? config.maxWithdrawAmount * 10n;
|
|
827
|
-
if (typeof maxDailyWithdrawAbt !== "bigint" || maxDailyWithdrawAbt < config.minWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: maxDailyWithdrawAbt must be >= minWithdrawAmount");
|
|
828
|
-
const largeWithdrawTimelockThresholdAbt = config.largeWithdrawTimelockThresholdAbt ?? config.maxWithdrawAmount;
|
|
829
|
-
if (typeof largeWithdrawTimelockThresholdAbt !== "bigint" || largeWithdrawTimelockThresholdAbt < config.minWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: largeWithdrawTimelockThresholdAbt must be >= minWithdrawAmount");
|
|
830
|
-
const timelockDelaySeconds = config.timelockDelaySeconds ?? DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS;
|
|
831
|
-
if (!Number.isSafeInteger(timelockDelaySeconds) || timelockDelaySeconds < 60 || timelockDelaySeconds > 604800) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: timelockDelaySeconds must be in 60..604800 seconds");
|
|
832
|
-
const genesisBlockHash = config.genesisBlockHash ? assertBytes32Hex(config.genesisBlockHash, "genesisBlockHash") : ZERO_BYTES32_HASH;
|
|
833
|
-
if (typeof config.webhookHmacSecret !== "string" || config.webhookHmacSecret.trim().length < 16) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: webhookHmacSecret must be at least 16 characters");
|
|
834
|
-
this.config = {
|
|
835
|
-
bridgeId,
|
|
836
|
-
rollupAddress,
|
|
837
|
-
bridgeProposerDid,
|
|
838
|
-
guardianDid,
|
|
839
|
-
verifyingContractAddress,
|
|
840
|
-
ocapNativeAbtTokenAddress,
|
|
841
|
-
canonicalErc20AbtAddress,
|
|
842
|
-
allowedServicePaymentTokens,
|
|
843
|
-
allowedEvmChainIds,
|
|
844
|
-
validatorDids,
|
|
845
|
-
minValidatorSignatures,
|
|
846
|
-
allowSingleSignerForTesting,
|
|
847
|
-
minConfirmations,
|
|
848
|
-
minDepositAmount: config.minDepositAmount,
|
|
849
|
-
maxDepositAmount: config.maxDepositAmount,
|
|
850
|
-
minWithdrawAmount: config.minWithdrawAmount,
|
|
851
|
-
maxWithdrawAmount: config.maxWithdrawAmount,
|
|
852
|
-
maxDailyWithdrawAbt,
|
|
853
|
-
largeWithdrawTimelockThresholdAbt,
|
|
854
|
-
timelockDelaySeconds,
|
|
855
|
-
maxBlockSize,
|
|
856
|
-
genesisBlockHash,
|
|
857
|
-
webhookHmacSecret: config.webhookHmacSecret
|
|
858
|
-
};
|
|
859
|
-
this.latestBlockHash = genesisBlockHash;
|
|
860
|
-
this.allowedChainSet = new Set(allowedEvmChainIds);
|
|
861
|
-
this.allowedPaymentTokenSet = new Set(allowedServicePaymentTokens);
|
|
862
|
-
this.validatorSet = new Set(validatorDids);
|
|
863
|
-
}
|
|
864
|
-
assertNotPaused() {
|
|
865
|
-
if (this.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: bridge is emergency-paused by guardian");
|
|
866
|
-
}
|
|
867
|
-
/**
|
|
868
|
-
* Layer 3 Anti-Drain Control: Guardian emergency pause / unpause.
|
|
869
|
-
*/
|
|
870
|
-
setBridgePaused(params) {
|
|
871
|
-
const guardianDid = assertCleanString(params.guardianDid, "guardianDid");
|
|
872
|
-
if (guardianDid !== this.config.guardianDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: caller ${guardianDid} is not authorized guardian (${this.config.guardianDid})`);
|
|
873
|
-
this.paused = Boolean(params.paused);
|
|
874
|
-
return { paused: this.paused };
|
|
875
|
-
}
|
|
876
|
-
/**
|
|
877
|
-
* Layer 3 Anti-Drain Control: Guardian cancels a timelocked whale withdrawal before its timelock expires,
|
|
878
|
-
* restoring the Canary reserve watermark and daily withdrawal cap.
|
|
879
|
-
*/
|
|
880
|
-
cancelTimelockedWithdraw(params) {
|
|
881
|
-
const guardianDid = assertCleanString(params.guardianDid, "guardianDid");
|
|
882
|
-
if (guardianDid !== this.config.guardianDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: caller ${guardianDid} is not authorized guardian (${this.config.guardianDid})`);
|
|
883
|
-
if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
|
|
884
|
-
const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
885
|
-
const voucher = this.issuedDirectVouchers.get(cleanTxHash);
|
|
886
|
-
if (!voucher) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no issued direct withdraw voucher found for ${cleanTxHash}`);
|
|
887
|
-
if (voucher.cancelled === true || this.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw ${cleanTxHash} is already cancelled`);
|
|
888
|
-
if (!voucher.timelocked || params.nowUnixSeconds >= voucher.unlocksAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw ${cleanTxHash} cannot be cancelled because timelock window has already elapsed`);
|
|
889
|
-
voucher.cancelled = true;
|
|
890
|
-
this.cancelledWithdrawTxHashes.add(cleanTxHash);
|
|
891
|
-
this.cumulativeWithdrawnAbt -= voucher.amount;
|
|
892
|
-
const dayBucket = Math.floor(voucher.issuedAtUnixSeconds / 86400);
|
|
893
|
-
const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
|
|
894
|
-
const nextDayTotal = currentDayTotal > voucher.amount ? currentDayTotal - voucher.amount : 0n;
|
|
895
|
-
if (nextDayTotal === 0n) this.dailyWithdrawnByDay.delete(dayBucket);
|
|
896
|
-
else this.dailyWithdrawnByDay.set(dayBucket, nextDayTotal);
|
|
897
|
-
return {
|
|
898
|
-
cancelledTxHash: cleanTxHash,
|
|
899
|
-
refundedReserveAbt: voucher.amount
|
|
900
|
-
};
|
|
901
|
-
}
|
|
902
|
-
assertFinalizedEvmEvent(params) {
|
|
903
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
904
|
-
if (!this.allowedChainSet.has(evmChainId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
|
|
905
|
-
const evmTxHash = assertBytes32Hex(params.evmTxHash, "evmTxHash");
|
|
906
|
-
if (!Number.isSafeInteger(params.logIndex) || params.logIndex < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: logIndex must be a non-negative integer");
|
|
907
|
-
if (params.reorged === true) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: reorged EVM events are rejected");
|
|
908
|
-
if (!Number.isSafeInteger(params.confirmations) || params.confirmations < this.config.minConfirmations) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: confirmations (${params.confirmations}) below required finality threshold (${this.config.minConfirmations})`);
|
|
909
|
-
const eventKey = `${evmChainId}:${evmTxHash}:${params.logIndex}`;
|
|
910
|
-
if (this.processedEventKeys.has(eventKey)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate EVM event ${eventKey} replay blocked`);
|
|
911
|
-
return {
|
|
912
|
-
evmChainId,
|
|
913
|
-
evmTxHash,
|
|
914
|
-
eventKey
|
|
915
|
-
};
|
|
916
|
-
}
|
|
917
|
-
/**
|
|
918
|
-
* Track 1 — `Pay-Where-You-Are, Consume-on-OCAP`:
|
|
919
|
-
* Ingests a finalized `OcapServicePaid` event from Ethereum/Base (paid in ERC-20 ABT or USDC)
|
|
920
|
-
* and produces a deterministic `OcapServiceDeliveryInstruction` (`CrossChainPurchaseInput`)
|
|
921
|
-
* without minting or bridging any foreign token onto OCAP.
|
|
922
|
-
*/
|
|
923
|
-
ingestEvmServicePaymentEvent(input) {
|
|
924
|
-
this.assertNotPaused();
|
|
925
|
-
const { evmChainId, evmTxHash, eventKey } = this.assertFinalizedEvmEvent(input);
|
|
926
|
-
const orderId = assertBytes32Hex(input.orderId, "orderId");
|
|
927
|
-
if (orderId === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: orderId cannot be zero bytes32");
|
|
928
|
-
if (this.processedServiceOrderIds.has(orderId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate service orderId ${orderId} replay blocked`);
|
|
929
|
-
assertEvmAddress(input.payerEvmAddress, "payerEvmAddress");
|
|
930
|
-
const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
|
|
931
|
-
const serviceDid = assertCleanString(input.serviceDid, "serviceDid");
|
|
932
|
-
const paymentTokenAddress = assertEvmAddress(input.paymentTokenAddress, "paymentTokenAddress");
|
|
933
|
-
if (!this.allowedPaymentTokenSet.has(paymentTokenAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: paymentTokenAddress ${paymentTokenAddress} is not whitelisted for service payments`);
|
|
934
|
-
if (typeof input.amount !== "bigint" || input.amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: service payment amount must be > 0n");
|
|
935
|
-
const nftDid = input.deliverableNftDid ? assertCleanString(input.deliverableNftDid, "deliverableNftDid") : `did:abt:snft:service:${orderId.slice(2, 34)}`;
|
|
936
|
-
const depositProofPreimage = `ocap:evm-service-pay:v1:${this.config.bridgeId}:${eventKey}:${orderId}:${recipientDid}:${serviceDid}:${paymentTokenAddress}:${input.amount.toString()}`;
|
|
937
|
-
const depositProofDigest = keccak256(`0x${Buffer.from(depositProofPreimage, "utf8").toString("hex")}`).toLowerCase();
|
|
938
|
-
const crossChainPurchaseInput = {
|
|
939
|
-
id: `blk:evm-pay:${orderId.slice(2, 18)}`,
|
|
940
|
-
relayer: this.config.bridgeProposerDid,
|
|
941
|
-
buyer: recipientDid,
|
|
942
|
-
deposit: {
|
|
943
|
-
rollup: this.config.rollupAddress,
|
|
944
|
-
proposer: this.config.bridgeProposerDid,
|
|
945
|
-
token: {
|
|
946
|
-
address: this.config.ocapNativeAbtTokenAddress,
|
|
947
|
-
value: input.amount.toString()
|
|
948
|
-
},
|
|
949
|
-
actualFee: "0",
|
|
950
|
-
evidence: {
|
|
951
|
-
hash: evmTxHash,
|
|
952
|
-
targetType: "EVM",
|
|
953
|
-
targetChainId: evmChainId
|
|
954
|
-
}
|
|
955
|
-
},
|
|
956
|
-
purchaseStatements: [{
|
|
957
|
-
id: "purchase_1",
|
|
958
|
-
typeUrl: "fg:t:acquire_asset_v3",
|
|
959
|
-
from: recipientDid,
|
|
960
|
-
to: serviceDid,
|
|
961
|
-
tokenAddress: this.config.ocapNativeAbtTokenAddress,
|
|
962
|
-
amount: input.amount.toString(),
|
|
963
|
-
itx: {
|
|
964
|
-
factory: serviceDid,
|
|
965
|
-
assets: [nftDid]
|
|
966
|
-
}
|
|
967
|
-
}]
|
|
968
|
-
};
|
|
969
|
-
this.processedEventKeys.add(eventKey);
|
|
970
|
-
this.processedServiceOrderIds.add(orderId);
|
|
971
|
-
return {
|
|
972
|
-
instructionId: `srv:${orderId.slice(2, 26)}`,
|
|
973
|
-
eventKey,
|
|
974
|
-
orderId,
|
|
975
|
-
recipientDid,
|
|
976
|
-
serviceDid,
|
|
977
|
-
paymentTokenAddress,
|
|
978
|
-
paidAmount: input.amount,
|
|
979
|
-
depositProofDigest,
|
|
980
|
-
crossChainPurchaseInput
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
/**
|
|
984
|
-
* Track 2A — `ERC-20 ABT -> OCAP Native ABT` 1:1 Relayer-Sponsored Deposit:
|
|
985
|
-
* Ingests a finalized `NativeAbtDepositLocked` event on Ethereum/Base, increments the Canary
|
|
986
|
-
* reserve watermark (`cumulativeDepositedAbt`), and generates a proposer-sponsored `deposit_token_v2`
|
|
987
|
-
* instruction so even 0-gas OCAP accounts receive Native ABT in 1 click.
|
|
988
|
-
*/
|
|
989
|
-
ingestEvmAbtDepositEvent(input) {
|
|
990
|
-
this.assertNotPaused();
|
|
991
|
-
const { eventKey, evmTxHash } = this.assertFinalizedEvmEvent(input);
|
|
992
|
-
assertEvmAddress(input.depositorEvmAddress, "depositorEvmAddress");
|
|
993
|
-
const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
|
|
994
|
-
if (assertEvmAddress(input.tokenAddress, "tokenAddress") !== this.config.canonicalErc20AbtAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: canonical deposit only accepts official ERC-20 ABT (${this.config.canonicalErc20AbtAddress})`);
|
|
995
|
-
if (typeof input.amount !== "bigint" || input.amount < this.config.minDepositAmount || input.amount > this.config.maxDepositAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: deposit amount (${String(input.amount)}) must be within [${this.config.minDepositAmount}, ${this.config.maxDepositAmount}]`);
|
|
996
|
-
const actualFee = input.actualFee ?? 0n;
|
|
997
|
-
if (typeof actualFee !== "bigint" || actualFee < 0n || actualFee >= input.amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: actualFee must be a non-negative bigint strictly less than deposit amount");
|
|
998
|
-
const netValue = input.amount - actualFee;
|
|
999
|
-
this.cumulativeDepositedAbt += input.amount;
|
|
1000
|
-
this.processedEventKeys.add(eventKey);
|
|
1001
|
-
return {
|
|
1002
|
-
instructionId: `dep:${evmTxHash.slice(2, 26)}:${input.logIndex}`,
|
|
1003
|
-
eventKey,
|
|
1004
|
-
rollupAddress: this.config.rollupAddress,
|
|
1005
|
-
proposerDid: this.config.bridgeProposerDid,
|
|
1006
|
-
proposerSponsored: true,
|
|
1007
|
-
recipientDid,
|
|
1008
|
-
tokenAddress: this.config.ocapNativeAbtTokenAddress,
|
|
1009
|
-
value: netValue,
|
|
1010
|
-
actualFee,
|
|
1011
|
-
evidenceHash: evmTxHash,
|
|
1012
|
-
cumulativeDepositedAbt: this.cumulativeDepositedAbt
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
/**
|
|
1016
|
-
* Track 2B (Step 1) — Enqueues a finalized OCAP `withdraw_token_v2` transaction for the next
|
|
1017
|
-
* Rollup Merkle block, enforcing the Canary Net-Inflow Reserve Watermark up front.
|
|
1018
|
-
*/
|
|
1019
|
-
enqueueOcapAbtWithdraw(withdraw) {
|
|
1020
|
-
this.assertNotPaused();
|
|
1021
|
-
const ocapTxHash = assertBytes32Hex(withdraw.ocapTxHash, "ocapTxHash");
|
|
1022
|
-
if (ocapTxHash === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
|
|
1023
|
-
if (this.processedWithdrawTxHashes.has(ocapTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw ocapTxHash ${ocapTxHash} replay blocked`);
|
|
1024
|
-
const fromDid = assertCleanString(withdraw.fromDid, "fromDid");
|
|
1025
|
-
const recipientEvmAddress = assertEvmAddress(withdraw.recipientEvmAddress, "recipientEvmAddress");
|
|
1026
|
-
if (typeof withdraw.amount !== "bigint" || withdraw.amount < this.config.minWithdrawAmount || withdraw.amount > this.config.maxWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${String(withdraw.amount)}) must be within [${this.config.minWithdrawAmount}, ${this.config.maxWithdrawAmount}]`);
|
|
1027
|
-
if (withdraw.amount >= this.config.largeWithdrawTimelockThresholdAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: whale withdraw (${withdraw.amount} >= ${this.config.largeWithdrawTimelockThresholdAbt}) must use issueDirectWithdrawVoucher to enforce Layer 3 24h Timelock`);
|
|
1028
|
-
const pendingWithdrawTotal = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
|
|
1029
|
-
const nextTotalWithdrawn = this.cumulativeWithdrawnAbt + pendingWithdrawTotal + withdraw.amount;
|
|
1030
|
-
if (nextTotalWithdrawn > this.cumulativeDepositedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${withdraw.amount}) exceeds Canary net-inflow reserve watermark: nextTotalWithdrawn (${nextTotalWithdrawn}) > cumulativeDepositedAbt (${this.cumulativeDepositedAbt})`);
|
|
1031
|
-
this.processedWithdrawTxHashes.add(ocapTxHash);
|
|
1032
|
-
this.pendingWithdrawQueue.push({
|
|
1033
|
-
ocapTxHash,
|
|
1034
|
-
fromDid,
|
|
1035
|
-
recipientEvmAddress,
|
|
1036
|
-
amount: withdraw.amount
|
|
1037
|
-
});
|
|
1038
|
-
return {
|
|
1039
|
-
queuedCount: this.pendingWithdrawQueue.length,
|
|
1040
|
-
pendingWithdrawTotal: pendingWithdrawTotal + withdraw.amount
|
|
1041
|
-
};
|
|
1042
|
-
}
|
|
1043
|
-
/**
|
|
1044
|
-
* Pre-computes the next pending Rollup block header (`height`, `previousHash`, `merkleRoot`, `txsHash`, `blockHash`)
|
|
1045
|
-
* so validators can sign `blockHash` before calling `sealRollupWithdrawBlock`.
|
|
1046
|
-
*/
|
|
1047
|
-
previewNextRollupWithdrawBlock() {
|
|
1048
|
-
if (this.pendingWithdrawQueue.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: no pending withdraw transactions to seal");
|
|
1049
|
-
const batchWithdrawTxs = this.pendingWithdrawQueue.slice(0, this.config.maxBlockSize).map((item) => ({ ...item }));
|
|
1050
|
-
const height = this.latestBlockHeight + 1;
|
|
1051
|
-
const previousHash = this.latestBlockHash;
|
|
1052
|
-
const { merkleRoot } = buildEvmBridgeMerkleTree(batchWithdrawTxs);
|
|
1053
|
-
const txsHash = computeEvmBridgeTxsHash(batchWithdrawTxs.map((tx) => tx.ocapTxHash));
|
|
1054
|
-
return {
|
|
1055
|
-
height,
|
|
1056
|
-
previousHash,
|
|
1057
|
-
merkleRoot,
|
|
1058
|
-
txsHash,
|
|
1059
|
-
blockHash: computeEvmBridgeBlockHash({
|
|
1060
|
-
height,
|
|
1061
|
-
previousHash,
|
|
1062
|
-
merkleRoot,
|
|
1063
|
-
txsHash
|
|
1064
|
-
}),
|
|
1065
|
-
batchWithdrawTxs
|
|
1066
|
-
};
|
|
1067
|
-
}
|
|
1068
|
-
/**
|
|
1069
|
-
* Track 2B (Step 2) — Seals a batch of pending OCAP withdrawals into a `@ocap/merkle-tree` compatible
|
|
1070
|
-
* Rollup block verified by M-of-N distinct validators.
|
|
1071
|
-
*/
|
|
1072
|
-
sealRollupWithdrawBlock(params) {
|
|
1073
|
-
this.assertNotPaused();
|
|
1074
|
-
if (!Number.isSafeInteger(params.sealedAtUnixSeconds) || params.sealedAtUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: sealedAtUnixSeconds must be a positive integer");
|
|
1075
|
-
if (!Array.isArray(params.validatorSignatures)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorSignatures must be an array");
|
|
1076
|
-
const preview = this.previewNextRollupWithdrawBlock();
|
|
1077
|
-
const seenValidators = /* @__PURE__ */ new Set();
|
|
1078
|
-
const validatorSigners = [];
|
|
1079
|
-
for (const sig of params.validatorSignatures) {
|
|
1080
|
-
if (!sig || typeof sig !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid validator signature entry");
|
|
1081
|
-
const validatorDid = assertCleanString(sig.validatorDid, "validatorDid");
|
|
1082
|
-
if (!this.validatorSet.has(validatorDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: signer ${validatorDid} is not an authorized bridge validator`);
|
|
1083
|
-
if (seenValidators.has(validatorDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate validator signature from ${validatorDid}`);
|
|
1084
|
-
const expectedDigest = computeValidatorBlockSignatureDigest(this.config.bridgeId, this.config.rollupAddress, preview.blockHash, validatorDid);
|
|
1085
|
-
if (assertBytes32Hex(sig.signatureDigest, "signatureDigest") !== expectedDigest) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: invalid signatureDigest from validator ${validatorDid}`);
|
|
1086
|
-
seenValidators.add(validatorDid);
|
|
1087
|
-
validatorSigners.push(validatorDid);
|
|
1088
|
-
}
|
|
1089
|
-
if (validatorSigners.length < this.config.minValidatorSignatures) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator quorum not met (${validatorSigners.length} < ${this.config.minValidatorSignatures})`);
|
|
1090
|
-
const batchTotal = preview.batchWithdrawTxs.reduce((acc, item) => acc + item.amount, 0n);
|
|
1091
|
-
if (this.cumulativeWithdrawnAbt + batchTotal > this.cumulativeDepositedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: batch withdraw total exceeds Canary net-inflow reserve watermark");
|
|
1092
|
-
const dayBucket = Math.floor(params.sealedAtUnixSeconds / 86400);
|
|
1093
|
-
const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
|
|
1094
|
-
if (currentDayTotal + batchTotal > this.config.maxDailyWithdrawAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: batch withdraw (${batchTotal}) exceeds 24h rolling withdrawal cap (${this.config.maxDailyWithdrawAbt})`);
|
|
1095
|
-
this.pendingWithdrawQueue.splice(0, preview.batchWithdrawTxs.length);
|
|
1096
|
-
this.cumulativeWithdrawnAbt += batchTotal;
|
|
1097
|
-
this.dailyWithdrawnByDay.set(dayBucket, currentDayTotal + batchTotal);
|
|
1098
|
-
this.latestBlockHeight = preview.height;
|
|
1099
|
-
this.latestBlockHash = preview.blockHash;
|
|
1100
|
-
const sealedBlock = {
|
|
1101
|
-
height: preview.height,
|
|
1102
|
-
previousHash: preview.previousHash,
|
|
1103
|
-
merkleRoot: preview.merkleRoot,
|
|
1104
|
-
txsHash: preview.txsHash,
|
|
1105
|
-
blockHash: preview.blockHash,
|
|
1106
|
-
withdrawTxs: preview.batchWithdrawTxs,
|
|
1107
|
-
validatorSigners,
|
|
1108
|
-
sealedAtUnixSeconds: params.sealedAtUnixSeconds
|
|
1109
|
-
};
|
|
1110
|
-
this.sealedBlocks.set(sealedBlock.height, sealedBlock);
|
|
1111
|
-
for (const tx of sealedBlock.withdrawTxs) this.withdrawTxToBlockHeight.set(tx.ocapTxHash, sealedBlock.height);
|
|
1112
|
-
return sealedBlock;
|
|
1113
|
-
}
|
|
1114
|
-
/**
|
|
1115
|
-
* Track 2B (Step 3) — Generates the Merkle proof bundle for a sealed `ocapTxHash` so the user
|
|
1116
|
-
* can claim their ERC-20 ABT from `ArcEvmBridgeGateway.claimWithdrawWithMerkleProof` on Ethereum/Base.
|
|
1117
|
-
*/
|
|
1118
|
-
generateWithdrawClaimProof(ocapTxHash) {
|
|
1119
|
-
const cleanTxHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
|
|
1120
|
-
const blockHeight = this.withdrawTxToBlockHeight.get(cleanTxHash);
|
|
1121
|
-
if (blockHeight === void 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: withdraw tx ${cleanTxHash} is not in any sealed Rollup block`);
|
|
1122
|
-
const block = this.sealedBlocks.get(blockHeight);
|
|
1123
|
-
const targetTx = block.withdrawTxs.find((t) => t.ocapTxHash === cleanTxHash);
|
|
1124
|
-
const leafHash = computeEvmBridgeWithdrawLeafHash(targetTx.ocapTxHash, targetTx.recipientEvmAddress, targetTx.amount);
|
|
1125
|
-
const merkleProof = buildEvmBridgeMerkleTree(block.withdrawTxs).getProofForLeaf(leafHash);
|
|
1126
|
-
return {
|
|
1127
|
-
ocapTxHash: cleanTxHash,
|
|
1128
|
-
recipientEvmAddress: targetTx.recipientEvmAddress,
|
|
1129
|
-
amount: targetTx.amount,
|
|
1130
|
-
blockHeight: block.height,
|
|
1131
|
-
blockHash: block.blockHash,
|
|
1132
|
-
merkleRoot: block.merkleRoot,
|
|
1133
|
-
leafHash,
|
|
1134
|
-
merkleProof
|
|
1135
|
-
};
|
|
1136
|
-
}
|
|
1137
|
-
/**
|
|
1138
|
-
* Track 2B (Primary — Zero-Rollup-Block EIP-712 Pull Mode):
|
|
1139
|
-
* Immediately issues a threshold-signed `DirectWithdrawVoucher` for an OCAP withdraw transaction
|
|
1140
|
-
* without creating any `RollupBlock`, without building any Merkle tree, and without requiring the
|
|
1141
|
-
* Cloudflare Bridge Node to submit any Ethereum transaction or hold ETH gas.
|
|
1142
|
-
*/
|
|
1143
|
-
issueDirectWithdrawVoucher(params) {
|
|
1144
|
-
this.assertNotPaused();
|
|
1145
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
1146
|
-
if (!this.allowedChainSet.has(evmChainId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
|
|
1147
|
-
const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
1148
|
-
if (ocapTxHash === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: ocapTxHash cannot be zero bytes32");
|
|
1149
|
-
if (this.processedWithdrawTxHashes.has(ocapTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw ocapTxHash ${ocapTxHash} replay blocked`);
|
|
1150
|
-
const fromDid = assertCleanString(params.fromDid, "fromDid");
|
|
1151
|
-
const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
|
|
1152
|
-
if (typeof params.amount !== "bigint" || params.amount < this.config.minWithdrawAmount || params.amount > this.config.maxWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdraw amount (${String(params.amount)}) must be within [${this.config.minWithdrawAmount}, ${this.config.maxWithdrawAmount}]`);
|
|
1153
|
-
if (!Number.isSafeInteger(params.issuedAtUnixSeconds) || params.issuedAtUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.issuedAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: expiresAtUnixSeconds must be strictly greater than issuedAtUnixSeconds");
|
|
1154
|
-
const ttl = params.expiresAtUnixSeconds - params.issuedAtUnixSeconds;
|
|
1155
|
-
if (ttl < MIN_DIRECT_VOUCHER_TTL_SECONDS || ttl > MAX_DIRECT_VOUCHER_TTL_SECONDS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: direct voucher TTL (${ttl}s) must be within [${MIN_DIRECT_VOUCHER_TTL_SECONDS}, ${MAX_DIRECT_VOUCHER_TTL_SECONDS}]`);
|
|
1156
|
-
const timelocked = params.amount >= this.config.largeWithdrawTimelockThresholdAbt;
|
|
1157
|
-
const unlocksAtUnixSeconds = timelocked ? params.issuedAtUnixSeconds + this.config.timelockDelaySeconds : params.issuedAtUnixSeconds;
|
|
1158
|
-
if (timelocked && params.expiresAtUnixSeconds <= unlocksAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: timelocked whale withdraw voucher expiresAtUnixSeconds (${params.expiresAtUnixSeconds}) must be strictly greater than unlocksAtUnixSeconds (${unlocksAtUnixSeconds})`);
|
|
1159
|
-
const pendingWithdrawTotal = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
|
|
1160
|
-
const nextTotalWithdrawn = this.cumulativeWithdrawnAbt + pendingWithdrawTotal + params.amount;
|
|
1161
|
-
if (nextTotalWithdrawn > this.cumulativeDepositedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct voucher withdraw (${params.amount}) exceeds Canary net-inflow reserve watermark: nextTotalWithdrawn (${nextTotalWithdrawn}) > cumulativeDepositedAbt (${this.cumulativeDepositedAbt})`);
|
|
1162
|
-
const dayBucket = Math.floor(params.issuedAtUnixSeconds / 86400);
|
|
1163
|
-
const currentDayTotal = this.dailyWithdrawnByDay.get(dayBucket) ?? 0n;
|
|
1164
|
-
if (currentDayTotal + params.amount > this.config.maxDailyWithdrawAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct voucher withdraw (${params.amount}) exceeds 24h rolling withdrawal cap (${this.config.maxDailyWithdrawAbt})`);
|
|
1165
|
-
const eip712DomainSeparator = computeEip712BridgeDomainSeparator({
|
|
1166
|
-
evmChainId,
|
|
1167
|
-
verifyingContractAddress: this.config.verifyingContractAddress
|
|
1168
|
-
});
|
|
1169
|
-
const eip712StructHash = computeEip712WithdrawStructHash({
|
|
1170
|
-
bridgeId: this.config.bridgeId,
|
|
1171
|
-
ocapTxHash,
|
|
1172
|
-
recipientEvmAddress,
|
|
1173
|
-
amount: params.amount,
|
|
1174
|
-
expiresAtUnixSeconds: params.expiresAtUnixSeconds
|
|
1175
|
-
});
|
|
1176
|
-
const voucherDigest = computeDirectWithdrawVoucherDigest({
|
|
1177
|
-
bridgeId: this.config.bridgeId,
|
|
1178
|
-
evmChainId,
|
|
1179
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1180
|
-
ocapTxHash,
|
|
1181
|
-
recipientEvmAddress,
|
|
1182
|
-
amount: params.amount,
|
|
1183
|
-
expiresAtUnixSeconds: params.expiresAtUnixSeconds
|
|
1184
|
-
});
|
|
1185
|
-
if (!Array.isArray(params.validatorSignatures)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: validatorSignatures must be an array");
|
|
1186
|
-
const seenValidators = /* @__PURE__ */ new Set();
|
|
1187
|
-
const validatorSigners = [];
|
|
1188
|
-
const normalizedSignatures = [];
|
|
1189
|
-
for (const sig of params.validatorSignatures) {
|
|
1190
|
-
if (!sig || typeof sig !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid validator signature entry");
|
|
1191
|
-
const validatorDid = assertCleanString(sig.validatorDid, "validatorDid");
|
|
1192
|
-
if (!this.validatorSet.has(validatorDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: signer ${validatorDid} is not an authorized bridge validator`);
|
|
1193
|
-
if (seenValidators.has(validatorDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate validator signature from ${validatorDid}`);
|
|
1194
|
-
const expectedSig = computeValidatorVoucherSignatureDigest(this.config.bridgeId, voucherDigest, validatorDid);
|
|
1195
|
-
const actualSig = assertBytes32Hex(sig.signatureDigest, "signatureDigest");
|
|
1196
|
-
if (actualSig !== expectedSig) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: invalid voucher signatureDigest from validator ${validatorDid}`);
|
|
1197
|
-
seenValidators.add(validatorDid);
|
|
1198
|
-
validatorSigners.push(validatorDid);
|
|
1199
|
-
const normalizedSig = {
|
|
1200
|
-
validatorDid,
|
|
1201
|
-
signatureDigest: actualSig
|
|
1202
|
-
};
|
|
1203
|
-
if (sig.v !== void 0 || sig.r !== void 0 || sig.s !== void 0 || sig.evmSignerAddress !== void 0) {
|
|
1204
|
-
if (sig.v === void 0 || !sig.r || !sig.s) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: validator ${validatorDid} ECDSA signature must provide complete (v, r, s)`);
|
|
1205
|
-
const recoveredAddr = ecrecoverEvmAddress(voucherDigest, sig.v, sig.r, sig.s);
|
|
1206
|
-
if (sig.evmSignerAddress !== void 0) {
|
|
1207
|
-
const expectedAddr = assertEvmAddress(sig.evmSignerAddress, "evmSignerAddress");
|
|
1208
|
-
if (recoveredAddr !== expectedAddr) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator ${validatorDid} ecrecover (${recoveredAddr}) does not match evmSignerAddress (${expectedAddr})`);
|
|
1209
|
-
}
|
|
1210
|
-
normalizedSig.evmSignerAddress = recoveredAddr;
|
|
1211
|
-
normalizedSig.v = sig.v;
|
|
1212
|
-
normalizedSig.r = assertBytes32Hex(sig.r, "r");
|
|
1213
|
-
normalizedSig.s = assertBytes32Hex(sig.s, "s");
|
|
1214
|
-
}
|
|
1215
|
-
normalizedSignatures.push(normalizedSig);
|
|
1216
|
-
}
|
|
1217
|
-
if (validatorSigners.length < this.config.minValidatorSignatures) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: validator quorum not met (${validatorSigners.length} < ${this.config.minValidatorSignatures})`);
|
|
1218
|
-
this.processedWithdrawTxHashes.add(ocapTxHash);
|
|
1219
|
-
this.cumulativeWithdrawnAbt += params.amount;
|
|
1220
|
-
this.dailyWithdrawnByDay.set(dayBucket, currentDayTotal + params.amount);
|
|
1221
|
-
const voucher = {
|
|
1222
|
-
voucherDigest,
|
|
1223
|
-
eip712DomainSeparator,
|
|
1224
|
-
eip712StructHash,
|
|
1225
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1226
|
-
bridgeId: this.config.bridgeId,
|
|
1227
|
-
evmChainId,
|
|
1228
|
-
ocapTxHash,
|
|
1229
|
-
fromDid,
|
|
1230
|
-
recipientEvmAddress,
|
|
1231
|
-
amount: params.amount,
|
|
1232
|
-
issuedAtUnixSeconds: params.issuedAtUnixSeconds,
|
|
1233
|
-
expiresAtUnixSeconds: params.expiresAtUnixSeconds,
|
|
1234
|
-
timelocked,
|
|
1235
|
-
unlocksAtUnixSeconds,
|
|
1236
|
-
cancelled: false,
|
|
1237
|
-
validatorSigners,
|
|
1238
|
-
validatorSignatures: normalizedSignatures
|
|
1239
|
-
};
|
|
1240
|
-
this.issuedDirectVouchers.set(ocapTxHash, voucher);
|
|
1241
|
-
return cloneDirectWithdrawVoucher(voucher);
|
|
1242
|
-
}
|
|
1243
|
-
/**
|
|
1244
|
-
* Retrieves an already-issued Zero-Rollup-Block `DirectWithdrawVoucher` by `ocapTxHash`.
|
|
1245
|
-
*/
|
|
1246
|
-
getDirectWithdrawVoucher(ocapTxHash) {
|
|
1247
|
-
const cleanTxHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
|
|
1248
|
-
const voucher = this.issuedDirectVouchers.get(cleanTxHash);
|
|
1249
|
-
if (!voucher) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no direct withdraw voucher found for ${cleanTxHash}`);
|
|
1250
|
-
if (voucher.cancelled === true || this.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct withdraw voucher ${cleanTxHash} was cancelled by guardian`);
|
|
1251
|
-
return cloneDirectWithdrawVoucher(voucher);
|
|
1252
|
-
}
|
|
1253
|
-
getReserveWatermarkState() {
|
|
1254
|
-
const pendingWithdrawAbt = this.pendingWithdrawQueue.reduce((acc, item) => acc + item.amount, 0n);
|
|
1255
|
-
return {
|
|
1256
|
-
paused: this.paused,
|
|
1257
|
-
latestBlockHeight: this.latestBlockHeight,
|
|
1258
|
-
latestBlockHash: this.latestBlockHash,
|
|
1259
|
-
cumulativeDepositedAbt: this.cumulativeDepositedAbt,
|
|
1260
|
-
cumulativeWithdrawnAbt: this.cumulativeWithdrawnAbt,
|
|
1261
|
-
pendingWithdrawAbt,
|
|
1262
|
-
availableWithdrawReserveAbt: this.cumulativeDepositedAbt - this.cumulativeWithdrawnAbt - pendingWithdrawAbt,
|
|
1263
|
-
pendingWithdrawCount: this.pendingWithdrawQueue.length,
|
|
1264
|
-
issuedDirectVoucherCount: this.issuedDirectVouchers.size,
|
|
1265
|
-
cancelledWithdrawCount: this.cancelledWithdrawTxHashes.size
|
|
1266
|
-
};
|
|
1267
|
-
}
|
|
1268
|
-
/**
|
|
1269
|
-
* Issue #1245:
|
|
1270
|
-
* Returns the Circle `bridge.usdc.com`-style Web Portal configuration hosted by the ArcBridge Blocklet.
|
|
1271
|
-
* Requires zero custom native wallet code (`walletRequired: 'STANDARD_WEB_EIP1193_ONLY'`).
|
|
1272
|
-
*/
|
|
1273
|
-
getWebPortalConfig() {
|
|
1274
|
-
return {
|
|
1275
|
-
portalVersion: "1.0.0",
|
|
1276
|
-
hostPlatform: "ARC_BRIDGE_BLOCKLET",
|
|
1277
|
-
blockletDid: this.config.bridgeProposerDid,
|
|
1278
|
-
didConnectSessionSupported: true,
|
|
1279
|
-
zeroBridgeFee: true,
|
|
1280
|
-
bridgeFeeBps: 0,
|
|
1281
|
-
walletRequired: "STANDARD_WEB_EIP1193_ONLY",
|
|
1282
|
-
bridgeId: this.config.bridgeId,
|
|
1283
|
-
rollupAddress: this.config.rollupAddress,
|
|
1284
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1285
|
-
canonicalErc20AbtAddress: this.config.canonicalErc20AbtAddress,
|
|
1286
|
-
ocapNativeAbtTokenAddress: this.config.ocapNativeAbtTokenAddress,
|
|
1287
|
-
allowedEvmChainIds: [...this.config.allowedEvmChainIds],
|
|
1288
|
-
allowedServicePaymentTokens: [...this.config.allowedServicePaymentTokens],
|
|
1289
|
-
paused: this.paused,
|
|
1290
|
-
eip712Domain: {
|
|
1291
|
-
name: EIP712_BRIDGE_DOMAIN_NAME,
|
|
1292
|
-
version: EIP712_BRIDGE_DOMAIN_VERSION,
|
|
1293
|
-
verifyingContract: this.config.verifyingContractAddress
|
|
1294
|
-
},
|
|
1295
|
-
limits: {
|
|
1296
|
-
minDepositAmount: this.config.minDepositAmount.toString(),
|
|
1297
|
-
maxDepositAmount: this.config.maxDepositAmount.toString(),
|
|
1298
|
-
minWithdrawAmount: this.config.minWithdrawAmount.toString(),
|
|
1299
|
-
maxWithdrawAmount: this.config.maxWithdrawAmount.toString(),
|
|
1300
|
-
maxDailyWithdrawAbt: this.config.maxDailyWithdrawAbt.toString(),
|
|
1301
|
-
largeWithdrawTimelockThresholdAbt: this.config.largeWithdrawTimelockThresholdAbt.toString(),
|
|
1302
|
-
timelockDelaySeconds: this.config.timelockDelaySeconds
|
|
1303
|
-
},
|
|
1304
|
-
deprecatedRollupProtocols: DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS
|
|
1305
|
-
};
|
|
1306
|
-
}
|
|
1307
|
-
/**
|
|
1308
|
-
* Issue #1245:
|
|
1309
|
-
* Builds a wallet-agnostic EIP-1193 transaction execution plan for the ArcBridge Blocklet Web Portal
|
|
1310
|
-
* (`bridge.usdc.com`-style one-click web experience without custom wallet bridge code).
|
|
1311
|
-
*/
|
|
1312
|
-
buildWebPortalActionBundle(input) {
|
|
1313
|
-
this.assertNotPaused();
|
|
1314
|
-
if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: portal action input must be an object");
|
|
1315
|
-
const approveSig = "approve(address,uint256)";
|
|
1316
|
-
const approveSelector = computeSolidityFunctionSelector(approveSig);
|
|
1317
|
-
const gatewayWordHex64 = this.config.verifyingContractAddress.slice(2).padStart(64, "0");
|
|
1318
|
-
if (input.action === "DEPOSIT_FOR_NATIVE_ABT") {
|
|
1319
|
-
const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
|
|
1320
|
-
if (!this.allowedChainSet.has(evmChainId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
|
|
1321
|
-
const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
|
|
1322
|
-
if (input.userEvmAddress !== void 0) assertEvmAddress(input.userEvmAddress, "userEvmAddress");
|
|
1323
|
-
if (typeof input.amount !== "bigint" || input.amount < this.config.minDepositAmount || input.amount > this.config.maxDepositAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: portal deposit amount (${String(input.amount)}) must be within [${this.config.minDepositAmount}, ${this.config.maxDepositAmount}]`);
|
|
1324
|
-
const amountHex64 = uint256ToHex64(input.amount);
|
|
1325
|
-
const approveCalldata = `${approveSelector}${gatewayWordHex64}${amountHex64}`;
|
|
1326
|
-
const depositSig = "depositForNativeAbt(string,uint256)";
|
|
1327
|
-
const depositSelector = computeSolidityFunctionSelector(depositSig);
|
|
1328
|
-
const depositCalldata = `${depositSelector}${uint256ToHex64(64)}${amountHex64}${encodeAbiDynamicUtf8String(recipientDid)}`;
|
|
1329
|
-
return {
|
|
1330
|
-
action: "DEPOSIT_FOR_NATIVE_ABT",
|
|
1331
|
-
hostPlatform: "ARC_BRIDGE_BLOCKLET",
|
|
1332
|
-
blockletDid: this.config.bridgeProposerDid,
|
|
1333
|
-
walletRequired: "STANDARD_WEB_EIP1193_ONLY",
|
|
1334
|
-
bridgeId: this.config.bridgeId,
|
|
1335
|
-
evmChainId,
|
|
1336
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1337
|
-
autoRelayerSponsoredOnOcap: true,
|
|
1338
|
-
steps: [{
|
|
1339
|
-
stepId: "ERC20_APPROVE",
|
|
1340
|
-
description: "Approve canonical ERC-20 ABT to ArcEvmBridgeGateway",
|
|
1341
|
-
evmChainId,
|
|
1342
|
-
to: this.config.canonicalErc20AbtAddress,
|
|
1343
|
-
valueHex: "0x0",
|
|
1344
|
-
methodSignature: approveSig,
|
|
1345
|
-
functionSelector: approveSelector,
|
|
1346
|
-
calldataHex: approveCalldata,
|
|
1347
|
-
args: {
|
|
1348
|
-
spender: this.config.verifyingContractAddress,
|
|
1349
|
-
amount: input.amount.toString()
|
|
1350
|
-
}
|
|
1351
|
-
}, {
|
|
1352
|
-
stepId: "BRIDGE_DEPOSIT",
|
|
1353
|
-
description: "Lock ERC-20 ABT and auto-mint 1:1 Native ABT on OCAP (Relayer-Sponsored)",
|
|
1354
|
-
evmChainId,
|
|
1355
|
-
to: this.config.verifyingContractAddress,
|
|
1356
|
-
valueHex: "0x0",
|
|
1357
|
-
methodSignature: depositSig,
|
|
1358
|
-
functionSelector: depositSelector,
|
|
1359
|
-
calldataHex: depositCalldata,
|
|
1360
|
-
args: {
|
|
1361
|
-
recipientDid,
|
|
1362
|
-
amount: input.amount.toString()
|
|
1363
|
-
}
|
|
1364
|
-
}]
|
|
1365
|
-
};
|
|
1366
|
-
}
|
|
1367
|
-
if (input.action === "CLAIM_WITH_DIRECT_VOUCHER") {
|
|
1368
|
-
const voucher = this.getDirectWithdrawVoucher(input.ocapTxHash);
|
|
1369
|
-
if (input.nowUnixSeconds !== void 0) {
|
|
1370
|
-
if (!Number.isSafeInteger(input.nowUnixSeconds) || input.nowUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
|
|
1371
|
-
if (input.nowUnixSeconds > voucher.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: direct withdraw voucher ${voucher.ocapTxHash} has expired`);
|
|
1372
|
-
}
|
|
1373
|
-
const claimSig = "claimWithdrawWithDirectVoucher(bytes32,address,uint256,uint256,bytes32,uint8[],bytes32[],bytes32[])";
|
|
1374
|
-
const claimSelector = computeSolidityFunctionSelector(claimSig);
|
|
1375
|
-
const txHashHex64 = voucher.ocapTxHash.slice(2);
|
|
1376
|
-
const toWordHex64 = voucher.recipientEvmAddress.slice(2).padStart(64, "0");
|
|
1377
|
-
const amountHex64 = uint256ToHex64(voucher.amount);
|
|
1378
|
-
const expiresHex64 = uint256ToHex64(voucher.expiresAtUnixSeconds);
|
|
1379
|
-
const digestHex64 = voucher.voucherDigest.slice(2);
|
|
1380
|
-
const sortedSigs = [...voucher.validatorSignatures].sort((a, b) => {
|
|
1381
|
-
if (a.evmSignerAddress && b.evmSignerAddress) return BigInt(a.evmSignerAddress) < BigInt(b.evmSignerAddress) ? -1 : BigInt(a.evmSignerAddress) > BigInt(b.evmSignerAddress) ? 1 : 0;
|
|
1382
|
-
return 0;
|
|
1383
|
-
});
|
|
1384
|
-
const sigCount = sortedSigs.length;
|
|
1385
|
-
const vOffsetHex64 = uint256ToHex64(256);
|
|
1386
|
-
const rOffsetHex64 = uint256ToHex64((9 + sigCount) * 32);
|
|
1387
|
-
const sOffsetHex64 = uint256ToHex64((8 + 2 * (1 + sigCount)) * 32);
|
|
1388
|
-
const vValues = sortedSigs.map((sig) => sig.v ?? 27);
|
|
1389
|
-
const rValues = sortedSigs.map((sig) => sig.r ?? sig.signatureDigest);
|
|
1390
|
-
const sValues = sortedSigs.map((sig) => sig.s ?? computeValidatorVoucherSignatureDigest(voucher.bridgeId, sig.signatureDigest, sig.validatorDid));
|
|
1391
|
-
const claimCalldata = `${claimSelector}${txHashHex64}${toWordHex64}${amountHex64}${expiresHex64}${digestHex64}${vOffsetHex64}${rOffsetHex64}${sOffsetHex64}${`${uint256ToHex64(sigCount)}${vValues.map((v) => uint256ToHex64(v)).join("")}`}${`${uint256ToHex64(sigCount)}${rValues.map((r) => r.slice(2)).join("")}`}${`${uint256ToHex64(sigCount)}${sValues.map((s) => s.slice(2)).join("")}`}`;
|
|
1392
|
-
const isUnlocked = !voucher.timelocked || input.nowUnixSeconds !== void 0 && input.nowUnixSeconds >= voucher.unlocksAtUnixSeconds;
|
|
1393
|
-
const claimPhase = !voucher.timelocked ? "IMMEDIATE_CLAIM" : isUnlocked ? "FINAL_UNLOCKED_CLAIM" : "TIMELOCK_INITIATION";
|
|
1394
|
-
return {
|
|
1395
|
-
action: "CLAIM_WITH_DIRECT_VOUCHER",
|
|
1396
|
-
hostPlatform: "ARC_BRIDGE_BLOCKLET",
|
|
1397
|
-
blockletDid: this.config.bridgeProposerDid,
|
|
1398
|
-
walletRequired: "STANDARD_WEB_EIP1193_ONLY",
|
|
1399
|
-
bridgeId: this.config.bridgeId,
|
|
1400
|
-
evmChainId: voucher.evmChainId,
|
|
1401
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1402
|
-
autoRelayerSponsoredOnOcap: false,
|
|
1403
|
-
timelockStatus: {
|
|
1404
|
-
timelocked: voucher.timelocked,
|
|
1405
|
-
unlocksAtUnixSeconds: voucher.unlocksAtUnixSeconds,
|
|
1406
|
-
isUnlocked,
|
|
1407
|
-
claimPhase
|
|
1408
|
-
},
|
|
1409
|
-
steps: [{
|
|
1410
|
-
stepId: "CLAIM_DIRECT_VOUCHER",
|
|
1411
|
-
description: "Claim 1:1 ERC-20 ABT with EIP-712 DirectWithdrawVoucher (Zero RollupBlock)",
|
|
1412
|
-
evmChainId: voucher.evmChainId,
|
|
1413
|
-
to: this.config.verifyingContractAddress,
|
|
1414
|
-
valueHex: "0x0",
|
|
1415
|
-
methodSignature: claimSig,
|
|
1416
|
-
functionSelector: claimSelector,
|
|
1417
|
-
calldataHex: claimCalldata,
|
|
1418
|
-
args: {
|
|
1419
|
-
ocapTxHash: voucher.ocapTxHash,
|
|
1420
|
-
to: voucher.recipientEvmAddress,
|
|
1421
|
-
amount: voucher.amount.toString(),
|
|
1422
|
-
expiresAt: voucher.expiresAtUnixSeconds,
|
|
1423
|
-
voucherDigest: voucher.voucherDigest,
|
|
1424
|
-
v: vValues,
|
|
1425
|
-
r: rValues,
|
|
1426
|
-
s: sValues,
|
|
1427
|
-
validatorSignatures: voucher.validatorSignatures.map((s) => ({ ...s }))
|
|
1428
|
-
}
|
|
1429
|
-
}]
|
|
1430
|
-
};
|
|
1431
|
-
}
|
|
1432
|
-
if (input.action === "PAY_FOR_OCAP_SERVICE") {
|
|
1433
|
-
const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
|
|
1434
|
-
if (!this.allowedChainSet.has(evmChainId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: evmChainId ${evmChainId} is not permitted by this bridge`);
|
|
1435
|
-
const orderId = assertBytes32Hex(input.orderId, "orderId");
|
|
1436
|
-
if (orderId === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: orderId cannot be zero bytes32");
|
|
1437
|
-
if (this.processedServiceOrderIds.has(orderId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: service orderId ${orderId} has already been paid`);
|
|
1438
|
-
const recipientDid = assertCleanString(input.recipientDid, "recipientDid");
|
|
1439
|
-
const serviceDid = assertCleanString(input.serviceDid, "serviceDid");
|
|
1440
|
-
const paymentTokenAddress = assertEvmAddress(input.paymentTokenAddress, "paymentTokenAddress");
|
|
1441
|
-
if (!this.allowedPaymentTokenSet.has(paymentTokenAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: paymentTokenAddress ${paymentTokenAddress} is not whitelisted for service payments`);
|
|
1442
|
-
if (input.userEvmAddress !== void 0) assertEvmAddress(input.userEvmAddress, "userEvmAddress");
|
|
1443
|
-
if (typeof input.amount !== "bigint" || input.amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: service payment amount must be > 0n");
|
|
1444
|
-
const amountHex64 = uint256ToHex64(input.amount);
|
|
1445
|
-
const approveCalldata = `${approveSelector}${gatewayWordHex64}${amountHex64}`;
|
|
1446
|
-
const paySig = "payForOcapService(bytes32,string,string,address,uint256)";
|
|
1447
|
-
const paySelector = computeSolidityFunctionSelector(paySig);
|
|
1448
|
-
const tokenWordHex64 = paymentTokenAddress.slice(2).padStart(64, "0");
|
|
1449
|
-
const encodedRecipientHex = encodeAbiDynamicUtf8String(recipientDid);
|
|
1450
|
-
const encodedServiceHex = encodeAbiDynamicUtf8String(serviceDid);
|
|
1451
|
-
const offset1Hex64 = uint256ToHex64(160);
|
|
1452
|
-
const offset2Hex64 = uint256ToHex64(160 + encodedRecipientHex.length / 2);
|
|
1453
|
-
const payCalldata = `${paySelector}${orderId.slice(2)}${offset1Hex64}${offset2Hex64}${tokenWordHex64}${amountHex64}${encodedRecipientHex}${encodedServiceHex}`;
|
|
1454
|
-
return {
|
|
1455
|
-
action: "PAY_FOR_OCAP_SERVICE",
|
|
1456
|
-
hostPlatform: "ARC_BRIDGE_BLOCKLET",
|
|
1457
|
-
blockletDid: this.config.bridgeProposerDid,
|
|
1458
|
-
walletRequired: "STANDARD_WEB_EIP1193_ONLY",
|
|
1459
|
-
bridgeId: this.config.bridgeId,
|
|
1460
|
-
evmChainId,
|
|
1461
|
-
verifyingContractAddress: this.config.verifyingContractAddress,
|
|
1462
|
-
autoRelayerSponsoredOnOcap: true,
|
|
1463
|
-
steps: [{
|
|
1464
|
-
stepId: "ERC20_APPROVE",
|
|
1465
|
-
description: "Approve service payment token to ArcEvmBridgeGateway",
|
|
1466
|
-
evmChainId,
|
|
1467
|
-
to: paymentTokenAddress,
|
|
1468
|
-
valueHex: "0x0",
|
|
1469
|
-
methodSignature: approveSig,
|
|
1470
|
-
functionSelector: approveSelector,
|
|
1471
|
-
calldataHex: approveCalldata,
|
|
1472
|
-
args: {
|
|
1473
|
-
spender: this.config.verifyingContractAddress,
|
|
1474
|
-
amount: input.amount.toString()
|
|
1475
|
-
}
|
|
1476
|
-
}, {
|
|
1477
|
-
stepId: "PAY_FOR_SERVICE",
|
|
1478
|
-
description: "Pay-Where-You-Are on EVM and auto-deliver service on OCAP",
|
|
1479
|
-
evmChainId,
|
|
1480
|
-
to: this.config.verifyingContractAddress,
|
|
1481
|
-
valueHex: "0x0",
|
|
1482
|
-
methodSignature: paySig,
|
|
1483
|
-
functionSelector: paySelector,
|
|
1484
|
-
calldataHex: payCalldata,
|
|
1485
|
-
args: {
|
|
1486
|
-
orderId,
|
|
1487
|
-
recipientDid,
|
|
1488
|
-
serviceDid,
|
|
1489
|
-
paymentTokenAddress,
|
|
1490
|
-
amount: input.amount.toString()
|
|
1491
|
-
}
|
|
1492
|
-
}]
|
|
1493
|
-
};
|
|
1494
|
-
}
|
|
1495
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: unsupported portal action");
|
|
1496
|
-
}
|
|
1497
|
-
/**
|
|
1498
|
-
* Cloudflare Workers / Durable Objects / ArcBridge Blocklet Edge Handler (`fetch` & `scheduled` entry point):
|
|
1499
|
-
* Verifies HMAC-SHA256 webhook authentication and anti-replay nonces for all mutating endpoints.
|
|
1500
|
-
*/
|
|
1501
|
-
handleCloudflareEdgeRequest(req) {
|
|
1502
|
-
if (req.method === "GET" && req.path === "/health") {
|
|
1503
|
-
const state = this.getReserveWatermarkState();
|
|
1504
|
-
return {
|
|
1505
|
-
status: 200,
|
|
1506
|
-
body: {
|
|
1507
|
-
ok: true,
|
|
1508
|
-
bridgeId: this.config.bridgeId,
|
|
1509
|
-
rollupAddress: this.config.rollupAddress,
|
|
1510
|
-
paused: state.paused,
|
|
1511
|
-
latestBlockHeight: state.latestBlockHeight,
|
|
1512
|
-
latestBlockHash: state.latestBlockHash,
|
|
1513
|
-
cumulativeDepositedAbt: state.cumulativeDepositedAbt.toString(),
|
|
1514
|
-
cumulativeWithdrawnAbt: state.cumulativeWithdrawnAbt.toString(),
|
|
1515
|
-
pendingWithdrawAbt: state.pendingWithdrawAbt.toString(),
|
|
1516
|
-
availableWithdrawReserveAbt: state.availableWithdrawReserveAbt.toString(),
|
|
1517
|
-
pendingWithdrawCount: state.pendingWithdrawCount,
|
|
1518
|
-
issuedDirectVoucherCount: state.issuedDirectVoucherCount,
|
|
1519
|
-
cancelledWithdrawCount: state.cancelledWithdrawCount
|
|
1520
|
-
}
|
|
1521
|
-
};
|
|
1522
|
-
}
|
|
1523
|
-
if (req.method === "GET" && req.path === "/portal/config") return {
|
|
1524
|
-
status: 200,
|
|
1525
|
-
body: {
|
|
1526
|
-
ok: true,
|
|
1527
|
-
portalConfig: this.getWebPortalConfig()
|
|
1528
|
-
}
|
|
1529
|
-
};
|
|
1530
|
-
const bodyJson = req.bodyJson ?? "";
|
|
1531
|
-
if (Buffer.byteLength(bodyJson, "utf8") > MAX_EDGE_WEBHOOK_BODY_BYTES) return {
|
|
1532
|
-
status: 413,
|
|
1533
|
-
body: {
|
|
1534
|
-
ok: false,
|
|
1535
|
-
error: "SimplifiedEvmBridge: request body exceeds maximum allowed size"
|
|
1536
|
-
}
|
|
1537
|
-
};
|
|
1538
|
-
if (req.method === "POST" && req.path === "/portal/build-tx") try {
|
|
1539
|
-
const parsed = JSON.parse(bodyJson || "{}");
|
|
1540
|
-
const action = String(parsed.action ?? "");
|
|
1541
|
-
let actionInput;
|
|
1542
|
-
if (action === "DEPOSIT_FOR_NATIVE_ABT") actionInput = {
|
|
1543
|
-
action: "DEPOSIT_FOR_NATIVE_ABT",
|
|
1544
|
-
evmChainId: String(parsed.evmChainId ?? ""),
|
|
1545
|
-
recipientDid: String(parsed.recipientDid ?? ""),
|
|
1546
|
-
amount: parseStrictUint256JsonValue(parsed.amount, "amount"),
|
|
1547
|
-
userEvmAddress: parsed.userEvmAddress !== void 0 ? String(parsed.userEvmAddress) : void 0
|
|
1548
|
-
};
|
|
1549
|
-
else if (action === "CLAIM_WITH_DIRECT_VOUCHER") {
|
|
1550
|
-
let resolvedNowUnixSeconds = req.nowUnixSeconds;
|
|
1551
|
-
if (parsed.nowUnixSeconds !== void 0) {
|
|
1552
|
-
if (typeof parsed.nowUnixSeconds !== "number" || !Number.isSafeInteger(parsed.nowUnixSeconds)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: nowUnixSeconds must be a positive integer");
|
|
1553
|
-
resolvedNowUnixSeconds = parsed.nowUnixSeconds;
|
|
1554
|
-
}
|
|
1555
|
-
actionInput = {
|
|
1556
|
-
action: "CLAIM_WITH_DIRECT_VOUCHER",
|
|
1557
|
-
ocapTxHash: String(parsed.ocapTxHash ?? ""),
|
|
1558
|
-
nowUnixSeconds: resolvedNowUnixSeconds
|
|
1559
|
-
};
|
|
1560
|
-
} else if (action === "PAY_FOR_OCAP_SERVICE") actionInput = {
|
|
1561
|
-
action: "PAY_FOR_OCAP_SERVICE",
|
|
1562
|
-
evmChainId: String(parsed.evmChainId ?? ""),
|
|
1563
|
-
orderId: String(parsed.orderId ?? ""),
|
|
1564
|
-
recipientDid: String(parsed.recipientDid ?? ""),
|
|
1565
|
-
serviceDid: String(parsed.serviceDid ?? ""),
|
|
1566
|
-
paymentTokenAddress: String(parsed.paymentTokenAddress ?? ""),
|
|
1567
|
-
amount: parseStrictUint256JsonValue(parsed.amount, "amount"),
|
|
1568
|
-
userEvmAddress: parsed.userEvmAddress !== void 0 ? String(parsed.userEvmAddress) : void 0
|
|
1569
|
-
};
|
|
1570
|
-
else throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: unsupported portal action ${action}`);
|
|
1571
|
-
return {
|
|
1572
|
-
status: 200,
|
|
1573
|
-
body: {
|
|
1574
|
-
ok: true,
|
|
1575
|
-
actionBundle: this.buildWebPortalActionBundle(actionInput)
|
|
1576
|
-
}
|
|
1577
|
-
};
|
|
1578
|
-
} catch (err) {
|
|
1579
|
-
return {
|
|
1580
|
-
status: 400,
|
|
1581
|
-
body: {
|
|
1582
|
-
ok: false,
|
|
1583
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1584
|
-
}
|
|
1585
|
-
};
|
|
1586
|
-
}
|
|
1587
|
-
if (req.method === "POST" && req.path === "/query/withdraw-voucher") try {
|
|
1588
|
-
const parsed = JSON.parse(bodyJson || "{}");
|
|
1589
|
-
const voucher = this.getDirectWithdrawVoucher(String(parsed.ocapTxHash ?? ""));
|
|
1590
|
-
return {
|
|
1591
|
-
status: 200,
|
|
1592
|
-
body: {
|
|
1593
|
-
ok: true,
|
|
1594
|
-
voucher: {
|
|
1595
|
-
...voucher,
|
|
1596
|
-
amount: voucher.amount.toString()
|
|
1597
|
-
}
|
|
1598
|
-
}
|
|
1599
|
-
};
|
|
1600
|
-
} catch (err) {
|
|
1601
|
-
return {
|
|
1602
|
-
status: 400,
|
|
1603
|
-
body: {
|
|
1604
|
-
ok: false,
|
|
1605
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1606
|
-
}
|
|
1607
|
-
};
|
|
1608
|
-
}
|
|
1609
|
-
if (req.method === "POST" && req.path === "/query/withdraw-proof") try {
|
|
1610
|
-
const parsed = JSON.parse(bodyJson || "{}");
|
|
1611
|
-
const bundle = this.generateWithdrawClaimProof(String(parsed.ocapTxHash ?? ""));
|
|
1612
|
-
return {
|
|
1613
|
-
status: 200,
|
|
1614
|
-
body: {
|
|
1615
|
-
ok: true,
|
|
1616
|
-
proofBundle: {
|
|
1617
|
-
...bundle,
|
|
1618
|
-
amount: bundle.amount.toString()
|
|
1619
|
-
}
|
|
1620
|
-
}
|
|
1621
|
-
};
|
|
1622
|
-
} catch (err) {
|
|
1623
|
-
return {
|
|
1624
|
-
status: 400,
|
|
1625
|
-
body: {
|
|
1626
|
-
ok: false,
|
|
1627
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1628
|
-
}
|
|
1629
|
-
};
|
|
1630
|
-
}
|
|
1631
|
-
const normalizedHeaders = {};
|
|
1632
|
-
for (const [k, v] of Object.entries(req.headers ?? {})) normalizedHeaders[k.toLowerCase()] = v;
|
|
1633
|
-
const sigHeader = normalizedHeaders["x-arc-bridge-signature"] ?? "";
|
|
1634
|
-
const tsHeader = normalizedHeaders["x-arc-bridge-timestamp"] ?? "";
|
|
1635
|
-
const rawNonceHeader = normalizedHeaders["x-arc-bridge-nonce"] ?? "";
|
|
1636
|
-
const nowUnixSeconds = req.nowUnixSeconds ?? Math.floor(Date.now() / 1e3);
|
|
1637
|
-
let nonceHeader = "";
|
|
1638
|
-
try {
|
|
1639
|
-
nonceHeader = assertCleanString(rawNonceHeader, "nonceHeader");
|
|
1640
|
-
} catch {
|
|
1641
|
-
nonceHeader = "";
|
|
1642
|
-
}
|
|
1643
|
-
const tsSeconds = Number(tsHeader);
|
|
1644
|
-
if (!Number.isSafeInteger(tsSeconds) || Math.abs(nowUnixSeconds - tsSeconds) > MAX_EDGE_WEBHOOK_SKEW_SECONDS || nonceHeader.length < 8 || nonceHeader.length > 128 || !/^[a-fA-F0-9]{64}$/.test(sigHeader)) return {
|
|
1645
|
-
status: 401,
|
|
1646
|
-
body: {
|
|
1647
|
-
ok: false,
|
|
1648
|
-
error: "SimplifiedEvmBridge: invalid or expired edge webhook authentication headers"
|
|
1649
|
-
}
|
|
1650
|
-
};
|
|
1651
|
-
for (const [oldNonce, oldTs] of this.processedWebhookNonces.entries()) if (nowUnixSeconds - oldTs > MAX_EDGE_WEBHOOK_SKEW_SECONDS * 2) this.processedWebhookNonces.delete(oldNonce);
|
|
1652
|
-
if (this.processedWebhookNonces.has(nonceHeader)) return {
|
|
1653
|
-
status: 401,
|
|
1654
|
-
body: {
|
|
1655
|
-
ok: false,
|
|
1656
|
-
error: "SimplifiedEvmBridge: duplicate webhook nonce replay rejected"
|
|
1657
|
-
}
|
|
1658
|
-
};
|
|
1659
|
-
if (this.processedWebhookNonces.size >= MAX_TRACKED_WEBHOOK_NONCES) return {
|
|
1660
|
-
status: 429,
|
|
1661
|
-
body: {
|
|
1662
|
-
ok: false,
|
|
1663
|
-
error: "SimplifiedEvmBridge: webhook nonce rate limit capacity reached"
|
|
1664
|
-
}
|
|
1665
|
-
};
|
|
1666
|
-
const expectedHmac = computeEdgeWebhookHmac(this.config.webhookHmacSecret, tsSeconds, nonceHeader, req.path, bodyJson);
|
|
1667
|
-
const sigBuf = Buffer.from(sigHeader.toLowerCase(), "hex");
|
|
1668
|
-
const expBuf = Buffer.from(expectedHmac.toLowerCase(), "hex");
|
|
1669
|
-
if (sigBuf.length !== expBuf.length || !(0, node_crypto.timingSafeEqual)(sigBuf, expBuf)) return {
|
|
1670
|
-
status: 401,
|
|
1671
|
-
body: {
|
|
1672
|
-
ok: false,
|
|
1673
|
-
error: "SimplifiedEvmBridge: webhook HMAC signature mismatch"
|
|
1674
|
-
}
|
|
1675
|
-
};
|
|
1676
|
-
try {
|
|
1677
|
-
const payload = JSON.parse(bodyJson || "{}");
|
|
1678
|
-
if (req.method === "POST" && req.path === "/webhook/evm-service-pay") {
|
|
1679
|
-
const instruction = this.ingestEvmServicePaymentEvent({
|
|
1680
|
-
evmChainId: String(payload.evmChainId ?? ""),
|
|
1681
|
-
evmTxHash: String(payload.evmTxHash ?? ""),
|
|
1682
|
-
logIndex: Number(payload.logIndex),
|
|
1683
|
-
confirmations: Number(payload.confirmations),
|
|
1684
|
-
reorged: Boolean(payload.reorged),
|
|
1685
|
-
orderId: String(payload.orderId ?? ""),
|
|
1686
|
-
payerEvmAddress: String(payload.payerEvmAddress ?? ""),
|
|
1687
|
-
recipientDid: String(payload.recipientDid ?? ""),
|
|
1688
|
-
serviceDid: String(payload.serviceDid ?? ""),
|
|
1689
|
-
paymentTokenAddress: String(payload.paymentTokenAddress ?? ""),
|
|
1690
|
-
amount: parseStrictUint256JsonValue(payload.amount, "amount"),
|
|
1691
|
-
deliverableNftDid: payload.deliverableNftDid ? String(payload.deliverableNftDid) : void 0
|
|
1692
|
-
});
|
|
1693
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1694
|
-
return {
|
|
1695
|
-
status: 200,
|
|
1696
|
-
body: {
|
|
1697
|
-
ok: true,
|
|
1698
|
-
instructionId: instruction.instructionId,
|
|
1699
|
-
depositProofDigest: instruction.depositProofDigest,
|
|
1700
|
-
paidAmount: instruction.paidAmount.toString()
|
|
1701
|
-
}
|
|
1702
|
-
};
|
|
1703
|
-
}
|
|
1704
|
-
if (req.method === "POST" && req.path === "/webhook/evm-abt-deposit") {
|
|
1705
|
-
const instruction = this.ingestEvmAbtDepositEvent({
|
|
1706
|
-
evmChainId: String(payload.evmChainId ?? ""),
|
|
1707
|
-
evmTxHash: String(payload.evmTxHash ?? ""),
|
|
1708
|
-
logIndex: Number(payload.logIndex),
|
|
1709
|
-
confirmations: Number(payload.confirmations),
|
|
1710
|
-
reorged: Boolean(payload.reorged),
|
|
1711
|
-
depositorEvmAddress: String(payload.depositorEvmAddress ?? ""),
|
|
1712
|
-
recipientDid: String(payload.recipientDid ?? ""),
|
|
1713
|
-
tokenAddress: String(payload.tokenAddress ?? ""),
|
|
1714
|
-
amount: parseStrictUint256JsonValue(payload.amount, "amount"),
|
|
1715
|
-
actualFee: payload.actualFee !== void 0 ? parseStrictUint256JsonValue(payload.actualFee, "actualFee") : 0n
|
|
1716
|
-
});
|
|
1717
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1718
|
-
return {
|
|
1719
|
-
status: 200,
|
|
1720
|
-
body: {
|
|
1721
|
-
ok: true,
|
|
1722
|
-
instructionId: instruction.instructionId,
|
|
1723
|
-
value: instruction.value.toString(),
|
|
1724
|
-
cumulativeDepositedAbt: instruction.cumulativeDepositedAbt.toString()
|
|
1725
|
-
}
|
|
1726
|
-
};
|
|
1727
|
-
}
|
|
1728
|
-
if (req.method === "POST" && req.path === "/webhook/ocap-abt-withdraw-voucher") {
|
|
1729
|
-
const issuedAtUnixSeconds = Number(payload.issuedAtUnixSeconds ?? nowUnixSeconds);
|
|
1730
|
-
const expiresAtUnixSeconds = Number(payload.expiresAtUnixSeconds ?? nowUnixSeconds + 86400);
|
|
1731
|
-
if (!Number.isSafeInteger(issuedAtUnixSeconds) || Math.abs(nowUnixSeconds - issuedAtUnixSeconds) > MAX_EDGE_WEBHOOK_SKEW_SECONDS || expiresAtUnixSeconds <= nowUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: voucher issuedAtUnixSeconds/expiresAtUnixSeconds outside valid edge window");
|
|
1732
|
-
const voucher = this.issueDirectWithdrawVoucher({
|
|
1733
|
-
evmChainId: String(payload.evmChainId ?? ""),
|
|
1734
|
-
ocapTxHash: String(payload.ocapTxHash ?? ""),
|
|
1735
|
-
fromDid: String(payload.fromDid ?? ""),
|
|
1736
|
-
recipientEvmAddress: String(payload.recipientEvmAddress ?? ""),
|
|
1737
|
-
amount: parseStrictUint256JsonValue(payload.amount, "amount"),
|
|
1738
|
-
issuedAtUnixSeconds,
|
|
1739
|
-
expiresAtUnixSeconds,
|
|
1740
|
-
validatorSignatures: Array.isArray(payload.validatorSignatures) ? payload.validatorSignatures : []
|
|
1741
|
-
});
|
|
1742
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1743
|
-
return {
|
|
1744
|
-
status: 200,
|
|
1745
|
-
body: {
|
|
1746
|
-
ok: true,
|
|
1747
|
-
voucher: {
|
|
1748
|
-
...voucher,
|
|
1749
|
-
amount: voucher.amount.toString()
|
|
1750
|
-
}
|
|
1751
|
-
}
|
|
1752
|
-
};
|
|
1753
|
-
}
|
|
1754
|
-
if (req.method === "POST" && req.path === "/webhook/guardian-pause") {
|
|
1755
|
-
const res = this.setBridgePaused({
|
|
1756
|
-
guardianDid: String(payload.guardianDid ?? ""),
|
|
1757
|
-
paused: Boolean(payload.paused)
|
|
1758
|
-
});
|
|
1759
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1760
|
-
return {
|
|
1761
|
-
status: 200,
|
|
1762
|
-
body: {
|
|
1763
|
-
ok: true,
|
|
1764
|
-
paused: res.paused
|
|
1765
|
-
}
|
|
1766
|
-
};
|
|
1767
|
-
}
|
|
1768
|
-
if (req.method === "POST" && req.path === "/webhook/guardian-cancel-withdraw") {
|
|
1769
|
-
const res = this.cancelTimelockedWithdraw({
|
|
1770
|
-
guardianDid: String(payload.guardianDid ?? ""),
|
|
1771
|
-
ocapTxHash: String(payload.ocapTxHash ?? ""),
|
|
1772
|
-
nowUnixSeconds
|
|
1773
|
-
});
|
|
1774
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1775
|
-
return {
|
|
1776
|
-
status: 200,
|
|
1777
|
-
body: {
|
|
1778
|
-
ok: true,
|
|
1779
|
-
cancelledTxHash: res.cancelledTxHash,
|
|
1780
|
-
refundedReserveAbt: res.refundedReserveAbt.toString()
|
|
1781
|
-
}
|
|
1782
|
-
};
|
|
1783
|
-
}
|
|
1784
|
-
if (req.method === "POST" && req.path === "/webhook/ocap-abt-withdraw") {
|
|
1785
|
-
const res = this.enqueueOcapAbtWithdraw({
|
|
1786
|
-
ocapTxHash: String(payload.ocapTxHash ?? ""),
|
|
1787
|
-
fromDid: String(payload.fromDid ?? ""),
|
|
1788
|
-
recipientEvmAddress: String(payload.recipientEvmAddress ?? ""),
|
|
1789
|
-
amount: parseStrictUint256JsonValue(payload.amount, "amount")
|
|
1790
|
-
});
|
|
1791
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1792
|
-
return {
|
|
1793
|
-
status: 200,
|
|
1794
|
-
body: {
|
|
1795
|
-
ok: true,
|
|
1796
|
-
queuedCount: res.queuedCount,
|
|
1797
|
-
pendingWithdrawTotal: res.pendingWithdrawTotal.toString()
|
|
1798
|
-
}
|
|
1799
|
-
};
|
|
1800
|
-
}
|
|
1801
|
-
if (req.method === "POST" && req.path === "/cron/seal-withdraw-block") {
|
|
1802
|
-
const block = this.sealRollupWithdrawBlock({
|
|
1803
|
-
validatorSignatures: Array.isArray(payload.validatorSignatures) ? payload.validatorSignatures : [],
|
|
1804
|
-
sealedAtUnixSeconds: nowUnixSeconds
|
|
1805
|
-
});
|
|
1806
|
-
this.processedWebhookNonces.set(nonceHeader, tsSeconds);
|
|
1807
|
-
return {
|
|
1808
|
-
status: 200,
|
|
1809
|
-
body: {
|
|
1810
|
-
ok: true,
|
|
1811
|
-
height: block.height,
|
|
1812
|
-
blockHash: block.blockHash,
|
|
1813
|
-
merkleRoot: block.merkleRoot,
|
|
1814
|
-
txsHash: block.txsHash
|
|
1815
|
-
}
|
|
1816
|
-
};
|
|
1817
|
-
}
|
|
1818
|
-
return {
|
|
1819
|
-
status: 404,
|
|
1820
|
-
body: {
|
|
1821
|
-
ok: false,
|
|
1822
|
-
error: `Unsupported route ${req.method} ${req.path}`
|
|
1823
|
-
}
|
|
1824
|
-
};
|
|
1825
|
-
} catch (err) {
|
|
1826
|
-
return {
|
|
1827
|
-
status: 400,
|
|
1828
|
-
body: {
|
|
1829
|
-
ok: false,
|
|
1830
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1831
|
-
}
|
|
1832
|
-
};
|
|
1833
|
-
}
|
|
1834
|
-
}
|
|
1835
|
-
/**
|
|
1836
|
-
* Exports a JSON-serializable state snapshot for Cloudflare Durable Object storage (`ctx.storage.put`).
|
|
1837
|
-
*/
|
|
1838
|
-
exportDurableStateSnapshot() {
|
|
1839
|
-
return {
|
|
1840
|
-
schemaVersion: 1,
|
|
1841
|
-
config: {
|
|
1842
|
-
...this.config,
|
|
1843
|
-
minDepositAmount: this.config.minDepositAmount.toString(),
|
|
1844
|
-
maxDepositAmount: this.config.maxDepositAmount.toString(),
|
|
1845
|
-
minWithdrawAmount: this.config.minWithdrawAmount.toString(),
|
|
1846
|
-
maxWithdrawAmount: this.config.maxWithdrawAmount.toString(),
|
|
1847
|
-
maxDailyWithdrawAbt: this.config.maxDailyWithdrawAbt.toString(),
|
|
1848
|
-
largeWithdrawTimelockThresholdAbt: this.config.largeWithdrawTimelockThresholdAbt.toString()
|
|
1849
|
-
},
|
|
1850
|
-
paused: this.paused,
|
|
1851
|
-
latestBlockHeight: this.latestBlockHeight,
|
|
1852
|
-
latestBlockHash: this.latestBlockHash,
|
|
1853
|
-
cumulativeDepositedAbt: this.cumulativeDepositedAbt.toString(),
|
|
1854
|
-
cumulativeWithdrawnAbt: this.cumulativeWithdrawnAbt.toString(),
|
|
1855
|
-
processedEventKeys: Array.from(this.processedEventKeys),
|
|
1856
|
-
processedServiceOrderIds: Array.from(this.processedServiceOrderIds),
|
|
1857
|
-
processedWithdrawTxHashes: Array.from(this.processedWithdrawTxHashes),
|
|
1858
|
-
cancelledWithdrawTxHashes: Array.from(this.cancelledWithdrawTxHashes),
|
|
1859
|
-
dailyWithdrawnByDay: Array.from(this.dailyWithdrawnByDay.entries()).map(([dayBucket, withdrawnAbt]) => ({
|
|
1860
|
-
dayBucket,
|
|
1861
|
-
withdrawnAbt: withdrawnAbt.toString()
|
|
1862
|
-
})),
|
|
1863
|
-
processedWebhookNonces: Array.from(this.processedWebhookNonces.entries()).map(([nonce, timestampSeconds]) => ({
|
|
1864
|
-
nonce,
|
|
1865
|
-
timestampSeconds
|
|
1866
|
-
})),
|
|
1867
|
-
pendingWithdrawQueue: this.pendingWithdrawQueue.map((item) => ({
|
|
1868
|
-
...item,
|
|
1869
|
-
amount: item.amount.toString()
|
|
1870
|
-
})),
|
|
1871
|
-
sealedBlocks: Array.from(this.sealedBlocks.values()).map((b) => ({
|
|
1872
|
-
...b,
|
|
1873
|
-
withdrawTxs: b.withdrawTxs.map((tx) => ({
|
|
1874
|
-
...tx,
|
|
1875
|
-
amount: tx.amount.toString()
|
|
1876
|
-
}))
|
|
1877
|
-
})),
|
|
1878
|
-
issuedDirectVouchers: Array.from(this.issuedDirectVouchers.values()).map((v) => ({
|
|
1879
|
-
...v,
|
|
1880
|
-
amount: v.amount.toString()
|
|
1881
|
-
}))
|
|
1882
|
-
};
|
|
1883
|
-
}
|
|
1884
|
-
/**
|
|
1885
|
-
* Restores an `OcapSimplifiedEvmBridgeNode` instance from a Cloudflare Durable Object state snapshot.
|
|
1886
|
-
* Enforces full Red-Team conservation of value, replay-set synchronization, block hash linkage, and
|
|
1887
|
-
* direct voucher EIP-712 signature verification (`RT-1241-1`).
|
|
1888
|
-
*/
|
|
1889
|
-
static fromDurableStateSnapshot(snapshot) {
|
|
1890
|
-
if (!snapshot || snapshot.schemaVersion !== 1 || !snapshot.config) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid durable state snapshot");
|
|
1891
|
-
const node = new OcapSimplifiedEvmBridgeNode({
|
|
1892
|
-
...snapshot.config,
|
|
1893
|
-
minDepositAmount: parseStrictUint256JsonValue(snapshot.config.minDepositAmount, "snapshot.minDepositAmount"),
|
|
1894
|
-
maxDepositAmount: parseStrictUint256JsonValue(snapshot.config.maxDepositAmount, "snapshot.maxDepositAmount"),
|
|
1895
|
-
minWithdrawAmount: parseStrictUint256JsonValue(snapshot.config.minWithdrawAmount, "snapshot.minWithdrawAmount"),
|
|
1896
|
-
maxWithdrawAmount: parseStrictUint256JsonValue(snapshot.config.maxWithdrawAmount, "snapshot.maxWithdrawAmount"),
|
|
1897
|
-
maxDailyWithdrawAbt: snapshot.config.maxDailyWithdrawAbt !== void 0 ? parseStrictUint256JsonValue(snapshot.config.maxDailyWithdrawAbt, "snapshot.maxDailyWithdrawAbt") : void 0,
|
|
1898
|
-
largeWithdrawTimelockThresholdAbt: snapshot.config.largeWithdrawTimelockThresholdAbt !== void 0 ? parseStrictUint256JsonValue(snapshot.config.largeWithdrawTimelockThresholdAbt, "snapshot.largeWithdrawTimelockThresholdAbt") : void 0
|
|
1899
|
-
});
|
|
1900
|
-
node.paused = Boolean(snapshot.paused);
|
|
1901
|
-
if (!Number.isSafeInteger(snapshot.latestBlockHeight) || snapshot.latestBlockHeight < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot.latestBlockHeight");
|
|
1902
|
-
node.latestBlockHeight = snapshot.latestBlockHeight;
|
|
1903
|
-
node.latestBlockHash = assertBytes32Hex(snapshot.latestBlockHash, "snapshot.latestBlockHash");
|
|
1904
|
-
node.cumulativeDepositedAbt = parseStrictUint256JsonValue(snapshot.cumulativeDepositedAbt, "snapshot.cumulativeDepositedAbt");
|
|
1905
|
-
node.cumulativeWithdrawnAbt = parseStrictUint256JsonValue(snapshot.cumulativeWithdrawnAbt, "snapshot.cumulativeWithdrawnAbt");
|
|
1906
|
-
for (const k of snapshot.processedEventKeys) node.processedEventKeys.add(assertCleanString(k, "snapshot.eventKey"));
|
|
1907
|
-
for (const id of snapshot.processedServiceOrderIds) {
|
|
1908
|
-
const cleanId = assertBytes32Hex(id, "snapshot.orderId");
|
|
1909
|
-
if (cleanId === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot orderId cannot be zero bytes32");
|
|
1910
|
-
node.processedServiceOrderIds.add(cleanId);
|
|
1911
|
-
}
|
|
1912
|
-
for (const txHash of snapshot.processedWithdrawTxHashes) {
|
|
1913
|
-
const cleanHash = assertBytes32Hex(txHash, "snapshot.withdrawTxHash");
|
|
1914
|
-
if (cleanHash === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot withdrawTxHash cannot be zero bytes32");
|
|
1915
|
-
node.processedWithdrawTxHashes.add(cleanHash);
|
|
1916
|
-
}
|
|
1917
|
-
for (const txHash of snapshot.cancelledWithdrawTxHashes ?? []) {
|
|
1918
|
-
const cleanHash = assertBytes32Hex(txHash, "snapshot.cancelledWithdrawTxHash");
|
|
1919
|
-
node.cancelledWithdrawTxHashes.add(cleanHash);
|
|
1920
|
-
}
|
|
1921
|
-
for (const entry of snapshot.dailyWithdrawnByDay ?? []) {
|
|
1922
|
-
if (!Number.isSafeInteger(entry.dayBucket) || entry.dayBucket < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot dayBucket");
|
|
1923
|
-
if (node.dailyWithdrawnByDay.has(entry.dayBucket)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: duplicate snapshot dayBucket");
|
|
1924
|
-
const withdrawnAbt = parseStrictUint256JsonValue(entry.withdrawnAbt, "snapshot.dailyWithdrawnAbt");
|
|
1925
|
-
if (withdrawnAbt <= 0n || withdrawnAbt > node.config.maxDailyWithdrawAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot dailyWithdrawnAbt outside valid range (1..maxDailyWithdrawAbt)");
|
|
1926
|
-
node.dailyWithdrawnByDay.set(entry.dayBucket, withdrawnAbt);
|
|
1927
|
-
}
|
|
1928
|
-
for (const entry of snapshot.processedWebhookNonces ?? []) {
|
|
1929
|
-
const cleanNonce = assertCleanString(entry.nonce, "snapshot.nonce");
|
|
1930
|
-
if (!Number.isSafeInteger(entry.timestampSeconds) || entry.timestampSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid snapshot nonce timestamp");
|
|
1931
|
-
node.processedWebhookNonces.set(cleanNonce, entry.timestampSeconds);
|
|
1932
|
-
}
|
|
1933
|
-
const seenWithdrawTxsAcrossCollections = /* @__PURE__ */ new Set();
|
|
1934
|
-
const assertValidSnapshotWithdrawAmount = (amt, label) => {
|
|
1935
|
-
if (amt < node.config.minWithdrawAmount || amt > node.config.maxWithdrawAmount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: ${label} (${amt}) outside configured withdraw bounds`);
|
|
1936
|
-
};
|
|
1937
|
-
const registerCollectionTxHash = (rawHash, label) => {
|
|
1938
|
-
const cleanHash = assertBytes32Hex(rawHash, label);
|
|
1939
|
-
if (cleanHash === ZERO_BYTES32_HASH) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: ${label} cannot be zero bytes32`);
|
|
1940
|
-
if (seenWithdrawTxsAcrossCollections.has(cleanHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: duplicate withdraw tx ${cleanHash} across snapshot collections`);
|
|
1941
|
-
if (!node.processedWithdrawTxHashes.has(cleanHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot withdraw tx ${cleanHash} missing from processedWithdrawTxHashes`);
|
|
1942
|
-
seenWithdrawTxsAcrossCollections.add(cleanHash);
|
|
1943
|
-
return cleanHash;
|
|
1944
|
-
};
|
|
1945
|
-
let pendingTotal = 0n;
|
|
1946
|
-
for (const item of snapshot.pendingWithdrawQueue) {
|
|
1947
|
-
const cleanTxHash = registerCollectionTxHash(item.ocapTxHash, "snapshot.pending.ocapTxHash");
|
|
1948
|
-
const amount = parseStrictUint256JsonValue(item.amount, "snapshot.pending.amount");
|
|
1949
|
-
assertValidSnapshotWithdrawAmount(amount, "snapshot.pending.amount");
|
|
1950
|
-
pendingTotal += amount;
|
|
1951
|
-
node.pendingWithdrawQueue.push({
|
|
1952
|
-
ocapTxHash: cleanTxHash,
|
|
1953
|
-
fromDid: assertCleanString(item.fromDid, "snapshot.pending.fromDid"),
|
|
1954
|
-
recipientEvmAddress: assertEvmAddress(item.recipientEvmAddress, "snapshot.pending.recipientEvmAddress"),
|
|
1955
|
-
amount
|
|
1956
|
-
});
|
|
1957
|
-
}
|
|
1958
|
-
let sealedTotal = 0n;
|
|
1959
|
-
const expectedDailyTotals = /* @__PURE__ */ new Map();
|
|
1960
|
-
const addExpectedDailyWithdraw = (unixSeconds, amt, label) => {
|
|
1961
|
-
if (!Number.isSafeInteger(unixSeconds) || unixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: invalid ${label} timestamp`);
|
|
1962
|
-
const dayBucket = Math.floor(unixSeconds / 86400);
|
|
1963
|
-
const next = (expectedDailyTotals.get(dayBucket) ?? 0n) + amt;
|
|
1964
|
-
if (next > node.config.maxDailyWithdrawAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot dayBucket ${dayBucket} withdraw total (${next}) exceeds maxDailyWithdrawAbt (${node.config.maxDailyWithdrawAbt})`);
|
|
1965
|
-
expectedDailyTotals.set(dayBucket, next);
|
|
1966
|
-
};
|
|
1967
|
-
let expectedPrevHash = node.config.genesisBlockHash;
|
|
1968
|
-
const sortedBlocks = [...snapshot.sealedBlocks].sort((a, b) => a.height - b.height);
|
|
1969
|
-
if (sortedBlocks.length !== node.latestBlockHeight) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: snapshot sealedBlocks count does not match latestBlockHeight");
|
|
1970
|
-
for (let idx = 0; idx < sortedBlocks.length; idx++) {
|
|
1971
|
-
const b = sortedBlocks[idx];
|
|
1972
|
-
const expectedHeight = idx + 1;
|
|
1973
|
-
if (b.height !== expectedHeight) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: non-contiguous sealed block height ${b.height} (expected ${expectedHeight})`);
|
|
1974
|
-
if (!Array.isArray(b.withdrawTxs) || b.withdrawTxs.length === 0 || b.withdrawTxs.length > node.config.maxBlockSize) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid sealed block withdrawTxs count");
|
|
1975
|
-
let blockBatchTotal = 0n;
|
|
1976
|
-
const withdrawTxs = b.withdrawTxs.map((tx) => {
|
|
1977
|
-
const cleanTxHash = registerCollectionTxHash(tx.ocapTxHash, "snapshot.sealed.ocapTxHash");
|
|
1978
|
-
const amount = parseStrictUint256JsonValue(tx.amount, "snapshot.sealed.amount");
|
|
1979
|
-
assertValidSnapshotWithdrawAmount(amount, "snapshot.sealed.amount");
|
|
1980
|
-
sealedTotal += amount;
|
|
1981
|
-
blockBatchTotal += amount;
|
|
1982
|
-
return {
|
|
1983
|
-
ocapTxHash: cleanTxHash,
|
|
1984
|
-
fromDid: assertCleanString(tx.fromDid, "snapshot.sealed.fromDid"),
|
|
1985
|
-
recipientEvmAddress: assertEvmAddress(tx.recipientEvmAddress, "snapshot.sealed.recipientEvmAddress"),
|
|
1986
|
-
amount
|
|
1987
|
-
};
|
|
1988
|
-
});
|
|
1989
|
-
addExpectedDailyWithdraw(b.sealedAtUnixSeconds, blockBatchTotal, "snapshot.sealed.sealedAtUnixSeconds");
|
|
1990
|
-
const previousHash = assertBytes32Hex(b.previousHash, "snapshot.sealed.previousHash");
|
|
1991
|
-
if (previousHash !== expectedPrevHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} previousHash mismatch`);
|
|
1992
|
-
const merkleRoot = assertBytes32Hex(b.merkleRoot, "snapshot.sealed.merkleRoot");
|
|
1993
|
-
const txsHash = assertBytes32Hex(b.txsHash, "snapshot.sealed.txsHash");
|
|
1994
|
-
const blockHash = assertBytes32Hex(b.blockHash, "snapshot.sealed.blockHash");
|
|
1995
|
-
const computedTree = buildEvmBridgeMerkleTree(withdrawTxs);
|
|
1996
|
-
const computedTxsHash = computeEvmBridgeTxsHash(withdrawTxs.map((tx) => tx.ocapTxHash));
|
|
1997
|
-
const computedBlockHash = computeEvmBridgeBlockHash({
|
|
1998
|
-
height: b.height,
|
|
1999
|
-
previousHash,
|
|
2000
|
-
merkleRoot: computedTree.merkleRoot,
|
|
2001
|
-
txsHash: computedTxsHash
|
|
2002
|
-
});
|
|
2003
|
-
if (merkleRoot !== computedTree.merkleRoot || txsHash !== computedTxsHash || blockHash !== computedBlockHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} cryptographic header verification failed`);
|
|
2004
|
-
if (!Array.isArray(b.validatorSigners) || b.validatorSigners.length < node.config.minValidatorSignatures) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} validatorSigners quorum not met`);
|
|
2005
|
-
const seenBlockSigners = /* @__PURE__ */ new Set();
|
|
2006
|
-
for (const signerDid of b.validatorSigners) {
|
|
2007
|
-
const cleanSigner = assertCleanString(signerDid, "snapshot.sealed.validatorSigner");
|
|
2008
|
-
if (!node.validatorSet.has(cleanSigner) || seenBlockSigners.has(cleanSigner)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: sealed block ${b.height} contains unauthorized or duplicate validatorSigner`);
|
|
2009
|
-
seenBlockSigners.add(cleanSigner);
|
|
2010
|
-
}
|
|
2011
|
-
const sealed = {
|
|
2012
|
-
height: b.height,
|
|
2013
|
-
previousHash,
|
|
2014
|
-
merkleRoot,
|
|
2015
|
-
txsHash,
|
|
2016
|
-
blockHash,
|
|
2017
|
-
withdrawTxs,
|
|
2018
|
-
validatorSigners: [...b.validatorSigners],
|
|
2019
|
-
sealedAtUnixSeconds: b.sealedAtUnixSeconds
|
|
2020
|
-
};
|
|
2021
|
-
node.sealedBlocks.set(sealed.height, sealed);
|
|
2022
|
-
for (const tx of withdrawTxs) node.withdrawTxToBlockHeight.set(tx.ocapTxHash, sealed.height);
|
|
2023
|
-
expectedPrevHash = blockHash;
|
|
2024
|
-
}
|
|
2025
|
-
if (node.latestBlockHash !== expectedPrevHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot latestBlockHash does not match tip of sealedBlocks");
|
|
2026
|
-
let voucherTotal = 0n;
|
|
2027
|
-
const seenCancelledVouchers = /* @__PURE__ */ new Set();
|
|
2028
|
-
for (const v of snapshot.issuedDirectVouchers ?? []) {
|
|
2029
|
-
const cleanTxHash = registerCollectionTxHash(v.ocapTxHash, "snapshot.voucher.ocapTxHash");
|
|
2030
|
-
const amount = parseStrictUint256JsonValue(v.amount, "snapshot.voucher.amount");
|
|
2031
|
-
assertValidSnapshotWithdrawAmount(amount, "snapshot.voucher.amount");
|
|
2032
|
-
const isCancelledFlag = Boolean(v.cancelled);
|
|
2033
|
-
if (isCancelledFlag !== node.cancelledWithdrawTxHashes.has(cleanTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot voucher ${cleanTxHash} cancelled state desynchronized from cancelledWithdrawTxHashes`);
|
|
2034
|
-
const expectedTimelocked = amount >= node.config.largeWithdrawTimelockThresholdAbt;
|
|
2035
|
-
const expectedUnlocksAt = expectedTimelocked ? v.issuedAtUnixSeconds + node.config.timelockDelaySeconds : v.issuedAtUnixSeconds;
|
|
2036
|
-
if (Boolean(v.timelocked) !== expectedTimelocked || v.unlocksAtUnixSeconds !== expectedUnlocksAt || expectedTimelocked && v.expiresAtUnixSeconds <= expectedUnlocksAt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot voucher ${cleanTxHash} timelock metadata tampered`);
|
|
2037
|
-
if (isCancelledFlag) {
|
|
2038
|
-
if (!expectedTimelocked) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: non-timelocked voucher ${cleanTxHash} cannot be marked cancelled in snapshot`);
|
|
2039
|
-
seenCancelledVouchers.add(cleanTxHash);
|
|
2040
|
-
} else {
|
|
2041
|
-
voucherTotal += amount;
|
|
2042
|
-
addExpectedDailyWithdraw(v.issuedAtUnixSeconds, amount, "snapshot.voucher.issuedAtUnixSeconds");
|
|
2043
|
-
}
|
|
2044
|
-
const voucherDigest = assertBytes32Hex(v.voucherDigest, "snapshot.voucher.voucherDigest");
|
|
2045
|
-
const restoredVoucher = {
|
|
2046
|
-
voucherDigest,
|
|
2047
|
-
eip712DomainSeparator: assertBytes32Hex(v.eip712DomainSeparator, "snapshot.voucher.eip712DomainSeparator"),
|
|
2048
|
-
eip712StructHash: assertBytes32Hex(v.eip712StructHash, "snapshot.voucher.eip712StructHash"),
|
|
2049
|
-
verifyingContractAddress: assertEvmAddress(v.verifyingContractAddress, "snapshot.voucher.verifyingContractAddress"),
|
|
2050
|
-
bridgeId: assertCleanString(v.bridgeId, "snapshot.voucher.bridgeId"),
|
|
2051
|
-
evmChainId: assertCleanString(v.evmChainId, "snapshot.voucher.evmChainId"),
|
|
2052
|
-
ocapTxHash: cleanTxHash,
|
|
2053
|
-
fromDid: assertCleanString(v.fromDid, "snapshot.voucher.fromDid"),
|
|
2054
|
-
recipientEvmAddress: assertEvmAddress(v.recipientEvmAddress, "snapshot.voucher.recipientEvmAddress"),
|
|
2055
|
-
amount,
|
|
2056
|
-
issuedAtUnixSeconds: v.issuedAtUnixSeconds,
|
|
2057
|
-
expiresAtUnixSeconds: v.expiresAtUnixSeconds,
|
|
2058
|
-
timelocked: expectedTimelocked,
|
|
2059
|
-
unlocksAtUnixSeconds: expectedUnlocksAt,
|
|
2060
|
-
cancelled: isCancelledFlag,
|
|
2061
|
-
validatorSigners: [...v.validatorSigners],
|
|
2062
|
-
validatorSignatures: v.validatorSignatures.map((s) => {
|
|
2063
|
-
const restoredSig = {
|
|
2064
|
-
validatorDid: assertCleanString(s.validatorDid, "snapshot.voucher.validatorDid"),
|
|
2065
|
-
signatureDigest: assertBytes32Hex(s.signatureDigest, "snapshot.voucher.signatureDigest")
|
|
2066
|
-
};
|
|
2067
|
-
if (s.v !== void 0 && s.r && s.s) {
|
|
2068
|
-
restoredSig.evmSignerAddress = ecrecoverEvmAddress(voucherDigest, s.v, s.r, s.s);
|
|
2069
|
-
restoredSig.v = s.v;
|
|
2070
|
-
restoredSig.r = assertBytes32Hex(s.r, "snapshot.voucher.r");
|
|
2071
|
-
restoredSig.s = assertBytes32Hex(s.s, "snapshot.voucher.s");
|
|
2072
|
-
}
|
|
2073
|
-
return restoredSig;
|
|
2074
|
-
})
|
|
2075
|
-
};
|
|
2076
|
-
if (!verifyDirectWithdrawVoucher({
|
|
2077
|
-
...restoredVoucher,
|
|
2078
|
-
cancelled: false
|
|
2079
|
-
}, {
|
|
2080
|
-
bridgeId: node.config.bridgeId,
|
|
2081
|
-
verifyingContractAddress: node.config.verifyingContractAddress,
|
|
2082
|
-
allowedEvmChainIds: node.config.allowedEvmChainIds,
|
|
2083
|
-
validatorDids: node.config.validatorDids,
|
|
2084
|
-
minValidatorSignatures: node.config.minValidatorSignatures
|
|
2085
|
-
})) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: restored direct withdraw voucher ${cleanTxHash} failed cryptographic verification`);
|
|
2086
|
-
node.issuedDirectVouchers.set(cleanTxHash, restoredVoucher);
|
|
2087
|
-
}
|
|
2088
|
-
if (seenCancelledVouchers.size !== node.cancelledWithdrawTxHashes.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot cancelledWithdrawTxHashes contains orphan tx hashes");
|
|
2089
|
-
if (node.dailyWithdrawnByDay.size !== expectedDailyTotals.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: snapshot dailyWithdrawnByDay desynchronized from sealed blocks and active vouchers");
|
|
2090
|
-
for (const [dayBucket, expectedAmt] of expectedDailyTotals.entries()) if (node.dailyWithdrawnByDay.get(dayBucket) !== expectedAmt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot dailyWithdrawnByDay mismatch for dayBucket ${dayBucket}`);
|
|
2091
|
-
if (sealedTotal + voucherTotal !== node.cumulativeWithdrawnAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot cumulativeWithdrawnAbt (${node.cumulativeWithdrawnAbt}) does not match sealedTotal + voucherTotal (${sealedTotal + voucherTotal})`);
|
|
2092
|
-
if (node.cumulativeWithdrawnAbt + pendingTotal > node.cumulativeDepositedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: snapshot violates Canary net-inflow reserve watermark: cumulativeWithdrawnAbt + pendingTotal (${node.cumulativeWithdrawnAbt + pendingTotal}) > cumulativeDepositedAbt (${node.cumulativeDepositedAbt})`);
|
|
2093
|
-
return node;
|
|
2094
|
-
}
|
|
2095
|
-
};
|
|
2096
|
-
/**
|
|
2097
|
-
* Computes the deterministic EVM-side Two-Phase Challenge Hash (`seq: 500`):
|
|
2098
|
-
* When a large withdrawal (`amount >= largeWithdrawThreshold`) is submitted to the Ethereum contract
|
|
2099
|
-
* in Phase 1, the contract does NOT release funds. Instead, it records the pending withdrawal state
|
|
2100
|
-
* and computes a fresh `challengeHash` incorporating Ethereum on-chain state (`phase1BlockNumber`):
|
|
2101
|
-
* `keccak256(abi.encode(TWO_PHASE_CHALLENGE_TYPEHASH, chainId, verifyingContract, ocapTxHash, recipient, amount, phase1BlockNumber))`
|
|
2102
|
-
* Because `phase1BlockNumber` is determined on Ethereum when Phase 1 is mined, an attacker with stolen
|
|
2103
|
-
* Phase-1 hot keys (`Key_Hot`) cannot pre-forge Phase 2 offline and must expose Phase 1 on Ethereum first,
|
|
2104
|
-
* after which `challengeHash` must be verified against the OCAP burn ledger and signed by a separate
|
|
2105
|
-
* Sentinel/Cold key (`Key_Sentinel`).
|
|
2106
|
-
*/
|
|
2107
|
-
const TWO_PHASE_CHALLENGE_TYPEHASH = utf8Keccak256Hex("EvmTwoPhaseWithdrawChallenge(uint256 chainId,address verifyingContract,bytes32 ocapTxHash,address recipient,uint256 amount,uint256 phase1BlockNumber)");
|
|
2108
|
-
function computeEvmTwoPhaseChallengeHash(params) {
|
|
2109
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
2110
|
-
const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress, "verifyingContractAddress");
|
|
2111
|
-
const ocapTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
2112
|
-
const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
|
|
2113
|
-
if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: challenge amount must be > 0n");
|
|
2114
|
-
if (!Number.isSafeInteger(params.phase1BlockNumber) || params.phase1BlockNumber <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: phase1BlockNumber must be a positive safe integer");
|
|
2115
|
-
const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
|
|
2116
|
-
const contractWordHex64 = verifyingContractAddress.slice(2).padStart(64, "0");
|
|
2117
|
-
const recipientWordHex64 = recipientEvmAddress.slice(2).padStart(64, "0");
|
|
2118
|
-
const amountHex64 = uint256ToHex64(params.amount);
|
|
2119
|
-
const blockHex64 = uint256ToHex64(params.phase1BlockNumber);
|
|
2120
|
-
return keccak256(`0x${TWO_PHASE_CHALLENGE_TYPEHASH.slice(2)}${chainIdHex64}${contractWordHex64}${ocapTxHash.slice(2)}${recipientWordHex64}${amountHex64}${blockHex64}`).toLowerCase();
|
|
2121
|
-
}
|
|
2122
|
-
/**
|
|
2123
|
-
* Issue #1245 & #1243 (`seq: 500`):
|
|
2124
|
-
* Deterministic Local EVM + OCAP End-to-End Testnet Harness (`OcapLocalEvmBridgeTestnetHarness`).
|
|
2125
|
-
* - Executes raw EIP-1193 ABI `calldataHex` produced by `OcapSimplifiedEvmBridgeNode.buildWebPortalActionBundle`
|
|
2126
|
-
* against an in-memory EVM state machine implementing `ArcEvmBridgeGateway.sol` + `MultiSigVault.sol` + `IERC20Minimal`.
|
|
2127
|
-
* - Uses authentic `secp256k1` ECDSA `(v, r, s)` signing and `ecrecover(digest, v, r, s)` public-key recovery.
|
|
2128
|
-
* - Supports `MultiSigVault` Cold Reserve + Hot `allowance` Isolation (`ERC20Rollup.sol:162-170` & `MultiSigVault.sol:447-473`)
|
|
2129
|
-
* and EVM-Anchored Two-Phase Challenge-Response (`challengeHash` + independent `Key_Sentinel` co-signature).
|
|
2130
|
-
*/
|
|
2131
|
-
var OcapLocalEvmBridgeTestnetHarness = class {
|
|
2132
|
-
constructor(params) {
|
|
2133
|
-
this.blockNumber = 1e3;
|
|
2134
|
-
this.blockTimestampSeconds = 1782e6;
|
|
2135
|
-
this.txSequence = 0;
|
|
2136
|
-
this.erc20Balances = /* @__PURE__ */ new Map();
|
|
2137
|
-
this.erc20Allowances = /* @__PURE__ */ new Map();
|
|
2138
|
-
this.validatorEvmSet = /* @__PURE__ */ new Set();
|
|
2139
|
-
this.processedServiceOrders = /* @__PURE__ */ new Set();
|
|
2140
|
-
this.claimedWithdrawTxs = /* @__PURE__ */ new Set();
|
|
2141
|
-
this.cancelledWithdrawTxs = /* @__PURE__ */ new Set();
|
|
2142
|
-
this.timelockUnlockAt = /* @__PURE__ */ new Map();
|
|
2143
|
-
this.pendingTwoPhaseChallenges = /* @__PURE__ */ new Map();
|
|
2144
|
-
this.dailyWithdrawnAbt = /* @__PURE__ */ new Map();
|
|
2145
|
-
this.multiSigColdVaultAddress = null;
|
|
2146
|
-
this.coldVaultSignerEvmAddress = null;
|
|
2147
|
-
this.sentinelSignerDid = null;
|
|
2148
|
-
this.sentinelSignerEvmAddress = null;
|
|
2149
|
-
this.evmPaused = false;
|
|
2150
|
-
this.evmCumulativeDepositedAbt = 0n;
|
|
2151
|
-
this.evmCumulativeWithdrawnAbt = 0n;
|
|
2152
|
-
this.ocapNativeAbtBalances = /* @__PURE__ */ new Map();
|
|
2153
|
-
this.ocapBurnedWithdrawTxs = /* @__PURE__ */ new Map();
|
|
2154
|
-
this.ocapDeliveredServiceAssets = /* @__PURE__ */ new Map();
|
|
2155
|
-
this.evmChainId = params.evmChainId ?? "84532";
|
|
2156
|
-
this.gatewayContractAddress = assertEvmAddress(params.gatewayContractAddress ?? params.bridgeNode.config.verifyingContractAddress, "gatewayContractAddress");
|
|
2157
|
-
this.canonicalAbtTokenAddress = assertEvmAddress(params.canonicalAbtTokenAddress, "canonicalAbtTokenAddress");
|
|
2158
|
-
this.bridgeNode = params.bridgeNode;
|
|
2159
|
-
const specs = params.validatorPrivateKeys.map((v) => {
|
|
2160
|
-
const evmSignerAddress = deriveEvmAddressFromPrivateKeyHex(v.privateKeyHex);
|
|
2161
|
-
this.validatorEvmSet.add(evmSignerAddress);
|
|
2162
|
-
return {
|
|
2163
|
-
validatorDid: assertCleanString(v.validatorDid, "validatorDid"),
|
|
2164
|
-
privateKeyHex: v.privateKeyHex,
|
|
2165
|
-
evmSignerAddress
|
|
2166
|
-
};
|
|
2167
|
-
});
|
|
2168
|
-
this.validators = Object.freeze(specs);
|
|
2169
|
-
}
|
|
2170
|
-
getBlockTimestampSeconds() {
|
|
2171
|
-
return this.blockTimestampSeconds;
|
|
2172
|
-
}
|
|
2173
|
-
advanceTimeSeconds(deltaSeconds) {
|
|
2174
|
-
if (!Number.isSafeInteger(deltaSeconds) || deltaSeconds < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: deltaSeconds must be a non-negative integer");
|
|
2175
|
-
this.blockTimestampSeconds += deltaSeconds;
|
|
2176
|
-
this.blockNumber += Math.max(1, Math.floor(deltaSeconds / 12));
|
|
2177
|
-
return this.blockTimestampSeconds;
|
|
2178
|
-
}
|
|
2179
|
-
mintTestErc20(tokenAddress, toEvmAddress, amount) {
|
|
2180
|
-
const token = assertEvmAddress(tokenAddress, "tokenAddress");
|
|
2181
|
-
const to = assertEvmAddress(toEvmAddress, "toEvmAddress");
|
|
2182
|
-
if (amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: mint amount must be > 0n");
|
|
2183
|
-
let tokenMap = this.erc20Balances.get(token);
|
|
2184
|
-
if (!tokenMap) {
|
|
2185
|
-
tokenMap = /* @__PURE__ */ new Map();
|
|
2186
|
-
this.erc20Balances.set(token, tokenMap);
|
|
2187
|
-
}
|
|
2188
|
-
tokenMap.set(to, (tokenMap.get(to) ?? 0n) + amount);
|
|
2189
|
-
}
|
|
2190
|
-
getErc20Balance(tokenAddress, ownerEvmAddress) {
|
|
2191
|
-
const token = assertEvmAddress(tokenAddress, "tokenAddress");
|
|
2192
|
-
const owner = assertEvmAddress(ownerEvmAddress, "ownerEvmAddress");
|
|
2193
|
-
return this.erc20Balances.get(token)?.get(owner) ?? 0n;
|
|
2194
|
-
}
|
|
2195
|
-
getOcapNativeAbtBalance(did) {
|
|
2196
|
-
return this.ocapNativeAbtBalances.get(assertCleanString(did, "did")) ?? 0n;
|
|
2197
|
-
}
|
|
2198
|
-
getOcapDeliveredAssets(did) {
|
|
2199
|
-
return [...this.ocapDeliveredServiceAssets.get(assertCleanString(did, "did")) ?? []];
|
|
2200
|
-
}
|
|
2201
|
-
/**
|
|
2202
|
-
* Executes a user-signed OCAP `withdraw_token_v2` burn on the OCAP ledger and collects M-of-N
|
|
2203
|
-
* real `secp256k1` EIP-712 signatures (`v, r, s`) from the bridge validators.
|
|
2204
|
-
*/
|
|
2205
|
-
initiateOcapWithdrawAndIssueEip712Voucher(params) {
|
|
2206
|
-
const fromDid = assertCleanString(params.fromDid, "fromDid");
|
|
2207
|
-
const recipientEvmAddress = assertEvmAddress(params.recipientEvmAddress, "recipientEvmAddress");
|
|
2208
|
-
const currentBal = this.getOcapNativeAbtBalance(fromDid);
|
|
2209
|
-
if (params.amount <= 0n || currentBal < params.amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: insufficient OCAP Native ABT balance (${currentBal} < ${params.amount})`);
|
|
2210
|
-
this.ocapNativeAbtBalances.set(fromDid, currentBal - params.amount);
|
|
2211
|
-
this.txSequence += 1;
|
|
2212
|
-
const ocapTxHash = utf8Keccak256Hex(`ocap:withdraw:${this.txSequence}:${fromDid}:${recipientEvmAddress}:${params.amount}`);
|
|
2213
|
-
this.ocapBurnedWithdrawTxs.set(ocapTxHash, {
|
|
2214
|
-
fromDid,
|
|
2215
|
-
recipientEvmAddress,
|
|
2216
|
-
amount: params.amount
|
|
2217
|
-
});
|
|
2218
|
-
const issuedAtUnixSeconds = this.blockTimestampSeconds;
|
|
2219
|
-
const expiresAtUnixSeconds = issuedAtUnixSeconds + (params.ttlSeconds ?? 172800);
|
|
2220
|
-
const voucherDigest = computeDirectWithdrawVoucherDigest({
|
|
2221
|
-
bridgeId: this.bridgeNode.config.bridgeId,
|
|
2222
|
-
evmChainId: this.evmChainId,
|
|
2223
|
-
verifyingContractAddress: this.gatewayContractAddress,
|
|
2224
|
-
ocapTxHash,
|
|
2225
|
-
recipientEvmAddress,
|
|
2226
|
-
amount: params.amount,
|
|
2227
|
-
expiresAtUnixSeconds
|
|
2228
|
-
});
|
|
2229
|
-
const validatorSignatures = this.validators.slice(0, this.bridgeNode.config.minValidatorSignatures).map((val) => {
|
|
2230
|
-
const ecdsa = signDigestWithSecp256k1PrivateKey(voucherDigest, val.privateKeyHex);
|
|
2231
|
-
return {
|
|
2232
|
-
validatorDid: val.validatorDid,
|
|
2233
|
-
signatureDigest: computeValidatorVoucherSignatureDigest(this.bridgeNode.config.bridgeId, voucherDigest, val.validatorDid),
|
|
2234
|
-
evmSignerAddress: ecdsa.signerEvmAddress,
|
|
2235
|
-
v: ecdsa.v,
|
|
2236
|
-
r: ecdsa.r,
|
|
2237
|
-
s: ecdsa.s
|
|
2238
|
-
};
|
|
2239
|
-
});
|
|
2240
|
-
return this.bridgeNode.issueDirectWithdrawVoucher({
|
|
2241
|
-
evmChainId: this.evmChainId,
|
|
2242
|
-
ocapTxHash,
|
|
2243
|
-
fromDid,
|
|
2244
|
-
recipientEvmAddress,
|
|
2245
|
-
amount: params.amount,
|
|
2246
|
-
issuedAtUnixSeconds,
|
|
2247
|
-
expiresAtUnixSeconds,
|
|
2248
|
-
validatorSignatures
|
|
2249
|
-
});
|
|
2250
|
-
}
|
|
2251
|
-
/**
|
|
2252
|
-
* Executes a raw EIP-1193 transaction step (`to`, `calldataHex`) on the Local EVM Testnet,
|
|
2253
|
-
* decoding the raw ABI hex calldata and enforcing all `ArcEvmBridgeGateway.sol` invariants.
|
|
2254
|
-
*/
|
|
2255
|
-
executeEip1193Step(senderEvmAddress, step) {
|
|
2256
|
-
const sender = assertEvmAddress(senderEvmAddress, "senderEvmAddress");
|
|
2257
|
-
const to = assertEvmAddress(step.to, "step.to");
|
|
2258
|
-
if (typeof step.calldataHex !== "string" || !/^0x[0-9a-fA-F]{8,}$/.test(step.calldataHex)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: invalid step.calldataHex");
|
|
2259
|
-
const selector = step.calldataHex.slice(0, 10).toLowerCase();
|
|
2260
|
-
const dataHex = step.calldataHex.slice(10).toLowerCase();
|
|
2261
|
-
this.txSequence += 1;
|
|
2262
|
-
this.blockNumber += 1;
|
|
2263
|
-
const evmTxHash = utf8Keccak256Hex(`evm:tx:${this.blockNumber}:${this.txSequence}:${sender}:${to}:${selector}`);
|
|
2264
|
-
if (selector === computeSolidityFunctionSelector("approve(address,uint256)")) {
|
|
2265
|
-
const spender = assertEvmAddress(`0x${dataHex.slice(24, 64)}`, "spender");
|
|
2266
|
-
const amount = BigInt(`0x${dataHex.slice(64, 128)}`);
|
|
2267
|
-
let allowMap = this.erc20Allowances.get(to);
|
|
2268
|
-
if (!allowMap) {
|
|
2269
|
-
allowMap = /* @__PURE__ */ new Map();
|
|
2270
|
-
this.erc20Allowances.set(to, allowMap);
|
|
2271
|
-
}
|
|
2272
|
-
allowMap.set(`${sender}:${spender}`, amount);
|
|
2273
|
-
return {
|
|
2274
|
-
evmTxHash,
|
|
2275
|
-
blockNumber: this.blockNumber,
|
|
2276
|
-
blockTimestampSeconds: this.blockTimestampSeconds,
|
|
2277
|
-
from: sender,
|
|
2278
|
-
to,
|
|
2279
|
-
functionSelector: selector,
|
|
2280
|
-
eventEmitted: "ERC20Approval",
|
|
2281
|
-
details: {
|
|
2282
|
-
tokenAddress: to,
|
|
2283
|
-
owner: sender,
|
|
2284
|
-
spender,
|
|
2285
|
-
amount: amount.toString()
|
|
2286
|
-
}
|
|
2287
|
-
};
|
|
2288
|
-
}
|
|
2289
|
-
if (to !== this.gatewayContractAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: unknown target contract ${to}`);
|
|
2290
|
-
if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: BRIDGE_PAUSED");
|
|
2291
|
-
if (selector === computeSolidityFunctionSelector("depositForNativeAbt(string,uint256)")) {
|
|
2292
|
-
const strByteOffset = Number(BigInt(`0x${dataHex.slice(0, 64)}`));
|
|
2293
|
-
const amount = BigInt(`0x${dataHex.slice(64, 128)}`);
|
|
2294
|
-
const recipientDid = decodeAbiDynamicUtf8String(dataHex, strByteOffset);
|
|
2295
|
-
const depositVaultTarget = this.multiSigColdVaultAddress ?? this.gatewayContractAddress;
|
|
2296
|
-
this.transferFromErc20(this.canonicalAbtTokenAddress, sender, depositVaultTarget, amount);
|
|
2297
|
-
this.evmCumulativeDepositedAbt += amount;
|
|
2298
|
-
const instruction = this.bridgeNode.ingestEvmAbtDepositEvent({
|
|
2299
|
-
evmChainId: this.evmChainId,
|
|
2300
|
-
evmTxHash,
|
|
2301
|
-
logIndex: 0,
|
|
2302
|
-
confirmations: this.bridgeNode.config.minConfirmations,
|
|
2303
|
-
depositorEvmAddress: sender,
|
|
2304
|
-
recipientDid,
|
|
2305
|
-
tokenAddress: this.canonicalAbtTokenAddress,
|
|
2306
|
-
amount,
|
|
2307
|
-
actualFee: 0n
|
|
2308
|
-
});
|
|
2309
|
-
this.ocapNativeAbtBalances.set(recipientDid, (this.ocapNativeAbtBalances.get(recipientDid) ?? 0n) + instruction.value);
|
|
2310
|
-
return {
|
|
2311
|
-
evmTxHash,
|
|
2312
|
-
blockNumber: this.blockNumber,
|
|
2313
|
-
blockTimestampSeconds: this.blockTimestampSeconds,
|
|
2314
|
-
from: sender,
|
|
2315
|
-
to,
|
|
2316
|
-
functionSelector: selector,
|
|
2317
|
-
eventEmitted: "NativeAbtDepositLocked",
|
|
2318
|
-
details: {
|
|
2319
|
-
depositor: sender,
|
|
2320
|
-
recipientDid,
|
|
2321
|
-
amount: amount.toString(),
|
|
2322
|
-
mintedOnOcap: instruction.value.toString(),
|
|
2323
|
-
custodiedInVault: depositVaultTarget,
|
|
2324
|
-
zeroBridgeFee: instruction.actualFee === 0n
|
|
2325
|
-
}
|
|
2326
|
-
};
|
|
2327
|
-
}
|
|
2328
|
-
if (selector === computeSolidityFunctionSelector("payForOcapService(bytes32,string,string,address,uint256)")) {
|
|
2329
|
-
const orderId = `0x${dataHex.slice(0, 64)}`;
|
|
2330
|
-
const offset1 = Number(BigInt(`0x${dataHex.slice(64, 128)}`));
|
|
2331
|
-
const offset2 = Number(BigInt(`0x${dataHex.slice(128, 192)}`));
|
|
2332
|
-
const paymentToken = assertEvmAddress(`0x${dataHex.slice(216, 256)}`, "paymentToken");
|
|
2333
|
-
const amount = BigInt(`0x${dataHex.slice(256, 320)}`);
|
|
2334
|
-
const recipientDid = decodeAbiDynamicUtf8String(dataHex, offset1);
|
|
2335
|
-
const serviceDid = decodeAbiDynamicUtf8String(dataHex, offset2);
|
|
2336
|
-
if (this.processedServiceOrders.has(orderId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_OR_DUPLICATE_ORDER");
|
|
2337
|
-
this.processedServiceOrders.add(orderId);
|
|
2338
|
-
this.transferFromErc20(paymentToken, sender, this.gatewayContractAddress, amount);
|
|
2339
|
-
const delivery = this.bridgeNode.ingestEvmServicePaymentEvent({
|
|
2340
|
-
evmChainId: this.evmChainId,
|
|
2341
|
-
evmTxHash,
|
|
2342
|
-
logIndex: 0,
|
|
2343
|
-
confirmations: this.bridgeNode.config.minConfirmations,
|
|
2344
|
-
orderId,
|
|
2345
|
-
payerEvmAddress: sender,
|
|
2346
|
-
recipientDid,
|
|
2347
|
-
serviceDid,
|
|
2348
|
-
paymentTokenAddress: paymentToken,
|
|
2349
|
-
amount
|
|
2350
|
-
});
|
|
2351
|
-
const existingAssets = this.ocapDeliveredServiceAssets.get(recipientDid) ?? [];
|
|
2352
|
-
existingAssets.push(...delivery.crossChainPurchaseInput.purchaseStatements[0].itx.assets);
|
|
2353
|
-
this.ocapDeliveredServiceAssets.set(recipientDid, existingAssets);
|
|
2354
|
-
return {
|
|
2355
|
-
evmTxHash,
|
|
2356
|
-
blockNumber: this.blockNumber,
|
|
2357
|
-
blockTimestampSeconds: this.blockTimestampSeconds,
|
|
2358
|
-
from: sender,
|
|
2359
|
-
to,
|
|
2360
|
-
functionSelector: selector,
|
|
2361
|
-
eventEmitted: "OcapServicePaid",
|
|
2362
|
-
details: {
|
|
2363
|
-
orderId,
|
|
2364
|
-
payer: sender,
|
|
2365
|
-
recipientDid,
|
|
2366
|
-
serviceDid,
|
|
2367
|
-
paymentToken,
|
|
2368
|
-
amount: amount.toString(),
|
|
2369
|
-
deliveredNftDid: delivery.crossChainPurchaseInput.purchaseStatements[0].itx.assets[0]
|
|
2370
|
-
}
|
|
2371
|
-
};
|
|
2372
|
-
}
|
|
2373
|
-
if (selector === computeSolidityFunctionSelector("claimWithdrawWithDirectVoucher(bytes32,address,uint256,uint256,bytes32,uint8[],bytes32[],bytes32[])")) {
|
|
2374
|
-
const ocapTxHash = `0x${dataHex.slice(0, 64)}`;
|
|
2375
|
-
const recipient = assertEvmAddress(`0x${dataHex.slice(88, 128)}`, "recipient");
|
|
2376
|
-
const amount = BigInt(`0x${dataHex.slice(128, 192)}`);
|
|
2377
|
-
const expiresAt = Number(BigInt(`0x${dataHex.slice(192, 256)}`));
|
|
2378
|
-
const voucherDigest = `0x${dataHex.slice(256, 320)}`;
|
|
2379
|
-
const vOffset = Number(BigInt(`0x${dataHex.slice(320, 384)}`)) * 2;
|
|
2380
|
-
const rOffset = Number(BigInt(`0x${dataHex.slice(384, 448)}`)) * 2;
|
|
2381
|
-
const sOffset = Number(BigInt(`0x${dataHex.slice(448, 512)}`)) * 2;
|
|
2382
|
-
const vLen = Number(BigInt(`0x${dataHex.slice(vOffset, vOffset + 64)}`));
|
|
2383
|
-
const rLen = Number(BigInt(`0x${dataHex.slice(rOffset, rOffset + 64)}`));
|
|
2384
|
-
const sLen = Number(BigInt(`0x${dataHex.slice(sOffset, sOffset + 64)}`));
|
|
2385
|
-
if (vLen < this.bridgeNode.config.minValidatorSignatures || vLen !== rLen || vLen !== sLen) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: QUORUM_NOT_MET");
|
|
2386
|
-
if (this.claimedWithdrawTxs.has(ocapTxHash) || this.cancelledWithdrawTxs.has(ocapTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: ALREADY_CLAIMED_OR_CANCELLED");
|
|
2387
|
-
if (this.blockTimestampSeconds > expiresAt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: VOUCHER_EXPIRED");
|
|
2388
|
-
if (this.evmCumulativeWithdrawnAbt + amount > this.evmCumulativeDepositedAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: CANARY_RESERVE_WATERMARK_EXCEEDED");
|
|
2389
|
-
if (voucherDigest !== computeDirectWithdrawVoucherDigest({
|
|
2390
|
-
bridgeId: this.bridgeNode.config.bridgeId,
|
|
2391
|
-
evmChainId: this.evmChainId,
|
|
2392
|
-
verifyingContractAddress: this.gatewayContractAddress,
|
|
2393
|
-
ocapTxHash,
|
|
2394
|
-
recipientEvmAddress: recipient,
|
|
2395
|
-
amount,
|
|
2396
|
-
expiresAtUnixSeconds: expiresAt
|
|
2397
|
-
})) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_EIP712_VOUCHER_DIGEST");
|
|
2398
|
-
let lastSignerBig = 0n;
|
|
2399
|
-
for (let i = 0; i < vLen; i++) {
|
|
2400
|
-
const recovered = ecrecoverEvmAddress(voucherDigest, Number(BigInt(`0x${dataHex.slice(vOffset + 64 + i * 64, vOffset + 128 + i * 64)}`)), `0x${dataHex.slice(rOffset + 64 + i * 64, rOffset + 128 + i * 64)}`, `0x${dataHex.slice(sOffset + 64 + i * 64, sOffset + 128 + i * 64)}`);
|
|
2401
|
-
const signerBig = BigInt(recovered);
|
|
2402
|
-
if (signerBig <= lastSignerBig || !this.validatorEvmSet.has(recovered)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_OR_UNSORTED_SIGNER");
|
|
2403
|
-
lastSignerBig = signerBig;
|
|
2404
|
-
}
|
|
2405
|
-
if (amount >= this.bridgeNode.config.largeWithdrawTimelockThresholdAbt) {
|
|
2406
|
-
const unlockAt = this.timelockUnlockAt.get(ocapTxHash) ?? 0;
|
|
2407
|
-
if (unlockAt === 0) {
|
|
2408
|
-
const newUnlockAt = this.blockTimestampSeconds + this.bridgeNode.config.timelockDelaySeconds;
|
|
2409
|
-
const challengeHash = computeEvmTwoPhaseChallengeHash({
|
|
2410
|
-
evmChainId: this.evmChainId,
|
|
2411
|
-
verifyingContractAddress: this.gatewayContractAddress,
|
|
2412
|
-
ocapTxHash,
|
|
2413
|
-
recipientEvmAddress: recipient,
|
|
2414
|
-
amount,
|
|
2415
|
-
phase1BlockNumber: this.blockNumber
|
|
2416
|
-
});
|
|
2417
|
-
this.timelockUnlockAt.set(ocapTxHash, newUnlockAt);
|
|
2418
|
-
this.pendingTwoPhaseChallenges.set(ocapTxHash, {
|
|
2419
|
-
ocapTxHash,
|
|
2420
|
-
recipientEvmAddress: recipient,
|
|
2421
|
-
amount,
|
|
2422
|
-
phase1BlockNumber: this.blockNumber,
|
|
2423
|
-
unlockAtUnixSeconds: newUnlockAt,
|
|
2424
|
-
challengeHash,
|
|
2425
|
-
sentinelCoSigned: false
|
|
2426
|
-
});
|
|
2427
|
-
return {
|
|
2428
|
-
evmTxHash,
|
|
2429
|
-
blockNumber: this.blockNumber,
|
|
2430
|
-
blockTimestampSeconds: this.blockTimestampSeconds,
|
|
2431
|
-
from: sender,
|
|
2432
|
-
to,
|
|
2433
|
-
functionSelector: selector,
|
|
2434
|
-
eventEmitted: "LargeWithdrawTimelocked",
|
|
2435
|
-
details: {
|
|
2436
|
-
ocapTxHash,
|
|
2437
|
-
recipient,
|
|
2438
|
-
amount: amount.toString(),
|
|
2439
|
-
unlockAt: newUnlockAt,
|
|
2440
|
-
phase1BlockNumber: this.blockNumber,
|
|
2441
|
-
challengeHash
|
|
2442
|
-
}
|
|
2443
|
-
};
|
|
2444
|
-
}
|
|
2445
|
-
const pendingChallenge = this.pendingTwoPhaseChallenges.get(ocapTxHash);
|
|
2446
|
-
if (!pendingChallenge || pendingChallenge.recipientEvmAddress.toLowerCase() !== recipient.toLowerCase() || pendingChallenge.amount !== amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: PHASE1_CHALLENGE_PARAMETER_MISMATCH");
|
|
2447
|
-
if (this.sentinelSignerEvmAddress !== null && !pendingChallenge.sentinelCoSigned) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: TWO_PHASE_SENTINEL_COSIGN_REQUIRED");
|
|
2448
|
-
if (this.blockTimestampSeconds < unlockAt && !pendingChallenge.sentinelCoSigned) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: TIMELOCK_ACTIVE");
|
|
2449
|
-
}
|
|
2450
|
-
return this.settleEvmWithdrawTransfer({
|
|
2451
|
-
evmTxHash,
|
|
2452
|
-
sender,
|
|
2453
|
-
to,
|
|
2454
|
-
selector,
|
|
2455
|
-
ocapTxHash,
|
|
2456
|
-
recipient,
|
|
2457
|
-
amount
|
|
2458
|
-
});
|
|
2459
|
-
}
|
|
2460
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `ArcEvmBridgeGateway: unsupported selector ${selector}`);
|
|
2461
|
-
}
|
|
2462
|
-
/**
|
|
2463
|
-
* Configures the `MultiSigVault.sol` Cold Reserve + Hot `allowance` Isolation & Independent
|
|
2464
|
-
* Sentinel Second-Factor Key Domain (`seq: 500`, matching `ArcBlock/contracts/src/ERC20Rollup.sol:162-170`
|
|
2465
|
-
* and `MultiSigVault.sol:447-473`):
|
|
2466
|
-
* - The Bridge Gateway contract (`gatewayContractAddress`) holds 0 ERC-20 ABT directly.
|
|
2467
|
-
* - All reserves sit in `vaultAddress` (`MultiSigVault`), which grants `gatewayContractAddress` a bounded
|
|
2468
|
-
* ERC-20 `allowance(vaultAddress, gatewayContractAddress)` (`initialHotAllowanceAbt`).
|
|
2469
|
-
* - Enforces strict cryptographic key-domain separation: neither `coldVaultPrivateKeyHex` nor
|
|
2470
|
-
* `sentinelPrivateKeyHex` may overlap with any Phase-1 hot bridge validator key (`validatorEvmSet`).
|
|
2471
|
-
*/
|
|
2472
|
-
configureMultiSigColdVault(params) {
|
|
2473
|
-
const vaultAddress = assertEvmAddress(params.vaultAddress, "vaultAddress");
|
|
2474
|
-
if (vaultAddress === this.gatewayContractAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigVault address must be isolated from gatewayContractAddress");
|
|
2475
|
-
const coldVaultSignerEvmAddress = deriveEvmAddressFromPrivateKeyHex(params.coldVaultPrivateKeyHex);
|
|
2476
|
-
const sentinelDid = assertCleanString(params.sentinelDid, "sentinelDid");
|
|
2477
|
-
const sentinelEvmAddress = deriveEvmAddressFromPrivateKeyHex(params.sentinelPrivateKeyHex);
|
|
2478
|
-
if (this.validatorEvmSet.has(coldVaultSignerEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: coldVaultPrivateKeyHex must be strictly disjoint from Phase-1 hot validator keys");
|
|
2479
|
-
if (this.validatorEvmSet.has(sentinelEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: sentinelPrivateKeyHex must be strictly disjoint from Phase-1 hot validator keys");
|
|
2480
|
-
if (coldVaultSignerEvmAddress === sentinelEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: coldVaultPrivateKeyHex and sentinelPrivateKeyHex must be distinct keys");
|
|
2481
|
-
if (vaultAddress === this.canonicalAbtTokenAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigVault address must be distinct from canonicalAbtTokenAddress");
|
|
2482
|
-
if (this.multiSigColdVaultAddress !== null) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: MultiSigColdVault is already configured");
|
|
2483
|
-
if (params.initialColdReserveAbt < 0n || params.initialHotAllowanceAbt < 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: vault amounts must be non-negative");
|
|
2484
|
-
if (params.initialHotAllowanceAbt > params.initialColdReserveAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: initialHotAllowanceAbt cannot exceed initialColdReserveAbt");
|
|
2485
|
-
this.multiSigColdVaultAddress = vaultAddress;
|
|
2486
|
-
this.coldVaultSignerEvmAddress = coldVaultSignerEvmAddress;
|
|
2487
|
-
this.sentinelSignerDid = sentinelDid;
|
|
2488
|
-
this.sentinelSignerEvmAddress = sentinelEvmAddress;
|
|
2489
|
-
if (params.initialColdReserveAbt > 0n) {
|
|
2490
|
-
this.mintTestErc20(this.canonicalAbtTokenAddress, vaultAddress, params.initialColdReserveAbt);
|
|
2491
|
-
this.evmCumulativeDepositedAbt += params.initialColdReserveAbt;
|
|
2492
|
-
this.bridgeNode.ingestEvmAbtDepositEvent({
|
|
2493
|
-
evmChainId: this.evmChainId,
|
|
2494
|
-
evmTxHash: utf8Keccak256Hex(`evm:cold-vault-init:${vaultAddress}:${params.initialColdReserveAbt}`),
|
|
2495
|
-
logIndex: 0,
|
|
2496
|
-
confirmations: this.bridgeNode.config.minConfirmations,
|
|
2497
|
-
depositorEvmAddress: vaultAddress,
|
|
2498
|
-
recipientDid: this.bridgeNode.config.bridgeProposerDid,
|
|
2499
|
-
tokenAddress: this.canonicalAbtTokenAddress,
|
|
2500
|
-
amount: params.initialColdReserveAbt,
|
|
2501
|
-
actualFee: 0n
|
|
2502
|
-
});
|
|
2503
|
-
this.ocapNativeAbtBalances.set(this.bridgeNode.config.bridgeProposerDid, (this.ocapNativeAbtBalances.get(this.bridgeNode.config.bridgeProposerDid) ?? 0n) + params.initialColdReserveAbt);
|
|
2504
|
-
}
|
|
2505
|
-
let allowMap = this.erc20Allowances.get(this.canonicalAbtTokenAddress);
|
|
2506
|
-
if (!allowMap) {
|
|
2507
|
-
allowMap = /* @__PURE__ */ new Map();
|
|
2508
|
-
this.erc20Allowances.set(this.canonicalAbtTokenAddress, allowMap);
|
|
2509
|
-
}
|
|
2510
|
-
allowMap.set(`${vaultAddress}:${this.gatewayContractAddress}`, params.initialHotAllowanceAbt);
|
|
2511
|
-
return {
|
|
2512
|
-
vaultAddress,
|
|
2513
|
-
coldVaultSignerEvmAddress,
|
|
2514
|
-
sentinelDid,
|
|
2515
|
-
sentinelEvmAddress,
|
|
2516
|
-
coldReserveAbt: this.getErc20Balance(this.canonicalAbtTokenAddress, vaultAddress),
|
|
2517
|
-
hotAllowanceAbt: params.initialHotAllowanceAbt
|
|
2518
|
-
};
|
|
2519
|
-
}
|
|
2520
|
-
getMultiSigVaultState() {
|
|
2521
|
-
const vaultAddress = this.multiSigColdVaultAddress;
|
|
2522
|
-
return {
|
|
2523
|
-
vaultAddress,
|
|
2524
|
-
coldReserveAbt: vaultAddress ? this.getErc20Balance(this.canonicalAbtTokenAddress, vaultAddress) : 0n,
|
|
2525
|
-
hotAllowanceAbt: vaultAddress ? this.erc20Allowances.get(this.canonicalAbtTokenAddress)?.get(`${vaultAddress}:${this.gatewayContractAddress}`) ?? 0n : 0n,
|
|
2526
|
-
gatewayDirectBalanceAbt: this.getErc20Balance(this.canonicalAbtTokenAddress, this.gatewayContractAddress),
|
|
2527
|
-
sentinelEvmAddress: this.sentinelSignerEvmAddress
|
|
2528
|
-
};
|
|
2529
|
-
}
|
|
2530
|
-
/**
|
|
2531
|
-
* Mirrors `MultiSigVault.approveERC20(token, spender, ApproveAction, amount, signatures)`:
|
|
2532
|
-
* Only the independent Cold Vault signer (`coldVaultPrivateKeyHex`) can increase or decrease
|
|
2533
|
-
* the ERC-20 `allowance(vaultAddress, gatewayContractAddress)` hot exposure cap.
|
|
2534
|
-
*/
|
|
2535
|
-
approveColdVaultHotAllowance(params) {
|
|
2536
|
-
if (!this.multiSigColdVaultAddress || !this.coldVaultSignerEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: MultiSigColdVault is not configured");
|
|
2537
|
-
if (params.action !== "INCREASE" && params.action !== "DECREASE") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: action must be INCREASE or DECREASE");
|
|
2538
|
-
if (typeof params.amount !== "bigint" || params.amount <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: allowance change amount must be > 0n");
|
|
2539
|
-
const opHash = utf8Keccak256Hex(`multisig-vault:approve:${this.canonicalAbtTokenAddress}:${this.gatewayContractAddress}:${params.action}:${params.amount}`);
|
|
2540
|
-
const sig = signDigestWithSecp256k1PrivateKey(opHash, params.coldVaultPrivateKeyHex);
|
|
2541
|
-
const recovered = ecrecoverEvmAddress(opHash, sig.v, sig.r, sig.s);
|
|
2542
|
-
if (recovered !== this.coldVaultSignerEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `MultiSigVault: unauthorized cold vault signer (${recovered} !== ${this.coldVaultSignerEvmAddress})`);
|
|
2543
|
-
const allowKey = `${this.multiSigColdVaultAddress}:${this.gatewayContractAddress}`;
|
|
2544
|
-
const allowMap = this.erc20Allowances.get(this.canonicalAbtTokenAddress);
|
|
2545
|
-
const currentAllow = allowMap.get(allowKey) ?? 0n;
|
|
2546
|
-
const coldReserve = this.getErc20Balance(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress);
|
|
2547
|
-
const nextAllow = params.action === "INCREASE" ? currentAllow + params.amount : currentAllow > params.amount ? currentAllow - params.amount : 0n;
|
|
2548
|
-
if (params.action === "INCREASE" && nextAllow > coldReserve) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `MultiSigVault: hot allowance (${nextAllow}) cannot exceed cold vault reserve (${coldReserve})`);
|
|
2549
|
-
allowMap.set(allowKey, nextAllow);
|
|
2550
|
-
return {
|
|
2551
|
-
vaultAddress: this.multiSigColdVaultAddress,
|
|
2552
|
-
newHotAllowanceAbt: nextAllow
|
|
2553
|
-
};
|
|
2554
|
-
}
|
|
2555
|
-
getPendingTwoPhaseChallenge(ocapTxHash) {
|
|
2556
|
-
const cleanHash = assertBytes32Hex(ocapTxHash, "ocapTxHash");
|
|
2557
|
-
const rec = this.pendingTwoPhaseChallenges.get(cleanHash);
|
|
2558
|
-
return rec ? { ...rec } : void 0;
|
|
2559
|
-
}
|
|
2560
|
-
/**
|
|
2561
|
-
* Intermediate Cross-Chain Handshake (`seq: 500`):
|
|
2562
|
-
* Takes the `challengeHash` emitted on Ethereum during Phase 1 back to the OCAP / Sentinel control plane:
|
|
2563
|
-
* 1. Verifies that `ocapTxHash` exists in `pendingTwoPhaseChallenges` on Ethereum and its `challengeHash` matches.
|
|
2564
|
-
* 2. Verifies against the OCAP ledger (`ocapBurnedWithdrawTxs`) that `ocapTxHash` genuinely burned the exact
|
|
2565
|
-
* `amount` for `recipientEvmAddress`. If an attacker forged Phase 1 with stolen `Key_Hot` without a matching
|
|
2566
|
-
* OCAP burn, Sentinel immediately cancels the withdrawal on EVM, pauses the bridge, and aborts!
|
|
2567
|
-
* 3. Uses the independent Second-Factor key (`sentinelPrivateKeyHex`, disjoint from `Key_Hot`) to sign `challengeHash`,
|
|
2568
|
-
* and optionally replenishes the `MultiSigVault` hot `allowance` if `coldVaultPrivateKeyHex` is provided.
|
|
2569
|
-
*/
|
|
2570
|
-
coSignEvmWithdrawalChallenge(params) {
|
|
2571
|
-
if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: bridge is paused");
|
|
2572
|
-
if (!this.sentinelSignerEvmAddress || !this.sentinelSignerDid) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SimplifiedEvmBridge: Sentinel second-factor key not configured");
|
|
2573
|
-
const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
2574
|
-
if (this.claimedWithdrawTxs.has(cleanTxHash) || this.cancelledWithdrawTxs.has(cleanTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: withdrawal already claimed or cancelled");
|
|
2575
|
-
const cleanChallengeHash = assertBytes32Hex(params.challengeHash, "challengeHash");
|
|
2576
|
-
const derivedSentinelAddr = deriveEvmAddressFromPrivateKeyHex(params.sentinelPrivateKeyHex);
|
|
2577
|
-
if (derivedSentinelAddr !== this.sentinelSignerEvmAddress || this.validatorEvmSet.has(derivedSentinelAddr)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SimplifiedEvmBridge: unauthorized or non-isolated Sentinel second-factor key");
|
|
2578
|
-
const pending = this.pendingTwoPhaseChallenges.get(cleanTxHash);
|
|
2579
|
-
if (!pending) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SimplifiedEvmBridge: no Phase-1 pending withdrawal challenge on EVM for ${cleanTxHash}`);
|
|
2580
|
-
if (pending.challengeHash !== cleanChallengeHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: challengeHash mismatch (${cleanChallengeHash} !== ${pending.challengeHash})`);
|
|
2581
|
-
const ocapBurn = this.ocapBurnedWithdrawTxs.get(cleanTxHash);
|
|
2582
|
-
if (!ocapBurn || ocapBurn.recipientEvmAddress.toLowerCase() !== pending.recipientEvmAddress.toLowerCase() || ocapBurn.amount !== pending.amount) {
|
|
2583
|
-
this.cancelledWithdrawTxs.add(cleanTxHash);
|
|
2584
|
-
this.evmPaused = true;
|
|
2585
|
-
this.bridgeNode.setBridgePaused({
|
|
2586
|
-
guardianDid: this.bridgeNode.config.guardianDid,
|
|
2587
|
-
paused: true
|
|
2588
|
-
});
|
|
2589
|
-
throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: Sentinel detected forged Phase-1 withdrawal ${cleanTxHash} without matching OCAP burn; withdrawal cancelled and bridge paused`);
|
|
2590
|
-
}
|
|
2591
|
-
let replenishedHotAllowanceAbt = 0n;
|
|
2592
|
-
if (this.multiSigColdVaultAddress) {
|
|
2593
|
-
const vaultState = this.getMultiSigVaultState();
|
|
2594
|
-
if (vaultState.hotAllowanceAbt < pending.amount) {
|
|
2595
|
-
const deficit = pending.amount - vaultState.hotAllowanceAbt;
|
|
2596
|
-
if (!params.coldVaultPrivateKeyHexForAllowanceTopUp) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SimplifiedEvmBridge: withdrawal amount (${pending.amount}) exceeds current MultiSigVault hot allowance (${vaultState.hotAllowanceAbt}); coldVaultPrivateKeyHexForAllowanceTopUp required`);
|
|
2597
|
-
this.approveColdVaultHotAllowance({
|
|
2598
|
-
action: "INCREASE",
|
|
2599
|
-
amount: deficit,
|
|
2600
|
-
coldVaultPrivateKeyHex: params.coldVaultPrivateKeyHexForAllowanceTopUp
|
|
2601
|
-
});
|
|
2602
|
-
replenishedHotAllowanceAbt = deficit;
|
|
2603
|
-
}
|
|
2604
|
-
}
|
|
2605
|
-
const sig = signDigestWithSecp256k1PrivateKey(cleanChallengeHash, params.sentinelPrivateKeyHex);
|
|
2606
|
-
pending.sentinelCoSigned = true;
|
|
2607
|
-
return {
|
|
2608
|
-
ocapTxHash: cleanTxHash,
|
|
2609
|
-
challengeHash: cleanChallengeHash,
|
|
2610
|
-
sentinelDid: this.sentinelSignerDid,
|
|
2611
|
-
sentinelEvmAddress: derivedSentinelAddr,
|
|
2612
|
-
v: sig.v,
|
|
2613
|
-
r: sig.r,
|
|
2614
|
-
s: sig.s,
|
|
2615
|
-
replenishedHotAllowanceAbt
|
|
2616
|
-
};
|
|
2617
|
-
}
|
|
2618
|
-
/**
|
|
2619
|
-
* Phase 2 on Ethereum (`seq: 500`):
|
|
2620
|
-
* Submits the independent second-factor signature (`sig_Phase2` over `challengeHash`) to the Ethereum
|
|
2621
|
-
* gateway contract. The contract verifies:
|
|
2622
|
-
* 1. The withdrawal completed Phase 1 on Ethereum (`pendingTwoPhaseChallenges.get(ocapTxHash)`) and its
|
|
2623
|
-
* on-chain `challengeHash` matches.
|
|
2624
|
-
* 2. `ecrecover(challengeHash, v, r, s)` recovers the authorized independent `sentinelSignerEvmAddress`.
|
|
2625
|
-
* 3. Transfers `amount` from `MultiSigVault` (`safeTransferFrom(token, vaultAddress, recipient, amount)`)
|
|
2626
|
-
* within the approved `allowance(vaultAddress, gatewayContractAddress)`.
|
|
2627
|
-
*/
|
|
2628
|
-
finalizeChallengedWithdrawOnEvm(params) {
|
|
2629
|
-
const sender = assertEvmAddress(params.senderEvmAddress, "senderEvmAddress");
|
|
2630
|
-
const cleanTxHash = assertBytes32Hex(params.ocapTxHash, "ocapTxHash");
|
|
2631
|
-
const cleanChallengeHash = assertBytes32Hex(params.challengeHash, "challengeHash");
|
|
2632
|
-
if (this.evmPaused || this.bridgeNode.getReserveWatermarkState().paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: BRIDGE_PAUSED");
|
|
2633
|
-
if (!this.sentinelSignerEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "ArcEvmBridgeGateway: SENTINEL_SIGNER_NOT_CONFIGURED");
|
|
2634
|
-
if (this.claimedWithdrawTxs.has(cleanTxHash) || this.cancelledWithdrawTxs.has(cleanTxHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: ALREADY_CLAIMED_OR_CANCELLED");
|
|
2635
|
-
const pending = this.pendingTwoPhaseChallenges.get(cleanTxHash);
|
|
2636
|
-
if (!pending) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: PHASE1_CHALLENGE_NOT_FOUND");
|
|
2637
|
-
const expectedChallengeHash = computeEvmTwoPhaseChallengeHash({
|
|
2638
|
-
evmChainId: this.evmChainId,
|
|
2639
|
-
verifyingContractAddress: this.gatewayContractAddress,
|
|
2640
|
-
ocapTxHash: cleanTxHash,
|
|
2641
|
-
recipientEvmAddress: pending.recipientEvmAddress,
|
|
2642
|
-
amount: pending.amount,
|
|
2643
|
-
phase1BlockNumber: pending.phase1BlockNumber
|
|
2644
|
-
});
|
|
2645
|
-
if (cleanChallengeHash !== pending.challengeHash || cleanChallengeHash !== expectedChallengeHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: INVALID_PHASE2_CHALLENGE_HASH");
|
|
2646
|
-
const recoveredSentinel = ecrecoverEvmAddress(cleanChallengeHash, params.v, params.r, params.s);
|
|
2647
|
-
if (recoveredSentinel !== this.sentinelSignerEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `ArcEvmBridgeGateway: INVALID_PHASE2_SENTINEL_SIGNATURE (${recoveredSentinel} !== ${this.sentinelSignerEvmAddress})`);
|
|
2648
|
-
this.txSequence += 1;
|
|
2649
|
-
this.blockNumber += 1;
|
|
2650
|
-
const selector = computeSolidityFunctionSelector("finalizeChallengedWithdraw(bytes32,bytes32,uint8,bytes32,bytes32)");
|
|
2651
|
-
const evmTxHash = utf8Keccak256Hex(`evm:tx:${this.blockNumber}:${this.txSequence}:${sender}:${this.gatewayContractAddress}:${selector}`);
|
|
2652
|
-
const receipt = this.settleEvmWithdrawTransfer({
|
|
2653
|
-
evmTxHash,
|
|
2654
|
-
sender,
|
|
2655
|
-
to: this.gatewayContractAddress,
|
|
2656
|
-
selector,
|
|
2657
|
-
ocapTxHash: cleanTxHash,
|
|
2658
|
-
recipient: pending.recipientEvmAddress,
|
|
2659
|
-
amount: pending.amount,
|
|
2660
|
-
challengeHash: cleanChallengeHash,
|
|
2661
|
-
sentinelSigner: recoveredSentinel
|
|
2662
|
-
});
|
|
2663
|
-
pending.sentinelCoSigned = true;
|
|
2664
|
-
return receipt;
|
|
2665
|
-
}
|
|
2666
|
-
settleEvmWithdrawTransfer(params) {
|
|
2667
|
-
const { evmTxHash, sender, to, selector, ocapTxHash, recipient, amount } = params;
|
|
2668
|
-
const currentDay = Math.floor(this.blockTimestampSeconds / 86400);
|
|
2669
|
-
const dayTotal = this.dailyWithdrawnAbt.get(currentDay) ?? 0n;
|
|
2670
|
-
if (dayTotal + amount > this.bridgeNode.config.maxDailyWithdrawAbt) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ArcEvmBridgeGateway: DAILY_WITHDRAW_CAP_EXCEEDED");
|
|
2671
|
-
if (this.multiSigColdVaultAddress) {
|
|
2672
|
-
if (this.getErc20Balance(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress) < amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ERC20Rollup: E243_INSUFFICIENT_VAULT_BALANCE");
|
|
2673
|
-
const allowKey = `${this.multiSigColdVaultAddress}:${this.gatewayContractAddress}`;
|
|
2674
|
-
const currentAllow = this.erc20Allowances.get(this.canonicalAbtTokenAddress)?.get(allowKey) ?? 0n;
|
|
2675
|
-
if (currentAllow < amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `ERC20Rollup: E220_HOT_VAULT_ALLOWANCE_EXCEEDED (requested ${amount} > remaining hot allowance ${currentAllow})`);
|
|
2676
|
-
this.transferFromErc20(this.canonicalAbtTokenAddress, this.multiSigColdVaultAddress, recipient, amount);
|
|
2677
|
-
} else this.transferDirectErc20(this.canonicalAbtTokenAddress, this.gatewayContractAddress, recipient, amount);
|
|
2678
|
-
this.dailyWithdrawnAbt.set(currentDay, dayTotal + amount);
|
|
2679
|
-
this.claimedWithdrawTxs.add(ocapTxHash);
|
|
2680
|
-
this.evmCumulativeWithdrawnAbt += amount;
|
|
2681
|
-
return {
|
|
2682
|
-
evmTxHash,
|
|
2683
|
-
blockNumber: this.blockNumber,
|
|
2684
|
-
blockTimestampSeconds: this.blockTimestampSeconds,
|
|
2685
|
-
from: sender,
|
|
2686
|
-
to,
|
|
2687
|
-
functionSelector: selector,
|
|
2688
|
-
eventEmitted: "NativeAbtWithdrawClaimed",
|
|
2689
|
-
details: {
|
|
2690
|
-
ocapTxHash,
|
|
2691
|
-
recipient,
|
|
2692
|
-
amount: amount.toString(),
|
|
2693
|
-
zeroBridgeFee: true,
|
|
2694
|
-
...params.challengeHash ? { challengeHash: params.challengeHash } : {},
|
|
2695
|
-
...params.sentinelSigner ? { sentinelSigner: params.sentinelSigner } : {}
|
|
2696
|
-
}
|
|
2697
|
-
};
|
|
2698
|
-
}
|
|
2699
|
-
/**
|
|
2700
|
-
* Crowdsourced User-Wallet Watchtower Witness (`seq: 463`):
|
|
2701
|
-
* Any user wallet or Blocklet can inspect pending timelocked withdrawals on the EVM gateway contract
|
|
2702
|
-
* against the authentic OCAP chain burn ledger (`ocapBurnedWithdrawTxs`).
|
|
2703
|
-
* If a timelocked withdrawal on EVM does not exist on OCAP (or has a mismatched amount/recipient),
|
|
2704
|
-
* the Watchtower Witness flags the anomaly and triggers Guardian cancellation + pause.
|
|
2705
|
-
*/
|
|
2706
|
-
verifyWatchtowerStateConsistency(witnessWalletDid) {
|
|
2707
|
-
const cleanWitness = assertCleanString(witnessWalletDid, "witnessWalletDid");
|
|
2708
|
-
const flaggedTxHashes = [];
|
|
2709
|
-
for (const [ocapTxHash] of this.timelockUnlockAt.entries()) {
|
|
2710
|
-
if (this.cancelledWithdrawTxs.has(ocapTxHash) || this.claimedWithdrawTxs.has(ocapTxHash)) continue;
|
|
2711
|
-
const ocapBurn = this.ocapBurnedWithdrawTxs.get(ocapTxHash);
|
|
2712
|
-
const pendingChallenge = this.pendingTwoPhaseChallenges.get(ocapTxHash);
|
|
2713
|
-
if (!ocapBurn || pendingChallenge && (ocapBurn.recipientEvmAddress.toLowerCase() !== pendingChallenge.recipientEvmAddress.toLowerCase() || ocapBurn.amount !== pendingChallenge.amount)) flaggedTxHashes.push(ocapTxHash);
|
|
2714
|
-
}
|
|
2715
|
-
if (flaggedTxHashes.length > 0) {
|
|
2716
|
-
for (const txHash of flaggedTxHashes) {
|
|
2717
|
-
this.cancelledWithdrawTxs.add(txHash);
|
|
2718
|
-
try {
|
|
2719
|
-
this.bridgeNode.cancelTimelockedWithdraw({
|
|
2720
|
-
guardianDid: this.bridgeNode.config.guardianDid,
|
|
2721
|
-
ocapTxHash: txHash,
|
|
2722
|
-
nowUnixSeconds: this.blockTimestampSeconds
|
|
2723
|
-
});
|
|
2724
|
-
} catch {}
|
|
2725
|
-
}
|
|
2726
|
-
this.evmPaused = true;
|
|
2727
|
-
this.bridgeNode.setBridgePaused({
|
|
2728
|
-
guardianDid: this.bridgeNode.config.guardianDid,
|
|
2729
|
-
paused: true
|
|
2730
|
-
});
|
|
2731
|
-
return {
|
|
2732
|
-
consistent: false,
|
|
2733
|
-
witnessWalletDid: cleanWitness,
|
|
2734
|
-
flaggedTxHashes,
|
|
2735
|
-
autoCancelledAndPaused: true
|
|
2736
|
-
};
|
|
2737
|
-
}
|
|
2738
|
-
return {
|
|
2739
|
-
consistent: true,
|
|
2740
|
-
witnessWalletDid: cleanWitness,
|
|
2741
|
-
flaggedTxHashes: [],
|
|
2742
|
-
autoCancelledAndPaused: false
|
|
2743
|
-
};
|
|
2744
|
-
}
|
|
2745
|
-
transferFromErc20(tokenAddress, from, to, amount) {
|
|
2746
|
-
const allowKey = `${from}:${this.gatewayContractAddress}`;
|
|
2747
|
-
const allowMap = this.erc20Allowances.get(tokenAddress);
|
|
2748
|
-
const currentAllow = allowMap?.get(allowKey) ?? 0n;
|
|
2749
|
-
if (currentAllow < amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ERC20: insufficient allowance");
|
|
2750
|
-
allowMap.set(allowKey, currentAllow - amount);
|
|
2751
|
-
this.transferDirectErc20(tokenAddress, from, to, amount);
|
|
2752
|
-
}
|
|
2753
|
-
transferDirectErc20(tokenAddress, from, to, amount) {
|
|
2754
|
-
const tokenMap = this.erc20Balances.get(tokenAddress);
|
|
2755
|
-
const fromBal = tokenMap?.get(from) ?? 0n;
|
|
2756
|
-
if (fromBal < amount) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "ERC20: transfer amount exceeds balance");
|
|
2757
|
-
tokenMap.set(from, fromBal - amount);
|
|
2758
|
-
tokenMap.set(to, (tokenMap.get(to) ?? 0n) + amount);
|
|
2759
|
-
}
|
|
2760
|
-
};
|
|
2761
|
-
const MULTISIG_OP_TYPEHASH = utf8Keccak256Hex("MultiSigOperation(address targetContract,bytes4 selector,uint256 nonce,bytes32 paramsHash)");
|
|
2762
|
-
const BRIDGE_CHARTER_KIND = "BridgeGovernanceCharter";
|
|
2763
|
-
const MULTISIG_SELECTOR_HEX_MAP = {
|
|
2764
|
-
SEND_ETHER: computeSolidityFunctionSelector("sendEther(address,uint256,bytes)"),
|
|
2765
|
-
SEND_ERC20: computeSolidityFunctionSelector("sendERC20(address,address,uint256,bytes)"),
|
|
2766
|
-
APPROVE_ERC20: computeSolidityFunctionSelector("approveERC20(address,address,uint8,uint256,bytes)"),
|
|
2767
|
-
ADD_SIGNER: computeSolidityFunctionSelector("addSigner(address,bytes)"),
|
|
2768
|
-
REMOVE_SIGNER: computeSolidityFunctionSelector("removeSigner(address,bytes)"),
|
|
2769
|
-
SET_THRESHOLD: computeSolidityFunctionSelector("setThreshold(uint8,bytes)"),
|
|
2770
|
-
REPLACE_SEED_SIGNER: computeSolidityFunctionSelector("replaceSeedSigner(address,address,bytes)"),
|
|
2771
|
-
MIGRATE_VAULT: computeSolidityFunctionSelector("migrateVault(address,bytes)")
|
|
2772
|
-
};
|
|
2773
|
-
/**
|
|
2774
|
-
* Hardened `SignerManagerV2` + `MultiSigVaultV2` EIP-712 Digest (`seq: 504`):
|
|
2775
|
-
* Fixes the 4 Critical/High vulnerabilities identified in legacy `SignerManager.sol` & `MultiSigVault.sol`:
|
|
2776
|
-
* 1. CRITICAL-1 (Cross-Contract / Cross-Method Replay & Front-Run Nonce Burn):
|
|
2777
|
-
* Binds `targetContract` (`msg.sender`, e.g., `vaultAddress` vs `signerManagerAddress`), `selector` (`bytes4`),
|
|
2778
|
-
* and a contract-wide sequential `nonce` into the EIP-712 struct hash. Calling `ensureSignatures` directly
|
|
2779
|
-
* from an EOA or unauthorized contract produces a different `targetContract` (`msg.sender`) and fails recovery.
|
|
2780
|
-
* 2. CRITICAL-2 (Permanent Vault Lockout on Single Lost Seed Signer):
|
|
2781
|
-
* Supports `seedThreshold` (M-of-K seed quorum) and `REPLACE_SEED_SIGNER` recovery rotation.
|
|
2782
|
-
* 3. HIGH-1 (Opaque Raw-Hash Signing & `abi.encodePacked` Collision):
|
|
2783
|
-
* Uses EIP-712 Typed Structured Data with fixed-width 32-byte `abi.encode` words for wallet Clear-Signing.
|
|
2784
|
-
* 4. HIGH-2 (Per-Signer Nonce Desynchronization Under Partial Subset Signing):
|
|
2785
|
-
* Uses a single Safe-style sequential `nonce` per target contract and strictly ascending signer address order (`O(N)`).
|
|
2786
|
-
*/
|
|
2787
|
-
function computeHardenedMultiSigOpDigest(params) {
|
|
2788
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
2789
|
-
const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
|
|
2790
|
-
const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
|
|
2791
|
-
const selectorHex = MULTISIG_SELECTOR_HEX_MAP[params.operation];
|
|
2792
|
-
if (!selectorHex) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `MultiSigVaultV2: unsupported operation ${params.operation}`);
|
|
2793
|
-
if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "MultiSigVaultV2: nonce must be a non-negative safe integer");
|
|
2794
|
-
const paramsHash = assertBytes32Hex(params.paramsHash, "paramsHash");
|
|
2795
|
-
const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
|
|
2796
|
-
const versionHash = utf8Keccak256Hex("2").slice(2);
|
|
2797
|
-
const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
|
|
2798
|
-
const signerManagerWord64 = signerManagerAddress.slice(2).padStart(64, "0");
|
|
2799
|
-
const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerWord64}`).toLowerCase();
|
|
2800
|
-
const selectorWord = selectorHex.slice(2).toLowerCase().padEnd(64, "0");
|
|
2801
|
-
const targetWord64 = targetContractAddress.slice(2).padStart(64, "0");
|
|
2802
|
-
const structHash = keccak256(`0x${MULTISIG_OP_TYPEHASH.slice(2)}${targetWord64}${selectorWord}${uint256ToHex64(params.nonce)}${paramsHash.slice(2)}`).toLowerCase();
|
|
2803
|
-
return {
|
|
2804
|
-
domainSeparator,
|
|
2805
|
-
structHash,
|
|
2806
|
-
digest: keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase(),
|
|
2807
|
-
selectorHex
|
|
2808
|
-
};
|
|
2809
|
-
}
|
|
2810
|
-
var HardenedMultiSigSignerManagerV2 = class {
|
|
2811
|
-
constructor(params) {
|
|
2812
|
-
this.signers = /* @__PURE__ */ new Set();
|
|
2813
|
-
this.seedSigners = /* @__PURE__ */ new Set();
|
|
2814
|
-
this.noncesByTarget = /* @__PURE__ */ new Map();
|
|
2815
|
-
this.vetoedProposalHashes = /* @__PURE__ */ new Set();
|
|
2816
|
-
this.evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
2817
|
-
this.signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
|
|
2818
|
-
if (!Array.isArray(params.signers) || params.signers.length === 0 || params.signers.length > 32) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: signers must contain 1..32 addresses");
|
|
2819
|
-
for (const s of params.signers) {
|
|
2820
|
-
const addr = assertEvmAddress(s, "signerAddress");
|
|
2821
|
-
if (this.signers.has(addr)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: duplicate signer ${addr}`);
|
|
2822
|
-
this.signers.add(addr);
|
|
2823
|
-
}
|
|
2824
|
-
if (!Array.isArray(params.seedSigners) || params.seedSigners.length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: seedSigners must be non-empty");
|
|
2825
|
-
for (const s of params.seedSigners) {
|
|
2826
|
-
const addr = assertEvmAddress(s, "seedSignerAddress");
|
|
2827
|
-
if (!this.signers.has(addr)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: seedSigner ${addr} must also be in signers`);
|
|
2828
|
-
this.seedSigners.add(addr);
|
|
2829
|
-
}
|
|
2830
|
-
if (!Number.isSafeInteger(params.threshold) || params.threshold < 1 || params.threshold > this.signers.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: invalid threshold (1..signers.length)");
|
|
2831
|
-
const seedThreshold = params.seedThreshold ?? Math.min(params.threshold, this.seedSigners.size);
|
|
2832
|
-
if (!Number.isSafeInteger(seedThreshold) || seedThreshold < 1 || seedThreshold > this.seedSigners.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "SignerManagerV2: invalid seedThreshold (1..seedSigners.length)");
|
|
2833
|
-
this.threshold = params.threshold;
|
|
2834
|
-
this.seedThreshold = seedThreshold;
|
|
2835
|
-
}
|
|
2836
|
-
getTargetNonce(targetContractAddress) {
|
|
2837
|
-
const cleanTarget = assertEvmAddress(targetContractAddress, "targetContractAddress");
|
|
2838
|
-
return this.noncesByTarget.get(cleanTarget) ?? 0;
|
|
2839
|
-
}
|
|
2840
|
-
getState() {
|
|
2841
|
-
return {
|
|
2842
|
-
evmChainId: this.evmChainId,
|
|
2843
|
-
signerManagerAddress: this.signerManagerAddress,
|
|
2844
|
-
signers: Array.from(this.signers),
|
|
2845
|
-
seedSigners: Array.from(this.seedSigners),
|
|
2846
|
-
threshold: this.threshold,
|
|
2847
|
-
seedThreshold: this.seedThreshold
|
|
2848
|
-
};
|
|
2849
|
-
}
|
|
2850
|
-
/**
|
|
2851
|
-
* Verifies EIP-712 signatures bound to `(evmChainId, signerManagerAddress, callerTargetContract, operation, nonce, paramsHash)`
|
|
2852
|
-
* in O(N) time with strictly ascending signer order (`currentSigner > lastSigner`) and `seedThreshold` check,
|
|
2853
|
-
* then atomically increments the target contract's sequential nonce.
|
|
2854
|
-
*/
|
|
2855
|
-
ensureSignaturesForTarget(params) {
|
|
2856
|
-
const callerTarget = assertEvmAddress(params.callerTargetContract, "callerTargetContract");
|
|
2857
|
-
if (!Array.isArray(params.signatures) || params.signatures.length < this.threshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E113_INSUFFICIENT_SIGNATURES");
|
|
2858
|
-
const currentNonce = this.getTargetNonce(callerTarget);
|
|
2859
|
-
const { digest } = computeHardenedMultiSigOpDigest({
|
|
2860
|
-
evmChainId: this.evmChainId,
|
|
2861
|
-
signerManagerAddress: this.signerManagerAddress,
|
|
2862
|
-
targetContractAddress: callerTarget,
|
|
2863
|
-
operation: params.operation,
|
|
2864
|
-
nonce: currentNonce,
|
|
2865
|
-
paramsHash: params.paramsHash
|
|
2866
|
-
});
|
|
2867
|
-
let lastSignerBig = 0n;
|
|
2868
|
-
let seedSignedCount = 0;
|
|
2869
|
-
const verifiedSigners = [];
|
|
2870
|
-
for (const sig of params.signatures) {
|
|
2871
|
-
const recovered = ecrecoverEvmAddress(digest, sig.v, sig.r, sig.s);
|
|
2872
|
-
if (recovered !== assertEvmAddress(sig.signerEvmAddress, "sig.signerEvmAddress")) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E117_SIGNATURE_RECOVERY_MISMATCH");
|
|
2873
|
-
if (!this.signers.has(recovered)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E115_UNAUTHORIZED_SIGNER");
|
|
2874
|
-
const signerBig = BigInt(recovered);
|
|
2875
|
-
if (signerBig <= lastSignerBig) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E116_DUPLICATE_OR_UNSORTED_SIGNER");
|
|
2876
|
-
lastSignerBig = signerBig;
|
|
2877
|
-
if (this.seedSigners.has(recovered)) seedSignedCount += 1;
|
|
2878
|
-
verifiedSigners.push(recovered);
|
|
2879
|
-
}
|
|
2880
|
-
if (seedSignedCount < this.seedThreshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: E114_SEED_QUORUM_NOT_MET (${seedSignedCount} < ${this.seedThreshold})`);
|
|
2881
|
-
this.noncesByTarget.set(callerTarget, currentNonce + 1);
|
|
2882
|
-
return {
|
|
2883
|
-
consumedNonce: currentNonce,
|
|
2884
|
-
digest,
|
|
2885
|
-
verifiedSigners
|
|
2886
|
-
};
|
|
2887
|
-
}
|
|
2888
|
-
/**
|
|
2889
|
-
* Recoverable Seed Signer Rotation (`CRITICAL-2` fix):
|
|
2890
|
-
* Replaces a lost or rotated `oldSeedSigner` with `newSeedSigner` when authorized by a valid quorum
|
|
2891
|
-
* meeting `threshold` and `seedThreshold` (so losing 1 seed key in a 2-of-3 seed quorum never bricks the vault).
|
|
2892
|
-
*/
|
|
2893
|
-
replaceSeedSigner(params) {
|
|
2894
|
-
const oldSeed = assertEvmAddress(params.oldSeedSigner, "oldSeedSigner");
|
|
2895
|
-
const newSeed = assertEvmAddress(params.newSeedSigner, "newSeedSigner");
|
|
2896
|
-
if (!this.seedSigners.has(oldSeed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${oldSeed} is not an existing seed signer`);
|
|
2897
|
-
if (this.seedSigners.has(newSeed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${newSeed} is already a seed signer`);
|
|
2898
|
-
if (this.signers.has(newSeed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `SignerManagerV2: ${newSeed} is already an active signer; replaceSeedSigner requires a distinct replacement address`);
|
|
2899
|
-
const paramsHash = keccak256(`0x${oldSeed.slice(2).padStart(64, "0")}${newSeed.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
2900
|
-
const { consumedNonce } = this.ensureSignaturesForTarget({
|
|
2901
|
-
callerTargetContract: this.signerManagerAddress,
|
|
2902
|
-
operation: "REPLACE_SEED_SIGNER",
|
|
2903
|
-
paramsHash,
|
|
2904
|
-
signatures: params.signatures
|
|
2905
|
-
});
|
|
2906
|
-
this.seedSigners.delete(oldSeed);
|
|
2907
|
-
this.signers.delete(oldSeed);
|
|
2908
|
-
this.signers.add(newSeed);
|
|
2909
|
-
this.seedSigners.add(newSeed);
|
|
2910
|
-
if (this.signers.size < this.threshold || this.seedSigners.size < this.seedThreshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: post-rotation quorum invariant violated");
|
|
2911
|
-
return {
|
|
2912
|
-
oldSeedSigner: oldSeed,
|
|
2913
|
-
newSeedSigner: newSeed,
|
|
2914
|
-
consumedNonce
|
|
2915
|
-
};
|
|
2916
|
-
}
|
|
2917
|
-
isProposalVetoed(vledgerProposalHash) {
|
|
2918
|
-
const cleanHash = assertBytes32Hex(vledgerProposalHash, "vledgerProposalHash");
|
|
2919
|
-
return this.vetoedProposalHashes.has(cleanHash);
|
|
2920
|
-
}
|
|
2921
|
-
/**
|
|
2922
|
-
* Cross-Chain Seed Signer Veto Attestation (`RT-1262-8` & `RT-1262-9`):
|
|
2923
|
-
* Verifies an EIP-712 `MultiSigVetoAttestation` signed by an active Seed Signer and permanently blocks
|
|
2924
|
-
* `vledgerProposalHash` on the foreign chain `SignerManagerV2` contract, preventing a rogue signer from
|
|
2925
|
-
* scraping pre-veto voter signatures off VLedger and submitting them directly to the EVM contract.
|
|
2926
|
-
*/
|
|
2927
|
-
recordVetoAttestation(params) {
|
|
2928
|
-
const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
|
|
2929
|
-
const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
|
|
2930
|
-
const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
|
|
2931
|
-
if (!this.seedSigners.has(seedEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: ${seedEvmAddress} is not an authorized seed signer for veto attestation`);
|
|
2932
|
-
if (this.vetoedProposalHashes.has(vledgerProposalHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: proposal ${vledgerProposalHash} is already vetoed`);
|
|
2933
|
-
const currentNonce = this.getTargetNonce(targetContractAddress);
|
|
2934
|
-
if (!Number.isSafeInteger(params.nonce) || params.nonce < currentNonce) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: cannot record veto attestation for stale nonce (${params.nonce} < ${currentNonce})`);
|
|
2935
|
-
const { digest } = computeMultiSigVetoAttestationDigest({
|
|
2936
|
-
evmChainId: this.evmChainId,
|
|
2937
|
-
signerManagerAddress: this.signerManagerAddress,
|
|
2938
|
-
vledgerProposalHash,
|
|
2939
|
-
targetContractAddress,
|
|
2940
|
-
nonce: params.nonce,
|
|
2941
|
-
seedEvmAddress
|
|
2942
|
-
});
|
|
2943
|
-
const recovered = ecrecoverEvmAddress(digest, params.v, params.r, params.s);
|
|
2944
|
-
if (recovered !== seedEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `SignerManagerV2: veto attestation signature recovery mismatch (${recovered} !== ${seedEvmAddress})`);
|
|
2945
|
-
this.vetoedProposalHashes.add(vledgerProposalHash);
|
|
2946
|
-
return {
|
|
2947
|
-
vledgerProposalHash,
|
|
2948
|
-
seedEvmAddress,
|
|
2949
|
-
digest
|
|
2950
|
-
};
|
|
2951
|
-
}
|
|
2952
|
-
/**
|
|
2953
|
-
* Stateless Foreign-Chain Certificate Verification & Nonce Consumption (`RT-1262-8`, `RT-1262-11..15`):
|
|
2954
|
-
* Models the on-chain EVM `SignerManagerV2` contract verification without relying on VLedger's in-memory map.
|
|
2955
|
-
* Enforces:
|
|
2956
|
-
* - Cryptographic veto check (`!this.vetoedProposalHashes.has(cert.vledgerProposalHash)`)
|
|
2957
|
-
* - EIP-712 bound cooldown & TTL window (`executableAfterUnixSeconds <= nowUnixSeconds <= expiresAtUnixSeconds`)
|
|
2958
|
-
* - Full `vledgerProposalHash`, `certificateHash`, and optional `clearSigningPreview` (`paramsHash`) integrity
|
|
2959
|
-
* - Active proposer check + Seed Executor & Proposer-Executor Separation (`executor !== proposer`) for critical ops
|
|
2960
|
-
* - Holder Hardware Final Release signature + M-of-N EIP-712 voter signatures with `seedThreshold`
|
|
2961
|
-
*/
|
|
2962
|
-
verifyAndConsumePublishedCertificate(params) {
|
|
2963
|
-
if (!params || typeof params !== "object" || !params.certificate || typeof params.certificate !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate object is required");
|
|
2964
|
-
if (!params.holderReleaseSignature || typeof params.holderReleaseSignature !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: holderReleaseSignature object is required");
|
|
2965
|
-
if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nowUnixSeconds must be a positive integer");
|
|
2966
|
-
const cert = params.certificate;
|
|
2967
|
-
if (cert.kind !== "OcapPublishedMultiSigCert" || cert.schemaVersion !== 1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid certificate kind or version");
|
|
2968
|
-
if (cert.evmChainId !== this.evmChainId || assertEvmAddress(cert.signerManagerAddress, "cert.signerManagerAddress") !== this.signerManagerAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificate chainId or signerManagerAddress domain mismatch");
|
|
2969
|
-
const vledgerProposalHash = assertBytes32Hex(cert.vledgerProposalHash, "cert.vledgerProposalHash");
|
|
2970
|
-
if (this.vetoedProposalHashes.has(vledgerProposalHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${vledgerProposalHash} was vetoed by a seed signer`);
|
|
2971
|
-
const minCooldown = params.minCooldownSeconds ?? HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS;
|
|
2972
|
-
const cooldownSeconds = cert.executableAfterUnixSeconds - cert.proposedAtUnixSeconds;
|
|
2973
|
-
const ttlSeconds = cert.expiresAtUnixSeconds - cert.executableAfterUnixSeconds;
|
|
2974
|
-
if (cooldownSeconds < minCooldown) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cooldownSeconds (${cooldownSeconds}) is below minimum (${minCooldown})`);
|
|
2975
|
-
if (params.nowUnixSeconds < cert.executableAfterUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: pre-execution cooldown active until ${cert.executableAfterUnixSeconds}`);
|
|
2976
|
-
if (cert.issuedAtUnixSeconds < cert.executableAfterUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate issued before cooldown expiry (${cert.executableAfterUnixSeconds})`);
|
|
2977
|
-
if (params.nowUnixSeconds > cert.expiresAtUnixSeconds || cert.issuedAtUnixSeconds > cert.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate expired at ${cert.expiresAtUnixSeconds} (zombie certificate rejected)`);
|
|
2978
|
-
if (computeVLedgerMultiSigProposalHash({
|
|
2979
|
-
proposalId: cert.proposalId,
|
|
2980
|
-
ledgerMode: cert.ledgerMode,
|
|
2981
|
-
proposerDid: cert.proposerDid,
|
|
2982
|
-
proposerEvmAddress: cert.proposerEvmAddress,
|
|
2983
|
-
title: cert.title,
|
|
2984
|
-
rationale: cert.rationale,
|
|
2985
|
-
category: cert.category,
|
|
2986
|
-
evmChainId: cert.evmChainId,
|
|
2987
|
-
signerManagerAddress: cert.signerManagerAddress,
|
|
2988
|
-
targetContractAddress: cert.targetContractAddress,
|
|
2989
|
-
operation: cert.operation,
|
|
2990
|
-
nonce: cert.nonce,
|
|
2991
|
-
paramsHash: cert.paramsHash,
|
|
2992
|
-
proposedAtUnixSeconds: cert.proposedAtUnixSeconds,
|
|
2993
|
-
cooldownSeconds,
|
|
2994
|
-
ttlSeconds,
|
|
2995
|
-
decodedParams: cert.clearSigningPreview?.decodedParams
|
|
2996
|
-
}, { minCooldownSeconds: minCooldown }) !== vledgerProposalHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: vledgerProposalHash integrity or cross-proposal binding mismatch");
|
|
2997
|
-
if (computePublishedMultiSigCertificateHash(cert) !== cert.certificateHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificateHash integrity mismatch");
|
|
2998
|
-
if (cert.clearSigningPreview !== void 0) {
|
|
2999
|
-
const expectedPreview = buildPublishedMultiSigClearSigningPreview({
|
|
3000
|
-
targetContractAddress: cert.targetContractAddress,
|
|
3001
|
-
nonce: cert.nonce,
|
|
3002
|
-
decodedParams: cert.clearSigningPreview.decodedParams
|
|
3003
|
-
});
|
|
3004
|
-
if (JSON.stringify(expectedPreview) !== JSON.stringify(cert.clearSigningPreview)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: clearSigningPreview structural integrity mismatch");
|
|
3005
|
-
}
|
|
3006
|
-
const proposerEvmAddress = assertEvmAddress(cert.proposerEvmAddress, "cert.proposerEvmAddress");
|
|
3007
|
-
if (!this.signers.has(proposerEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} is no longer an active vault signer`);
|
|
3008
|
-
const executorEvmAddress = assertEvmAddress(params.executorEvmAddress, "executorEvmAddress");
|
|
3009
|
-
if (!this.signers.has(executorEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: executor ${executorEvmAddress} is not an authorized vault signer`);
|
|
3010
|
-
if (CRITICAL_SEED_EXECUTOR_OPERATIONS.has(cert.operation)) {
|
|
3011
|
-
if (!this.seedSigners.has(executorEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: critical operation ${cert.operation} requires a Seed Signer executor`);
|
|
3012
|
-
if (this.signers.size > 1 && executorEvmAddress === proposerEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: critical operation ${cert.operation} requires Proposer-Executor Separation (executor !== proposer)`);
|
|
3013
|
-
}
|
|
3014
|
-
const targetContractAddress = assertEvmAddress(cert.targetContractAddress, "cert.targetContractAddress");
|
|
3015
|
-
const expectedNonce = this.getTargetNonce(targetContractAddress);
|
|
3016
|
-
if (cert.nonce !== expectedNonce) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate nonce (${cert.nonce}) mismatch with current contract nonce (${expectedNonce})`);
|
|
3017
|
-
const recoveredExecutor = ecrecoverEvmAddress(computeHolderFinalReleaseDigest({
|
|
3018
|
-
evmChainId: this.evmChainId,
|
|
3019
|
-
signerManagerAddress: this.signerManagerAddress,
|
|
3020
|
-
certificateHash: cert.certificateHash,
|
|
3021
|
-
vledgerProposalHash,
|
|
3022
|
-
targetContractAddress,
|
|
3023
|
-
nonce: cert.nonce,
|
|
3024
|
-
executableAfterUnixSeconds: cert.executableAfterUnixSeconds,
|
|
3025
|
-
expiresAtUnixSeconds: cert.expiresAtUnixSeconds,
|
|
3026
|
-
executorEvmAddress
|
|
3027
|
-
}), params.holderReleaseSignature.v, params.holderReleaseSignature.r, params.holderReleaseSignature.s);
|
|
3028
|
-
if (recoveredExecutor !== executorEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: invalid holder hardware release signature (${recoveredExecutor} !== ${executorEvmAddress})`);
|
|
3029
|
-
const { digest: expectedVoteDigest } = computePublishedMultiSigVoteDigest({
|
|
3030
|
-
evmChainId: this.evmChainId,
|
|
3031
|
-
signerManagerAddress: this.signerManagerAddress,
|
|
3032
|
-
vledgerProposalHash,
|
|
3033
|
-
targetContractAddress,
|
|
3034
|
-
operation: cert.operation,
|
|
3035
|
-
nonce: cert.nonce,
|
|
3036
|
-
paramsHash: cert.paramsHash,
|
|
3037
|
-
executableAfterUnixSeconds: cert.executableAfterUnixSeconds,
|
|
3038
|
-
expiresAtUnixSeconds: cert.expiresAtUnixSeconds
|
|
3039
|
-
});
|
|
3040
|
-
let lastSignerBig = 0n;
|
|
3041
|
-
let seedSignedCount = 0;
|
|
3042
|
-
const verifiedSigners = [];
|
|
3043
|
-
for (const vote of cert.votes) {
|
|
3044
|
-
if (vote.eip712Digest !== expectedVoteDigest) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: vote eip712Digest mismatch");
|
|
3045
|
-
const recoveredVoter = ecrecoverEvmAddress(expectedVoteDigest, vote.v, vote.r, vote.s);
|
|
3046
|
-
if (recoveredVoter !== assertEvmAddress(vote.voterEvmAddress, "vote.voterEvmAddress")) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E117_VOTE_SIGNATURE_MISMATCH");
|
|
3047
|
-
if (!this.signers.has(recoveredVoter)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E115_UNAUTHORIZED_VOTER");
|
|
3048
|
-
const signerBig = BigInt(recoveredVoter);
|
|
3049
|
-
if (signerBig <= lastSignerBig) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E116_UNSORTED_OR_DUPLICATE_VOTER");
|
|
3050
|
-
lastSignerBig = signerBig;
|
|
3051
|
-
if (this.seedSigners.has(recoveredVoter)) seedSignedCount += 1;
|
|
3052
|
-
verifiedSigners.push(recoveredVoter);
|
|
3053
|
-
}
|
|
3054
|
-
if (verifiedSigners.length < this.threshold || seedSignedCount < this.seedThreshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: E113_E114_QUORUM_NOT_MET");
|
|
3055
|
-
const decoded = cert.clearSigningPreview?.decodedParams;
|
|
3056
|
-
if (cert.operation === "ADD_SIGNER" || cert.operation === "REMOVE_SIGNER" || cert.operation === "REPLACE_SEED_SIGNER" || cert.operation === "SET_THRESHOLD") {
|
|
3057
|
-
if (targetContractAddress !== this.signerManagerAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: ${cert.operation} must target signerManagerAddress (${this.signerManagerAddress})`);
|
|
3058
|
-
if (!decoded) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: ${cert.operation} requires clearSigningPreview.decodedParams for SignerManagerV2 invariant verification`);
|
|
3059
|
-
if (cert.operation === "ADD_SIGNER") {
|
|
3060
|
-
const newSigner = assertEvmAddress(decoded.signerAddress, "decodedParams.signerAddress");
|
|
3061
|
-
if (this.signers.has(newSigner) || this.signers.size >= 32) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E105_E106_INVALID_ADD_SIGNER");
|
|
3062
|
-
this.signers.add(newSigner);
|
|
3063
|
-
} else if (cert.operation === "REMOVE_SIGNER") {
|
|
3064
|
-
const oldSigner = assertEvmAddress(decoded.signerAddress, "decodedParams.signerAddress");
|
|
3065
|
-
if (this.seedSigners.has(oldSigner)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E107_CANNOT_REMOVE_SEED_SIGNER");
|
|
3066
|
-
if (!this.signers.has(oldSigner) || this.signers.size - 1 < this.threshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E104_E108_INVALID_REMOVE_SIGNER");
|
|
3067
|
-
this.signers.delete(oldSigner);
|
|
3068
|
-
} else if (cert.operation === "REPLACE_SEED_SIGNER") {
|
|
3069
|
-
const oldSeed = assertEvmAddress(decoded.oldSeedSignerAddress, "decodedParams.oldSeedSignerAddress");
|
|
3070
|
-
const newSeed = assertEvmAddress(decoded.newSeedSignerAddress, "decodedParams.newSeedSignerAddress");
|
|
3071
|
-
if (!this.seedSigners.has(oldSeed) || this.seedSigners.has(newSeed) || this.signers.has(newSeed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: INVALID_REPLACE_SEED_SIGNER");
|
|
3072
|
-
this.seedSigners.delete(oldSeed);
|
|
3073
|
-
this.signers.delete(oldSeed);
|
|
3074
|
-
this.signers.add(newSeed);
|
|
3075
|
-
this.seedSigners.add(newSeed);
|
|
3076
|
-
} else if (cert.operation === "SET_THRESHOLD") {
|
|
3077
|
-
const newThreshold = decoded.newThreshold;
|
|
3078
|
-
if (!Number.isSafeInteger(newThreshold) || newThreshold < 1 || newThreshold > this.signers.size) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "SignerManagerV2: E104_INVALID_THRESHOLD");
|
|
3079
|
-
this.threshold = newThreshold;
|
|
3080
|
-
}
|
|
3081
|
-
}
|
|
3082
|
-
this.noncesByTarget.set(targetContractAddress, expectedNonce + 1);
|
|
3083
|
-
return {
|
|
3084
|
-
consumedNonce: expectedNonce,
|
|
3085
|
-
verifiedSigners,
|
|
3086
|
-
certificateHash: cert.certificateHash,
|
|
3087
|
-
vledgerProposalHash,
|
|
3088
|
-
executorEvmAddress
|
|
3089
|
-
};
|
|
3090
|
-
}
|
|
3091
|
-
};
|
|
3092
|
-
function computeBridgeGovernanceCharterHash(state) {
|
|
3093
|
-
const validatorSummary = state.validators.map((v) => `${v.did}:${v.evmSignerAddress.toLowerCase()}:${v.role}:${v.endpoint ?? ""}`).join("|");
|
|
3094
|
-
const reserveSummary = Object.keys(state.reserves).sort().map((k) => `${k}:${state.reserves[k].totalDeposited}:${state.reserves[k].totalWithdrawn}`).join("|");
|
|
3095
|
-
const limitsSummary = [
|
|
3096
|
-
state.limits.minDepositAmount,
|
|
3097
|
-
state.limits.maxDepositAmount,
|
|
3098
|
-
state.limits.minWithdrawAmount,
|
|
3099
|
-
state.limits.maxWithdrawAmount,
|
|
3100
|
-
state.limits.maxDailyWithdrawAmount,
|
|
3101
|
-
state.limits.largeWithdrawTimelockThreshold,
|
|
3102
|
-
String(state.limits.timelockDelaySeconds)
|
|
3103
|
-
].join("|");
|
|
3104
|
-
return utf8Keccak256Hex([
|
|
3105
|
-
state.kind,
|
|
3106
|
-
state.schemaVersion,
|
|
3107
|
-
state.bridgeId,
|
|
3108
|
-
state.rollupAddress,
|
|
3109
|
-
state.ocapTokenAddress,
|
|
3110
|
-
state.supportedTokens.join(","),
|
|
3111
|
-
state.foreignChainType,
|
|
3112
|
-
state.foreignChainId,
|
|
3113
|
-
state.foreignChainName,
|
|
3114
|
-
state.foreignTokenContractAddress.toLowerCase(),
|
|
3115
|
-
state.verifyingContractAddress.toLowerCase(),
|
|
3116
|
-
state.vaultAddress.toLowerCase(),
|
|
3117
|
-
state.signerManagerAddress.toLowerCase(),
|
|
3118
|
-
state.sentinelDid,
|
|
3119
|
-
state.sentinelEvmAddress.toLowerCase(),
|
|
3120
|
-
state.guardianDid,
|
|
3121
|
-
state.migrateHistory.join(","),
|
|
3122
|
-
state.vaultHistory.join(","),
|
|
3123
|
-
validatorSummary,
|
|
3124
|
-
state.minValidatorSignatures,
|
|
3125
|
-
state.seedValidatorQuorum,
|
|
3126
|
-
state.minConfirmations,
|
|
3127
|
-
limitsSummary,
|
|
3128
|
-
state.paused ? "1" : "0",
|
|
3129
|
-
state.closed ? "1" : "0",
|
|
3130
|
-
reserveSummary,
|
|
3131
|
-
state.governanceVersion,
|
|
3132
|
-
state.lastGovernanceAction.action,
|
|
3133
|
-
state.lastGovernanceAction.ocapTxHash.toLowerCase(),
|
|
3134
|
-
state.lastGovernanceAction.blockHeight
|
|
3135
|
-
].join("::"));
|
|
3136
|
-
}
|
|
3137
|
-
var OcapOnChainBridgeGovernanceRegistry = class {
|
|
3138
|
-
constructor() {
|
|
3139
|
-
this.chartersByBridgeId = /* @__PURE__ */ new Map();
|
|
3140
|
-
}
|
|
3141
|
-
publishBridgeCharter(params) {
|
|
3142
|
-
const bridgeId = assertCleanString(params.bridgeId, "bridgeId");
|
|
3143
|
-
if (this.chartersByBridgeId.has(bridgeId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: charter for ${bridgeId} already published`);
|
|
3144
|
-
const verifyingContractAddress = assertEvmAddress(params.verifyingContractAddress, "verifyingContractAddress");
|
|
3145
|
-
const vaultAddress = assertEvmAddress(params.vaultAddress, "vaultAddress");
|
|
3146
|
-
const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
|
|
3147
|
-
const foreignTokenContractAddress = assertEvmAddress(params.foreignTokenContractAddress, "foreignTokenContractAddress");
|
|
3148
|
-
const sentinelEvmAddress = assertEvmAddress(params.sentinelEvmAddress, "sentinelEvmAddress");
|
|
3149
|
-
if (new Set([
|
|
3150
|
-
verifyingContractAddress,
|
|
3151
|
-
vaultAddress,
|
|
3152
|
-
signerManagerAddress,
|
|
3153
|
-
foreignTokenContractAddress,
|
|
3154
|
-
sentinelEvmAddress
|
|
3155
|
-
]).size !== 5) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: verifyingContractAddress, vaultAddress, signerManagerAddress, foreignTokenContractAddress, and sentinelEvmAddress must be pairwise distinct");
|
|
3156
|
-
if (!Array.isArray(params.validators) || params.validators.length < 2 || params.validators.length > 16) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: validators must contain 2..16 entries");
|
|
3157
|
-
const normalizedValidators = [];
|
|
3158
|
-
const seenDids = /* @__PURE__ */ new Set();
|
|
3159
|
-
const seenEvmAddrs = /* @__PURE__ */ new Set();
|
|
3160
|
-
let seedCount = 0;
|
|
3161
|
-
for (const v of params.validators) {
|
|
3162
|
-
const did = assertCleanString(v.did, "validator.did");
|
|
3163
|
-
const evmAddr = assertEvmAddress(v.evmSignerAddress, "validator.evmSignerAddress");
|
|
3164
|
-
if (seenDids.has(did) || seenEvmAddrs.has(evmAddr)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: duplicate validator ${did} / ${evmAddr}`);
|
|
3165
|
-
if (evmAddr === sentinelEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: sentinelEvmAddress must be strictly disjoint from hot validator signers");
|
|
3166
|
-
seenDids.add(did);
|
|
3167
|
-
seenEvmAddrs.add(evmAddr);
|
|
3168
|
-
if (v.role === "seed") seedCount += 1;
|
|
3169
|
-
normalizedValidators.push({
|
|
3170
|
-
did,
|
|
3171
|
-
evmSignerAddress: evmAddr,
|
|
3172
|
-
endpoint: v.endpoint,
|
|
3173
|
-
role: v.role
|
|
3174
|
-
});
|
|
3175
|
-
}
|
|
3176
|
-
if (seedCount === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: at least one seed validator is required");
|
|
3177
|
-
if (params.minValidatorSignatures < 2 || params.minValidatorSignatures > normalizedValidators.length) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: minValidatorSignatures must be 2..validators");
|
|
3178
|
-
const seedValidatorQuorum = params.seedValidatorQuorum ?? Math.min(seedCount, params.minValidatorSignatures);
|
|
3179
|
-
if (seedValidatorQuorum < 1 || seedValidatorQuorum > seedCount) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "BridgeGovernance: invalid seedValidatorQuorum");
|
|
3180
|
-
const ocapTokenAddress = assertCleanString(params.ocapTokenAddress, "ocapTokenAddress");
|
|
3181
|
-
const supportedTokens = Array.from(new Set([ocapTokenAddress, ...params.supportedTokens ?? []]));
|
|
3182
|
-
const reserves = {};
|
|
3183
|
-
for (const t of supportedTokens) reserves[t] = {
|
|
3184
|
-
totalDeposited: "0",
|
|
3185
|
-
totalWithdrawn: "0"
|
|
3186
|
-
};
|
|
3187
|
-
const baseState = {
|
|
3188
|
-
kind: BRIDGE_CHARTER_KIND,
|
|
3189
|
-
schemaVersion: 1,
|
|
3190
|
-
bridgeId,
|
|
3191
|
-
rollupAddress: assertCleanString(params.rollupAddress, "rollupAddress"),
|
|
3192
|
-
ocapTokenAddress,
|
|
3193
|
-
supportedTokens,
|
|
3194
|
-
foreignChainType: params.foreignChainType ?? "EVM",
|
|
3195
|
-
foreignChainId: assertCleanString(params.foreignChainId, "foreignChainId"),
|
|
3196
|
-
foreignChainName: assertCleanString(params.foreignChainName, "foreignChainName"),
|
|
3197
|
-
foreignTokenContractAddress,
|
|
3198
|
-
verifyingContractAddress,
|
|
3199
|
-
vaultAddress,
|
|
3200
|
-
signerManagerAddress,
|
|
3201
|
-
sentinelDid: assertCleanString(params.sentinelDid, "sentinelDid"),
|
|
3202
|
-
sentinelEvmAddress,
|
|
3203
|
-
guardianDid: assertCleanString(params.guardianDid, "guardianDid"),
|
|
3204
|
-
migrateHistory: [],
|
|
3205
|
-
vaultHistory: [],
|
|
3206
|
-
validators: normalizedValidators,
|
|
3207
|
-
minValidatorSignatures: params.minValidatorSignatures,
|
|
3208
|
-
seedValidatorQuorum,
|
|
3209
|
-
minConfirmations: params.minConfirmations ?? DEFAULT_MIN_EVM_CONFIRMATIONS,
|
|
3210
|
-
limits: { ...params.limits },
|
|
3211
|
-
zeroBridgeFee: true,
|
|
3212
|
-
bridgeFeeBps: 0,
|
|
3213
|
-
paused: false,
|
|
3214
|
-
closed: false,
|
|
3215
|
-
enforceReserveWatermark: true,
|
|
3216
|
-
reserves,
|
|
3217
|
-
governanceVersion: 1,
|
|
3218
|
-
lastGovernanceAction: {
|
|
3219
|
-
action: "PUBLISH",
|
|
3220
|
-
ocapTxHash: assertBytes32Hex(params.ocapTxHash, "ocapTxHash"),
|
|
3221
|
-
blockHeight: params.blockHeight
|
|
3222
|
-
}
|
|
3223
|
-
};
|
|
3224
|
-
const fullState = {
|
|
3225
|
-
...baseState,
|
|
3226
|
-
stateCommitmentHash: computeBridgeGovernanceCharterHash(baseState)
|
|
3227
|
-
};
|
|
3228
|
-
this.chartersByBridgeId.set(bridgeId, fullState);
|
|
3229
|
-
return cloneDeepCharter(fullState);
|
|
3230
|
-
}
|
|
3231
|
-
getBridgeCharter(bridgeId) {
|
|
3232
|
-
const charter = this.chartersByBridgeId.get(bridgeId);
|
|
3233
|
-
if (!charter) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: charter not found for ${bridgeId}`);
|
|
3234
|
-
return cloneDeepCharter(charter);
|
|
3235
|
-
}
|
|
3236
|
-
/**
|
|
3237
|
-
* Executes an on-chain M-of-N governed bridge state transition (`PAUSE`, `RESUME`, `MIGRATE_CONTRACT`,
|
|
3238
|
-
* `MIGRATE_VAULT`, `CLOSE`), enforcing the exact production invariants from `core/state/src/states/rollup.ts:527-630`:
|
|
3239
|
-
* - Requires `minValidatorSignatures` distinct validator DIDs and at least `seedValidatorQuorum` seed validators.
|
|
3240
|
-
* - `MIGRATE_CONTRACT` and `MIGRATE_VAULT` require `paused === true && closed === false`, reject self-migration
|
|
3241
|
-
* and cyclic reuse of any historical address in `migrateHistory` / `vaultHistory`, and append the old address
|
|
3242
|
-
* to the public on-chain linear history.
|
|
3243
|
-
*/
|
|
3244
|
-
applyGovernedTransition(params) {
|
|
3245
|
-
const charter = this.chartersByBridgeId.get(params.bridgeId);
|
|
3246
|
-
if (!charter) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `BridgeGovernance: charter not found for ${params.bridgeId}`);
|
|
3247
|
-
if (charter.closed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is permanently closed");
|
|
3248
|
-
this.verifyGovernanceSigners(charter, params.signerValidatorDids);
|
|
3249
|
-
const nextBase = {
|
|
3250
|
-
...cloneDeepCharter(charter),
|
|
3251
|
-
governanceVersion: charter.governanceVersion + 1,
|
|
3252
|
-
lastGovernanceAction: {
|
|
3253
|
-
action: params.action,
|
|
3254
|
-
ocapTxHash: assertBytes32Hex(params.ocapTxHash, "ocapTxHash"),
|
|
3255
|
-
blockHeight: params.blockHeight
|
|
3256
|
-
}
|
|
3257
|
-
};
|
|
3258
|
-
if (params.action === "PAUSE") {
|
|
3259
|
-
if (charter.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is already paused");
|
|
3260
|
-
nextBase.paused = true;
|
|
3261
|
-
} else if (params.action === "RESUME") {
|
|
3262
|
-
if (!charter.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge is not paused");
|
|
3263
|
-
nextBase.paused = false;
|
|
3264
|
-
} else if (params.action === "CLOSE") {
|
|
3265
|
-
if (!charter.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before closing");
|
|
3266
|
-
nextBase.closed = true;
|
|
3267
|
-
} else if (params.action === "MIGRATE_CONTRACT") {
|
|
3268
|
-
if (!charter.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before migrating verifyingContractAddress");
|
|
3269
|
-
const nextContract = assertEvmAddress(params.newAddress ?? "", "newContractAddress");
|
|
3270
|
-
if (nextContract === charter.verifyingContractAddress || charter.migrateHistory.includes(nextContract) || nextContract === charter.vaultAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: invalid or cyclic contract migration target ${nextContract}`);
|
|
3271
|
-
nextBase.migrateHistory = [...charter.migrateHistory, charter.verifyingContractAddress];
|
|
3272
|
-
nextBase.verifyingContractAddress = nextContract;
|
|
3273
|
-
} else if (params.action === "MIGRATE_VAULT") {
|
|
3274
|
-
if (!charter.paused) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: bridge must be paused before migrating MultiSigVault address");
|
|
3275
|
-
const nextVault = assertEvmAddress(params.newAddress ?? "", "newVaultAddress");
|
|
3276
|
-
if (nextVault === charter.vaultAddress || charter.vaultHistory.includes(nextVault) || nextVault === charter.verifyingContractAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: invalid or cyclic vault migration target ${nextVault}`);
|
|
3277
|
-
nextBase.vaultHistory = [...charter.vaultHistory, charter.vaultAddress];
|
|
3278
|
-
nextBase.vaultAddress = nextVault;
|
|
3279
|
-
}
|
|
3280
|
-
const updated = {
|
|
3281
|
-
...nextBase,
|
|
3282
|
-
stateCommitmentHash: computeBridgeGovernanceCharterHash(nextBase)
|
|
3283
|
-
};
|
|
3284
|
-
this.chartersByBridgeId.set(params.bridgeId, updated);
|
|
3285
|
-
return cloneDeepCharter(updated);
|
|
3286
|
-
}
|
|
3287
|
-
verifyGovernanceSigners(charter, signerDids) {
|
|
3288
|
-
if (!Array.isArray(signerDids) || signerDids.length < charter.minValidatorSignatures) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "BridgeGovernance: insufficient validator signatures");
|
|
3289
|
-
const byDid = new Map(charter.validators.map((v) => [v.did, v]));
|
|
3290
|
-
const uniqueSigners = /* @__PURE__ */ new Set();
|
|
3291
|
-
let seedSigned = 0;
|
|
3292
|
-
for (const rawDid of signerDids) {
|
|
3293
|
-
const did = assertCleanString(rawDid, "signerDid");
|
|
3294
|
-
if (uniqueSigners.has(did)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: duplicate governance signer ${did}`);
|
|
3295
|
-
const spec = byDid.get(did);
|
|
3296
|
-
if (!spec) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: unauthorized governance signer ${did}`);
|
|
3297
|
-
uniqueSigners.add(did);
|
|
3298
|
-
if (spec.role === "seed") seedSigned += 1;
|
|
3299
|
-
}
|
|
3300
|
-
if (seedSigned < charter.seedValidatorQuorum) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `BridgeGovernance: seed validator quorum not met (${seedSigned} < ${charter.seedValidatorQuorum})`);
|
|
3301
|
-
}
|
|
3302
|
-
};
|
|
3303
|
-
function cloneDeepCharter(c) {
|
|
3304
|
-
return JSON.parse(JSON.stringify(c));
|
|
3305
|
-
}
|
|
3306
|
-
const PUBLISHED_MULTISIG_CERT_OP_TYPEHASH = utf8Keccak256Hex("PublishedMultiSigOperation(bytes32 vledgerProposalHash,address targetContract,bytes4 selector,uint256 nonce,bytes32 paramsHash,uint256 executableAfter,uint256 expiresAt)");
|
|
3307
|
-
const HOLDER_RELEASE_INTENT_TYPEHASH = utf8Keccak256Hex("HolderReleaseIntent(bytes32 certificateHash,bytes32 vledgerProposalHash,address targetContract,uint256 nonce,uint256 executableAfter,uint256 expiresAt,address executor)");
|
|
3308
|
-
const MULTISIG_VETO_ATTESTATION_TYPEHASH = utf8Keccak256Hex("MultiSigVetoAttestation(bytes32 vledgerProposalHash,address targetContract,uint256 nonce,address seedSigner)");
|
|
3309
|
-
const HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS = 60;
|
|
3310
|
-
const DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS = 3600;
|
|
3311
|
-
const MIN_MULTISIG_CERT_TTL_SECONDS = 300;
|
|
3312
|
-
const MAX_MULTISIG_CERT_TTL_SECONDS = 30 * 86400;
|
|
3313
|
-
const DEFAULT_MULTISIG_CERT_TTL_SECONDS = 7 * 86400;
|
|
3314
|
-
const MAX_PUBLISHED_MULTISIG_PROPOSALS = 1024;
|
|
3315
|
-
const MAX_MULTISIG_VOTES_PER_CERT = 32;
|
|
3316
|
-
const ALLOWED_LEDGER_MODES = new Set(["VLEDGER", "OCAP_MAIN_CHAIN"]);
|
|
3317
|
-
const ALLOWED_PROPOSAL_CATEGORIES = new Set([
|
|
3318
|
-
"TREASURY_TRANSFER",
|
|
3319
|
-
"ALLOWANCE_UPDATE",
|
|
3320
|
-
"SIGNER_ROTATION",
|
|
3321
|
-
"BRIDGE_GOVERNANCE",
|
|
3322
|
-
"VAULT_MIGRATION"
|
|
3323
|
-
]);
|
|
3324
|
-
const EXPECTED_CATEGORY_BY_OPERATION = {
|
|
3325
|
-
SEND_ETHER: "TREASURY_TRANSFER",
|
|
3326
|
-
SEND_ERC20: "TREASURY_TRANSFER",
|
|
3327
|
-
APPROVE_ERC20: "ALLOWANCE_UPDATE",
|
|
3328
|
-
ADD_SIGNER: "SIGNER_ROTATION",
|
|
3329
|
-
REMOVE_SIGNER: "SIGNER_ROTATION",
|
|
3330
|
-
REPLACE_SEED_SIGNER: "SIGNER_ROTATION",
|
|
3331
|
-
SET_THRESHOLD: "BRIDGE_GOVERNANCE",
|
|
3332
|
-
MIGRATE_VAULT: "VAULT_MIGRATION"
|
|
3333
|
-
};
|
|
3334
|
-
const CRITICAL_SEED_EXECUTOR_OPERATIONS = new Set([
|
|
3335
|
-
"MIGRATE_VAULT",
|
|
3336
|
-
"REPLACE_SEED_SIGNER",
|
|
3337
|
-
"ADD_SIGNER",
|
|
3338
|
-
"REMOVE_SIGNER",
|
|
3339
|
-
"SET_THRESHOLD"
|
|
3340
|
-
]);
|
|
3341
|
-
function parsePositiveUint256(value, label) {
|
|
3342
|
-
const parsed = parseStrictUint256JsonValue(value, label);
|
|
3343
|
-
if (parsed <= 0n) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} must be > 0`);
|
|
3344
|
-
return parsed;
|
|
3345
|
-
}
|
|
3346
|
-
/**
|
|
3347
|
-
* Deterministic ABI-style parameter hash computation from structured `MultiSigDecodedParams` (`RT-1262-11`):
|
|
3348
|
-
* Eliminates Bybit-style blind-signing by proving that human-readable Clear-Signing fields (`tokenAddress`,
|
|
3349
|
-
* `recipientOrSpenderAddress`, `amountWei`, `newVaultAddress`, etc.) hash to the exact `paramsHash` in EIP-712.
|
|
3350
|
-
*/
|
|
3351
|
-
function computeMultiSigOperationParamsHash(decoded) {
|
|
3352
|
-
if (!decoded || typeof decoded !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: decodedParams must be an object");
|
|
3353
|
-
switch (decoded.operation) {
|
|
3354
|
-
case "SEND_ETHER": {
|
|
3355
|
-
const recipient = assertEvmAddress(decoded.recipientOrSpenderAddress ?? "", "decoded.recipientOrSpenderAddress");
|
|
3356
|
-
const amount = parsePositiveUint256(decoded.amountWei ?? "", "decoded.amountWei");
|
|
3357
|
-
return keccak256(`0x${recipient.slice(2).padStart(64, "0")}${uint256ToHex64(amount)}`).toLowerCase();
|
|
3358
|
-
}
|
|
3359
|
-
case "SEND_ERC20":
|
|
3360
|
-
case "APPROVE_ERC20": {
|
|
3361
|
-
const token = assertEvmAddress(decoded.tokenAddress ?? "", "decoded.tokenAddress");
|
|
3362
|
-
const target = assertEvmAddress(decoded.recipientOrSpenderAddress ?? "", "decoded.recipientOrSpenderAddress");
|
|
3363
|
-
const amount = parsePositiveUint256(decoded.amountWei ?? "", "decoded.amountWei");
|
|
3364
|
-
return keccak256(`0x${token.slice(2).padStart(64, "0")}${target.slice(2).padStart(64, "0")}${uint256ToHex64(amount)}`).toLowerCase();
|
|
3365
|
-
}
|
|
3366
|
-
case "ADD_SIGNER":
|
|
3367
|
-
case "REMOVE_SIGNER": return keccak256(`0x${assertEvmAddress(decoded.signerAddress ?? "", "decoded.signerAddress").slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3368
|
-
case "REPLACE_SEED_SIGNER": {
|
|
3369
|
-
const oldSeed = assertEvmAddress(decoded.oldSeedSignerAddress ?? "", "decoded.oldSeedSignerAddress");
|
|
3370
|
-
const newSeed = assertEvmAddress(decoded.newSeedSignerAddress ?? "", "decoded.newSeedSignerAddress");
|
|
3371
|
-
return keccak256(`0x${oldSeed.slice(2).padStart(64, "0")}${newSeed.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3372
|
-
}
|
|
3373
|
-
case "SET_THRESHOLD":
|
|
3374
|
-
if (!Number.isSafeInteger(decoded.newThreshold) || (decoded.newThreshold ?? 0) < 1) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: decoded.newThreshold must be a positive integer");
|
|
3375
|
-
return keccak256(`0x${uint256ToHex64(decoded.newThreshold)}`).toLowerCase();
|
|
3376
|
-
case "MIGRATE_VAULT": return keccak256(`0x${assertEvmAddress(decoded.newVaultAddress ?? "", "decoded.newVaultAddress").slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3377
|
-
default: throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: unsupported decodedParams operation ${String(decoded.operation)}`);
|
|
3378
|
-
}
|
|
3379
|
-
}
|
|
3380
|
-
function buildPublishedMultiSigClearSigningPreview(params) {
|
|
3381
|
-
const targetVault = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
|
|
3382
|
-
const d = params.decodedParams;
|
|
3383
|
-
computeMultiSigOperationParamsHash(d);
|
|
3384
|
-
let youAuthorize = "";
|
|
3385
|
-
let exactOutflow = "0";
|
|
3386
|
-
let maxTokenOutflowWei = "0";
|
|
3387
|
-
let allowedRecipientOrSpender;
|
|
3388
|
-
if (d.operation === "SEND_ETHER") {
|
|
3389
|
-
allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
|
|
3390
|
-
maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
|
|
3391
|
-
exactOutflow = `${maxTokenOutflowWei} wei NATIVE_ETH -> ${allowedRecipientOrSpender}`;
|
|
3392
|
-
youAuthorize = `SEND_ETHER (${exactOutflow}) at nonce ${params.nonce}`;
|
|
3393
|
-
} else if (d.operation === "SEND_ERC20") {
|
|
3394
|
-
const token = assertEvmAddress(d.tokenAddress, "tokenAddress");
|
|
3395
|
-
allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
|
|
3396
|
-
maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
|
|
3397
|
-
exactOutflow = `${maxTokenOutflowWei} units of ${token} -> ${allowedRecipientOrSpender}`;
|
|
3398
|
-
youAuthorize = `SEND_ERC20 (${exactOutflow}) at nonce ${params.nonce}`;
|
|
3399
|
-
} else if (d.operation === "APPROVE_ERC20") {
|
|
3400
|
-
const token = assertEvmAddress(d.tokenAddress, "tokenAddress");
|
|
3401
|
-
allowedRecipientOrSpender = assertEvmAddress(d.recipientOrSpenderAddress, "recipientOrSpenderAddress");
|
|
3402
|
-
maxTokenOutflowWei = String(parsePositiveUint256(d.amountWei, "amountWei"));
|
|
3403
|
-
exactOutflow = `ALLOWANCE ${maxTokenOutflowWei} units of ${token} for spender ${allowedRecipientOrSpender}`;
|
|
3404
|
-
youAuthorize = `APPROVE_ERC20 (${exactOutflow}) at nonce ${params.nonce}`;
|
|
3405
|
-
} else if (d.operation === "MIGRATE_VAULT") {
|
|
3406
|
-
const newVault = assertEvmAddress(d.newVaultAddress, "newVaultAddress");
|
|
3407
|
-
allowedRecipientOrSpender = newVault;
|
|
3408
|
-
exactOutflow = `ZERO_FUND_MOVEMENT_MIGRATE -> ${newVault}`;
|
|
3409
|
-
youAuthorize = `MIGRATE_VAULT to ${newVault} at nonce ${params.nonce}`;
|
|
3410
|
-
} else if (d.operation === "REPLACE_SEED_SIGNER") youAuthorize = `REPLACE_SEED_SIGNER ${assertEvmAddress(d.oldSeedSignerAddress, "oldSeedSignerAddress")} -> ${assertEvmAddress(d.newSeedSignerAddress, "newSeedSignerAddress")} at nonce ${params.nonce}`;
|
|
3411
|
-
else if (d.operation === "ADD_SIGNER" || d.operation === "REMOVE_SIGNER") {
|
|
3412
|
-
const signer = assertEvmAddress(d.signerAddress, "signerAddress");
|
|
3413
|
-
youAuthorize = `${d.operation} ${signer} at nonce ${params.nonce}`;
|
|
3414
|
-
} else if (d.operation === "SET_THRESHOLD") youAuthorize = `SET_THRESHOLD to ${d.newThreshold} at nonce ${params.nonce}`;
|
|
3415
|
-
return Object.freeze({
|
|
3416
|
-
youAuthorize,
|
|
3417
|
-
targetVault,
|
|
3418
|
-
exactOutflow,
|
|
3419
|
-
decodedParams: Object.freeze({ ...d }),
|
|
3420
|
-
postConditions: Object.freeze({
|
|
3421
|
-
strictZeroUnlistedOutflow: true,
|
|
3422
|
-
maxTokenOutflowWei,
|
|
3423
|
-
...allowedRecipientOrSpender ? { allowedRecipientOrSpender } : {}
|
|
3424
|
-
})
|
|
3425
|
-
});
|
|
3426
|
-
}
|
|
3427
|
-
function assertHumanText(value, label, maxLen = 512) {
|
|
3428
|
-
if (typeof value !== "string" || value.trim().length === 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} must be a non-empty string`);
|
|
3429
|
-
const trimmed = value.trim();
|
|
3430
|
-
if (trimmed.length > maxLen || /[\x00-\x1f\x7f]|::|\|/.test(trimmed)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ${label} exceeds max length or contains forbidden delimiters`);
|
|
3431
|
-
return trimmed;
|
|
3432
|
-
}
|
|
3433
|
-
function computeVLedgerMultiSigProposalHash(input, options) {
|
|
3434
|
-
if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal input must be an object");
|
|
3435
|
-
if (!ALLOWED_LEDGER_MODES.has(input.ledgerMode)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid ledgerMode ${String(input.ledgerMode)}`);
|
|
3436
|
-
if (!ALLOWED_PROPOSAL_CATEGORIES.has(input.category)) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid category ${String(input.category)}`);
|
|
3437
|
-
const selectorHex = MULTISIG_SELECTOR_HEX_MAP[input.operation];
|
|
3438
|
-
if (!selectorHex) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: invalid operation ${input.operation}`);
|
|
3439
|
-
const expectedCategory = EXPECTED_CATEGORY_BY_OPERATION[input.operation];
|
|
3440
|
-
if (input.category !== expectedCategory) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: semantic spoofing blocked — operation ${input.operation} requires category ${expectedCategory}, got ${input.category}`);
|
|
3441
|
-
const proposalId = assertCleanString(input.proposalId, "proposalId");
|
|
3442
|
-
const proposerDid = assertCleanString(input.proposerDid, "proposerDid");
|
|
3443
|
-
const proposerEvmAddress = assertEvmAddress(input.proposerEvmAddress, "proposerEvmAddress");
|
|
3444
|
-
const title = assertHumanText(input.title, "title", 200);
|
|
3445
|
-
const rationale = assertHumanText(input.rationale, "rationale", 1e3);
|
|
3446
|
-
const evmChainId = assertCleanString(input.evmChainId, "evmChainId");
|
|
3447
|
-
const signerManagerAddress = assertEvmAddress(input.signerManagerAddress, "signerManagerAddress");
|
|
3448
|
-
const targetContractAddress = assertEvmAddress(input.targetContractAddress, "targetContractAddress");
|
|
3449
|
-
if (!Number.isSafeInteger(input.nonce) || input.nonce < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
|
|
3450
|
-
const paramsHash = assertBytes32Hex(input.paramsHash, "paramsHash");
|
|
3451
|
-
if (input.decodedParams !== void 0) {
|
|
3452
|
-
if (input.decodedParams.operation !== input.operation) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: decodedParams.operation (${input.decodedParams.operation}) does not match proposal operation (${input.operation})`);
|
|
3453
|
-
const computedFromDecoded = computeMultiSigOperationParamsHash(input.decodedParams);
|
|
3454
|
-
if (computedFromDecoded !== paramsHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: Bybit blind-signing defense triggered — decodedParams hash (${computedFromDecoded}) does not match paramsHash (${paramsHash})`);
|
|
3455
|
-
}
|
|
3456
|
-
if (!Number.isSafeInteger(input.proposedAtUnixSeconds) || input.proposedAtUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposedAtUnixSeconds must be a positive integer");
|
|
3457
|
-
const minCooldown = Math.max(HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS, options?.minCooldownSeconds ?? HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS);
|
|
3458
|
-
const cooldownSeconds = input.cooldownSeconds ?? DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS;
|
|
3459
|
-
if (!Number.isSafeInteger(cooldownSeconds) || cooldownSeconds < minCooldown) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cooldownSeconds (${cooldownSeconds}) must be an integer >= ${minCooldown}s`);
|
|
3460
|
-
const ttlSeconds = input.ttlSeconds ?? DEFAULT_MULTISIG_CERT_TTL_SECONDS;
|
|
3461
|
-
if (!Number.isSafeInteger(ttlSeconds) || ttlSeconds < MIN_MULTISIG_CERT_TTL_SECONDS || ttlSeconds > MAX_MULTISIG_CERT_TTL_SECONDS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: ttlSeconds (${ttlSeconds}) must be within [${MIN_MULTISIG_CERT_TTL_SECONDS}, ${MAX_MULTISIG_CERT_TTL_SECONDS}]`);
|
|
3462
|
-
const clearSigningPreviewHash = input.decodedParams !== void 0 ? utf8Keccak256Hex(JSON.stringify(buildPublishedMultiSigClearSigningPreview({
|
|
3463
|
-
targetContractAddress,
|
|
3464
|
-
nonce: input.nonce,
|
|
3465
|
-
decodedParams: input.decodedParams
|
|
3466
|
-
}))) : ZERO_BYTES32_HASH;
|
|
3467
|
-
return utf8Keccak256Hex([
|
|
3468
|
-
"ocap:published-multisig-proposal:v1",
|
|
3469
|
-
input.ledgerMode,
|
|
3470
|
-
proposalId,
|
|
3471
|
-
proposerDid,
|
|
3472
|
-
proposerEvmAddress,
|
|
3473
|
-
input.category,
|
|
3474
|
-
title,
|
|
3475
|
-
rationale,
|
|
3476
|
-
evmChainId,
|
|
3477
|
-
signerManagerAddress,
|
|
3478
|
-
targetContractAddress,
|
|
3479
|
-
selectorHex,
|
|
3480
|
-
String(input.nonce),
|
|
3481
|
-
paramsHash,
|
|
3482
|
-
String(input.proposedAtUnixSeconds),
|
|
3483
|
-
String(cooldownSeconds),
|
|
3484
|
-
String(ttlSeconds),
|
|
3485
|
-
clearSigningPreviewHash
|
|
3486
|
-
].join("::"));
|
|
3487
|
-
}
|
|
3488
|
-
/**
|
|
3489
|
-
* Computes the canonical, tamper-evident hash over all fields of an `OcapPublishedMultiSigCertificate` (RT-1262-3, RT-1262-15).
|
|
3490
|
-
*/
|
|
3491
|
-
function computePublishedMultiSigCertificateHash(cert) {
|
|
3492
|
-
const selectorHex = MULTISIG_SELECTOR_HEX_MAP[cert.operation];
|
|
3493
|
-
if (!selectorHex || cert.selectorHex !== selectorHex) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate selectorHex mismatch");
|
|
3494
|
-
if (!Array.isArray(cert.votes) || cert.votes.length === 0 || cert.votes.length > MAX_MULTISIG_VOTES_PER_CERT) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: certificate votes must contain 1..${MAX_MULTISIG_VOTES_PER_CERT} entries`);
|
|
3495
|
-
const serializedVotes = cert.votes.map((v) => [
|
|
3496
|
-
utf8Keccak256Hex(assertCleanString(v.voterDid, "vote.voterDid")),
|
|
3497
|
-
assertEvmAddress(v.voterEvmAddress, "vote.voterEvmAddress"),
|
|
3498
|
-
utf8Keccak256Hex(assertHumanText(v.comment, "vote.comment", 500)),
|
|
3499
|
-
String(v.votedAtUnixSeconds),
|
|
3500
|
-
String(v.v),
|
|
3501
|
-
assertBytes32Hex(v.r, "vote.r"),
|
|
3502
|
-
assertBytes32Hex(v.s, "vote.s"),
|
|
3503
|
-
assertBytes32Hex(v.eip712Digest, "vote.eip712Digest")
|
|
3504
|
-
].join(":")).join("|");
|
|
3505
|
-
const clearSigningPreviewHash = cert.clearSigningPreview ? utf8Keccak256Hex(JSON.stringify(cert.clearSigningPreview)) : ZERO_BYTES32_HASH;
|
|
3506
|
-
return utf8Keccak256Hex([
|
|
3507
|
-
"ocap:published-multisig-cert:v1",
|
|
3508
|
-
cert.kind,
|
|
3509
|
-
String(cert.schemaVersion),
|
|
3510
|
-
assertCleanString(cert.proposalId, "cert.proposalId"),
|
|
3511
|
-
cert.ledgerMode,
|
|
3512
|
-
assertBytes32Hex(cert.vledgerProposalHash, "cert.vledgerProposalHash"),
|
|
3513
|
-
assertBytes32Hex(cert.vledgerStateRoot, "cert.vledgerStateRoot"),
|
|
3514
|
-
assertCleanString(cert.proposerDid, "cert.proposerDid"),
|
|
3515
|
-
assertEvmAddress(cert.proposerEvmAddress, "cert.proposerEvmAddress"),
|
|
3516
|
-
assertHumanText(cert.title, "cert.title", 200),
|
|
3517
|
-
assertHumanText(cert.rationale, "cert.rationale", 1e3),
|
|
3518
|
-
cert.category,
|
|
3519
|
-
assertCleanString(cert.evmChainId, "cert.evmChainId"),
|
|
3520
|
-
assertEvmAddress(cert.signerManagerAddress, "cert.signerManagerAddress"),
|
|
3521
|
-
assertEvmAddress(cert.targetContractAddress, "cert.targetContractAddress"),
|
|
3522
|
-
cert.operation,
|
|
3523
|
-
selectorHex,
|
|
3524
|
-
String(cert.nonce),
|
|
3525
|
-
assertBytes32Hex(cert.paramsHash, "cert.paramsHash"),
|
|
3526
|
-
String(cert.proposedAtUnixSeconds),
|
|
3527
|
-
String(cert.executableAfterUnixSeconds),
|
|
3528
|
-
String(cert.expiresAtUnixSeconds),
|
|
3529
|
-
String(cert.issuedAtUnixSeconds),
|
|
3530
|
-
clearSigningPreviewHash,
|
|
3531
|
-
serializedVotes
|
|
3532
|
-
].join("::"));
|
|
3533
|
-
}
|
|
3534
|
-
function freezePublishedCertificate(cert) {
|
|
3535
|
-
const clonedVotes = cert.votes.map((v) => Object.freeze({ ...v }));
|
|
3536
|
-
return Object.freeze({
|
|
3537
|
-
...cert,
|
|
3538
|
-
...cert.clearSigningPreview ? { clearSigningPreview: Object.freeze({ ...cert.clearSigningPreview }) } : {},
|
|
3539
|
-
votes: Object.freeze(clonedVotes)
|
|
3540
|
-
});
|
|
3541
|
-
}
|
|
3542
|
-
/**
|
|
3543
|
-
* Computes the EIP-712 digest for a Published Indirect Multi-Sig Vote (`seq: 508..511`, Issue #1262):
|
|
3544
|
-
* Binds `vledgerProposalHash`, `executableAfterUnixSeconds`, and `expiresAtUnixSeconds` directly into
|
|
3545
|
-
* the foreign chain `MultiSigVaultV2` / `SignerManagerV2` EIP-712 struct hash (`RT-1262-8`, `RT-1262-13`).
|
|
3546
|
-
*/
|
|
3547
|
-
function computePublishedMultiSigVoteDigest(params) {
|
|
3548
|
-
const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
|
|
3549
|
-
if (!Number.isSafeInteger(params.executableAfterUnixSeconds) || params.executableAfterUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.executableAfterUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid executableAfterUnixSeconds or expiresAtUnixSeconds");
|
|
3550
|
-
const base = computeHardenedMultiSigOpDigest({
|
|
3551
|
-
evmChainId: params.evmChainId,
|
|
3552
|
-
signerManagerAddress: params.signerManagerAddress,
|
|
3553
|
-
targetContractAddress: params.targetContractAddress,
|
|
3554
|
-
operation: params.operation,
|
|
3555
|
-
nonce: params.nonce,
|
|
3556
|
-
paramsHash: params.paramsHash
|
|
3557
|
-
});
|
|
3558
|
-
const targetWord64 = assertEvmAddress(params.targetContractAddress, "targetContractAddress").slice(2).padStart(64, "0");
|
|
3559
|
-
const selectorWord = base.selectorHex.slice(2).toLowerCase().padEnd(64, "0");
|
|
3560
|
-
const paramsHash = assertBytes32Hex(params.paramsHash, "paramsHash");
|
|
3561
|
-
const structHash = keccak256(`0x${PUBLISHED_MULTISIG_CERT_OP_TYPEHASH.slice(2)}${vledgerProposalHash.slice(2)}${targetWord64}${selectorWord}${uint256ToHex64(params.nonce)}${paramsHash.slice(2)}${uint256ToHex64(params.executableAfterUnixSeconds)}${uint256ToHex64(params.expiresAtUnixSeconds)}`).toLowerCase();
|
|
3562
|
-
const digest = keccak256(`0x1901${base.domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
|
|
3563
|
-
return {
|
|
3564
|
-
domainSeparator: base.domainSeparator,
|
|
3565
|
-
structHash,
|
|
3566
|
-
digest,
|
|
3567
|
-
selectorHex: base.selectorHex
|
|
3568
|
-
};
|
|
3569
|
-
}
|
|
3570
|
-
/**
|
|
3571
|
-
* Computes the EIP-712 Seed Signer Veto Attestation Digest (`RT-1262-9`):
|
|
3572
|
-
* Allows any Seed Signer to cryptographically sign a veto that is enforced both on VLedger and on the
|
|
3573
|
-
* foreign-chain `SignerManagerV2` contract (`recordVetoAttestation`).
|
|
3574
|
-
*/
|
|
3575
|
-
function computeMultiSigVetoAttestationDigest(params) {
|
|
3576
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
3577
|
-
const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
|
|
3578
|
-
const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
|
|
3579
|
-
const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
|
|
3580
|
-
const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
|
|
3581
|
-
if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
|
|
3582
|
-
const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
|
|
3583
|
-
const versionHash = utf8Keccak256Hex("2").slice(2);
|
|
3584
|
-
const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
|
|
3585
|
-
const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerAddress.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3586
|
-
const structHash = keccak256(`0x${MULTISIG_VETO_ATTESTATION_TYPEHASH.slice(2)}${vledgerProposalHash.slice(2)}${targetContractAddress.slice(2).padStart(64, "0")}${uint256ToHex64(params.nonce)}${seedEvmAddress.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3587
|
-
return {
|
|
3588
|
-
domainSeparator,
|
|
3589
|
-
structHash,
|
|
3590
|
-
digest: keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase()
|
|
3591
|
-
};
|
|
3592
|
-
}
|
|
3593
|
-
/**
|
|
3594
|
-
* Computes the Holder Hardware Final Release Intent Digest (`seq: 508..511`, Issue #1262):
|
|
3595
|
-
* Because OCAP software nodes never hold custody keys or auto-sign foreign chain transactions,
|
|
3596
|
-
* an authorized human executor must sign this Final Release Intent with their hardware key
|
|
3597
|
-
* when submitting the `OcapPublishedMultiSigCertificate` to the foreign chain contract.
|
|
3598
|
-
*/
|
|
3599
|
-
function computeHolderFinalReleaseDigest(params) {
|
|
3600
|
-
const evmChainId = assertCleanString(params.evmChainId, "evmChainId");
|
|
3601
|
-
const signerManagerAddress = assertEvmAddress(params.signerManagerAddress, "signerManagerAddress");
|
|
3602
|
-
const certificateHash = assertBytes32Hex(params.certificateHash, "certificateHash");
|
|
3603
|
-
const vledgerProposalHash = assertBytes32Hex(params.vledgerProposalHash, "vledgerProposalHash");
|
|
3604
|
-
const targetContractAddress = assertEvmAddress(params.targetContractAddress, "targetContractAddress");
|
|
3605
|
-
const executorEvmAddress = assertEvmAddress(params.executorEvmAddress, "executorEvmAddress");
|
|
3606
|
-
if (!Number.isSafeInteger(params.nonce) || params.nonce < 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nonce must be a non-negative integer");
|
|
3607
|
-
if (!Number.isSafeInteger(params.executableAfterUnixSeconds) || params.executableAfterUnixSeconds <= 0 || !Number.isSafeInteger(params.expiresAtUnixSeconds) || params.expiresAtUnixSeconds <= params.executableAfterUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: invalid executableAfterUnixSeconds or expiresAtUnixSeconds");
|
|
3608
|
-
const nameHash = utf8Keccak256Hex("ArcMultiSigSignerManagerV2").slice(2);
|
|
3609
|
-
const versionHash = utf8Keccak256Hex("2").slice(2);
|
|
3610
|
-
const chainIdHex64 = CANONICAL_UINT256_DECIMAL_REGEX.test(evmChainId) ? uint256ToHex64(BigInt(evmChainId)) : utf8Keccak256Hex(evmChainId).slice(2);
|
|
3611
|
-
const domainSeparator = keccak256(`0x${EIP712_DOMAIN_TYPEHASH.slice(2)}${nameHash}${versionHash}${chainIdHex64}${signerManagerAddress.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3612
|
-
const structHash = keccak256(`0x${HOLDER_RELEASE_INTENT_TYPEHASH.slice(2)}${certificateHash.slice(2)}${vledgerProposalHash.slice(2)}${targetContractAddress.slice(2).padStart(64, "0")}${uint256ToHex64(params.nonce)}${uint256ToHex64(params.executableAfterUnixSeconds)}${uint256ToHex64(params.expiresAtUnixSeconds)}${executorEvmAddress.slice(2).padStart(64, "0")}`).toLowerCase();
|
|
3613
|
-
return keccak256(`0x1901${domainSeparator.slice(2)}${structHash.slice(2)}`).toLowerCase();
|
|
3614
|
-
}
|
|
3615
|
-
/**
|
|
3616
|
-
* Standardized Published Indirect Multi-Sig Engine (`OcapPublishedMultiSigEngine`, Issue #1262):
|
|
3617
|
-
* Implements the 3-stage VLedger / OCAP Certificate-Driven Cross-Chain Control Plane:
|
|
3618
|
-
* 1. Public Proposal & Vote History on VLedger / OCAP (with pre-execution notifications, cooldowns, and cryptographic Veto).
|
|
3619
|
-
* 2. Deterministic `OcapPublishedMultiSigCertificate` generation once M-of-N (`threshold` + `seedThreshold`) is met.
|
|
3620
|
-
* 3. Foreign-chain `MultiSigVaultV2` execution gated by BOTH the published certificate AND an individual holder's
|
|
3621
|
-
* hardware Final Release Signature (zero software custody on OCAP nodes).
|
|
3622
|
-
*/
|
|
3623
|
-
var OcapPublishedMultiSigEngine = class {
|
|
3624
|
-
constructor(signerManager, options) {
|
|
3625
|
-
this.proposals = /* @__PURE__ */ new Map();
|
|
3626
|
-
this.vledgerSequence = 0;
|
|
3627
|
-
this.vledgerStateRoot = ZERO_BYTES32_HASH;
|
|
3628
|
-
this.signerManager = signerManager;
|
|
3629
|
-
const minCooldown = options?.minCooldownSeconds ?? DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS;
|
|
3630
|
-
if (!Number.isSafeInteger(minCooldown) || minCooldown < HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: minCooldownSeconds must be an integer >= ${HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS}`);
|
|
3631
|
-
this.minCooldownSeconds = minCooldown;
|
|
3632
|
-
}
|
|
3633
|
-
getVLedgerStateRoot() {
|
|
3634
|
-
return this.vledgerStateRoot;
|
|
3635
|
-
}
|
|
3636
|
-
getProposalStatus(proposalId, nowUnixSeconds) {
|
|
3637
|
-
const prop = this.proposals.get(proposalId);
|
|
3638
|
-
if (!prop) return void 0;
|
|
3639
|
-
if (prop.vetoed) return "VETOED";
|
|
3640
|
-
if (prop.executed) return "EXECUTED";
|
|
3641
|
-
if (nowUnixSeconds !== void 0 && nowUnixSeconds > prop.expiresAtUnixSeconds) return "EXPIRED";
|
|
3642
|
-
if (prop.issuedCert) return "CERT_ISSUED";
|
|
3643
|
-
return "VOTING";
|
|
3644
|
-
}
|
|
3645
|
-
createProposal(input) {
|
|
3646
|
-
if (!input || typeof input !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal input must be an object");
|
|
3647
|
-
if (this.proposals.size >= MAX_PUBLISHED_MULTISIG_PROPOSALS) for (const [id, existing] of this.proposals.entries()) {
|
|
3648
|
-
const targetNonce = this.signerManager.getTargetNonce(existing.input.targetContractAddress);
|
|
3649
|
-
if (existing.vetoed || existing.executed || existing.input.nonce < targetNonce || Number.isSafeInteger(input.proposedAtUnixSeconds) && input.proposedAtUnixSeconds > existing.expiresAtUnixSeconds) this.proposals.delete(id);
|
|
3650
|
-
}
|
|
3651
|
-
if (this.proposals.size >= MAX_PUBLISHED_MULTISIG_PROPOSALS) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: active proposal pool reached cap (${MAX_PUBLISHED_MULTISIG_PROPOSALS})`);
|
|
3652
|
-
const proposalId = assertCleanString(input.proposalId, "proposalId");
|
|
3653
|
-
if (this.proposals.has(proposalId)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: duplicate proposalId ${proposalId}`);
|
|
3654
|
-
const proposerEvmAddress = assertEvmAddress(input.proposerEvmAddress, "proposerEvmAddress");
|
|
3655
|
-
const managerState = this.signerManager.getState();
|
|
3656
|
-
if (!managerState.signers.includes(proposerEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} is not an authorized vault signer`);
|
|
3657
|
-
if (input.evmChainId !== managerState.evmChainId || assertEvmAddress(input.signerManagerAddress, "signerManagerAddress") !== managerState.signerManagerAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: proposal chainId or signerManagerAddress mismatch");
|
|
3658
|
-
const targetContractAddress = assertEvmAddress(input.targetContractAddress, "targetContractAddress");
|
|
3659
|
-
const expectedNonce = this.signerManager.getTargetNonce(targetContractAddress);
|
|
3660
|
-
if (input.nonce !== expectedNonce) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal nonce (${input.nonce}) does not match target contract nonce (${expectedNonce})`);
|
|
3661
|
-
for (const existing of this.proposals.values()) if (!existing.vetoed && !existing.executed && existing.input.targetContractAddress === targetContractAddress && existing.input.nonce === expectedNonce && existing.input.proposerEvmAddress === proposerEvmAddress && input.proposedAtUnixSeconds <= existing.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${proposerEvmAddress} already has an active proposal (${existing.input.proposalId}) for ${targetContractAddress} at nonce ${expectedNonce}`);
|
|
3662
|
-
const cooldownSeconds = input.cooldownSeconds ?? this.minCooldownSeconds;
|
|
3663
|
-
const ttlSeconds = input.ttlSeconds ?? DEFAULT_MULTISIG_CERT_TTL_SECONDS;
|
|
3664
|
-
const normalizedInput = {
|
|
3665
|
-
...input,
|
|
3666
|
-
proposerEvmAddress,
|
|
3667
|
-
signerManagerAddress: managerState.signerManagerAddress,
|
|
3668
|
-
targetContractAddress,
|
|
3669
|
-
paramsHash: assertBytes32Hex(input.paramsHash, "paramsHash"),
|
|
3670
|
-
cooldownSeconds,
|
|
3671
|
-
ttlSeconds
|
|
3672
|
-
};
|
|
3673
|
-
const vledgerProposalHash = computeVLedgerMultiSigProposalHash(normalizedInput, { minCooldownSeconds: this.minCooldownSeconds });
|
|
3674
|
-
const executableAfterUnixSeconds = normalizedInput.proposedAtUnixSeconds + cooldownSeconds;
|
|
3675
|
-
const expiresAtUnixSeconds = executableAfterUnixSeconds + ttlSeconds;
|
|
3676
|
-
const clearSigningPreview = normalizedInput.decodedParams ? buildPublishedMultiSigClearSigningPreview({
|
|
3677
|
-
targetContractAddress,
|
|
3678
|
-
nonce: normalizedInput.nonce,
|
|
3679
|
-
decodedParams: normalizedInput.decodedParams
|
|
3680
|
-
}) : void 0;
|
|
3681
|
-
this.vledgerSequence += 1;
|
|
3682
|
-
this.vledgerStateRoot = utf8Keccak256Hex(`vledger:propose:${this.vledgerSequence}:${this.vledgerStateRoot}:${vledgerProposalHash}`);
|
|
3683
|
-
this.proposals.set(proposalId, {
|
|
3684
|
-
input: normalizedInput,
|
|
3685
|
-
vledgerProposalHash,
|
|
3686
|
-
executableAfterUnixSeconds,
|
|
3687
|
-
expiresAtUnixSeconds,
|
|
3688
|
-
clearSigningPreview,
|
|
3689
|
-
vetoed: false,
|
|
3690
|
-
executed: false,
|
|
3691
|
-
votesBySigner: /* @__PURE__ */ new Map(),
|
|
3692
|
-
voterDids: /* @__PURE__ */ new Set()
|
|
3693
|
-
});
|
|
3694
|
-
return {
|
|
3695
|
-
proposalId,
|
|
3696
|
-
vledgerProposalHash,
|
|
3697
|
-
executableAfterUnixSeconds,
|
|
3698
|
-
expiresAtUnixSeconds,
|
|
3699
|
-
...clearSigningPreview ? { clearSigningPreview } : {},
|
|
3700
|
-
vledgerStateRoot: this.vledgerStateRoot
|
|
3701
|
-
};
|
|
3702
|
-
}
|
|
3703
|
-
recordVote(params) {
|
|
3704
|
-
const prop = this.proposals.get(params.proposalId);
|
|
3705
|
-
if (!prop) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
|
|
3706
|
-
if (prop.vetoed || this.signerManager.isProposalVetoed(prop.vledgerProposalHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has been vetoed (${prop.vetoReason ?? "on-chain veto"})`);
|
|
3707
|
-
if (prop.executed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has already been executed`);
|
|
3708
|
-
if (prop.issuedCert) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate already issued for proposal ${params.proposalId}`);
|
|
3709
|
-
const currentNonce = this.signerManager.getTargetNonce(prop.input.targetContractAddress);
|
|
3710
|
-
if (prop.input.nonce !== currentNonce) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot vote on stale proposal nonce (${prop.input.nonce} !== ${currentNonce})`);
|
|
3711
|
-
if (!Number.isSafeInteger(params.votedAtUnixSeconds) || params.votedAtUnixSeconds < prop.input.proposedAtUnixSeconds || params.votedAtUnixSeconds > prop.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: votedAtUnixSeconds must be within [${prop.input.proposedAtUnixSeconds}, ${prop.expiresAtUnixSeconds}]`);
|
|
3712
|
-
const voterDid = assertCleanString(params.voterDid, "voterDid");
|
|
3713
|
-
const voterEvmAddress = assertEvmAddress(params.voterEvmAddress, "voterEvmAddress");
|
|
3714
|
-
const comment = assertHumanText(params.comment, "comment", 500);
|
|
3715
|
-
if (!this.signerManager.getState().signers.includes(voterEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: voter ${voterEvmAddress} is not an authorized vault signer`);
|
|
3716
|
-
if (prop.votesBySigner.has(voterEvmAddress) || prop.voterDids.has(voterDid)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: duplicate vote from signer ${voterEvmAddress} (${voterDid})`);
|
|
3717
|
-
const { digest } = computePublishedMultiSigVoteDigest({
|
|
3718
|
-
evmChainId: prop.input.evmChainId,
|
|
3719
|
-
signerManagerAddress: prop.input.signerManagerAddress,
|
|
3720
|
-
vledgerProposalHash: prop.vledgerProposalHash,
|
|
3721
|
-
targetContractAddress: prop.input.targetContractAddress,
|
|
3722
|
-
operation: prop.input.operation,
|
|
3723
|
-
nonce: prop.input.nonce,
|
|
3724
|
-
paramsHash: prop.input.paramsHash,
|
|
3725
|
-
executableAfterUnixSeconds: prop.executableAfterUnixSeconds,
|
|
3726
|
-
expiresAtUnixSeconds: prop.expiresAtUnixSeconds
|
|
3727
|
-
});
|
|
3728
|
-
const recovered = ecrecoverEvmAddress(digest, params.v, params.r, params.s);
|
|
3729
|
-
if (recovered !== voterEvmAddress) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: vote signature recovery mismatch (${recovered} !== ${voterEvmAddress})`);
|
|
3730
|
-
const voteRecord = Object.freeze({
|
|
3731
|
-
voterDid,
|
|
3732
|
-
voterEvmAddress,
|
|
3733
|
-
comment,
|
|
3734
|
-
votedAtUnixSeconds: params.votedAtUnixSeconds,
|
|
3735
|
-
v: params.v,
|
|
3736
|
-
r: assertBytes32Hex(params.r, "r"),
|
|
3737
|
-
s: assertBytes32Hex(params.s, "s"),
|
|
3738
|
-
eip712Digest: digest
|
|
3739
|
-
});
|
|
3740
|
-
prop.votesBySigner.set(voterEvmAddress, voteRecord);
|
|
3741
|
-
prop.voterDids.add(voterDid);
|
|
3742
|
-
this.vledgerSequence += 1;
|
|
3743
|
-
this.vledgerStateRoot = utf8Keccak256Hex(`vledger:vote:${this.vledgerSequence}:${this.vledgerStateRoot}:${prop.vledgerProposalHash}:${voterEvmAddress}:${digest}`);
|
|
3744
|
-
return {
|
|
3745
|
-
proposalId: params.proposalId,
|
|
3746
|
-
totalVotes: prop.votesBySigner.size,
|
|
3747
|
-
vledgerStateRoot: this.vledgerStateRoot
|
|
3748
|
-
};
|
|
3749
|
-
}
|
|
3750
|
-
/**
|
|
3751
|
-
* Cryptographically Authenticated Seed Signer Veto (`RT-1262-8` & `RT-1262-9`):
|
|
3752
|
-
* Verifies the Seed Signer's EIP-712 `MultiSigVetoAttestation` signature via `ecrecover` and records the
|
|
3753
|
-
* veto on BOTH VLedger (`prop.vetoed = true`) AND the foreign-chain `SignerManagerV2` contract
|
|
3754
|
-
* (`this.signerManager.recordVetoAttestation`), blocking off-chain signature scraping bypasses.
|
|
3755
|
-
*/
|
|
3756
|
-
vetoProposal(params) {
|
|
3757
|
-
const prop = this.proposals.get(params.proposalId);
|
|
3758
|
-
if (!prop) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
|
|
3759
|
-
if (prop.executed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot veto proposal ${params.proposalId} after execution`);
|
|
3760
|
-
if (prop.vetoed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} is already vetoed`);
|
|
3761
|
-
const seedEvmAddress = assertEvmAddress(params.seedEvmAddress, "seedEvmAddress");
|
|
3762
|
-
const guardianOrSeedDid = assertCleanString(params.guardianOrSeedDid, "guardianOrSeedDid");
|
|
3763
|
-
const reason = assertHumanText(params.reason, "reason", 500);
|
|
3764
|
-
const { digest } = this.signerManager.recordVetoAttestation({
|
|
3765
|
-
vledgerProposalHash: prop.vledgerProposalHash,
|
|
3766
|
-
targetContractAddress: prop.input.targetContractAddress,
|
|
3767
|
-
nonce: prop.input.nonce,
|
|
3768
|
-
seedEvmAddress,
|
|
3769
|
-
v: params.v,
|
|
3770
|
-
r: params.r,
|
|
3771
|
-
s: params.s
|
|
3772
|
-
});
|
|
3773
|
-
prop.vetoed = true;
|
|
3774
|
-
prop.vetoedByDid = guardianOrSeedDid;
|
|
3775
|
-
prop.vetoReason = reason;
|
|
3776
|
-
prop.vetoAttestationDigest = digest;
|
|
3777
|
-
this.vledgerSequence += 1;
|
|
3778
|
-
this.vledgerStateRoot = utf8Keccak256Hex(`vledger:veto:${this.vledgerSequence}:${this.vledgerStateRoot}:${prop.vledgerProposalHash}:${seedEvmAddress}:${digest}`);
|
|
3779
|
-
return {
|
|
3780
|
-
vledgerProposalHash: prop.vledgerProposalHash,
|
|
3781
|
-
vetoAttestationDigest: digest,
|
|
3782
|
-
vledgerStateRoot: this.vledgerStateRoot
|
|
3783
|
-
};
|
|
3784
|
-
}
|
|
3785
|
-
/**
|
|
3786
|
-
* Stage 2: Crystallizes the verified vote records into an immutable `OcapPublishedMultiSigCertificate`
|
|
3787
|
-
* once M-of-N (`threshold` + `seedThreshold`) is met and `executableAfterUnixSeconds <= nowUnixSeconds <= expiresAtUnixSeconds`.
|
|
3788
|
-
*/
|
|
3789
|
-
issuePublishedCertificate(params) {
|
|
3790
|
-
const prop = this.proposals.get(params.proposalId);
|
|
3791
|
-
if (!prop) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} not found`);
|
|
3792
|
-
if (prop.vetoed || this.signerManager.isProposalVetoed(prop.vledgerProposalHash)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: cannot issue certificate for vetoed proposal (${prop.vetoReason ?? "on-chain veto"})`);
|
|
3793
|
-
if (prop.executed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal ${params.proposalId} has already been executed`);
|
|
3794
|
-
if (prop.issuedCert) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate already issued for proposal ${params.proposalId}`);
|
|
3795
|
-
if (!Number.isSafeInteger(params.nowUnixSeconds) || params.nowUnixSeconds <= 0) throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: nowUnixSeconds must be a positive integer");
|
|
3796
|
-
if (params.nowUnixSeconds < prop.executableAfterUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal is still in OCAP/VLedger cooldown until ${prop.executableAfterUnixSeconds}`);
|
|
3797
|
-
if (params.nowUnixSeconds > prop.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposal expired at ${prop.expiresAtUnixSeconds}`);
|
|
3798
|
-
const currentNonce = this.signerManager.getTargetNonce(prop.input.targetContractAddress);
|
|
3799
|
-
if (prop.input.nonce !== currentNonce) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: stale proposal nonce (${prop.input.nonce} !== ${currentNonce})`);
|
|
3800
|
-
const managerState = this.signerManager.getState();
|
|
3801
|
-
if (!managerState.signers.includes(prop.input.proposerEvmAddress)) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: proposer ${prop.input.proposerEvmAddress} is no longer an active vault signer`);
|
|
3802
|
-
for (const [otherId, other] of this.proposals.entries()) if (otherId !== params.proposalId && other.issuedCert && !other.vetoed && !other.executed && other.input.targetContractAddress === prop.input.targetContractAddress && other.input.nonce === currentNonce && params.nowUnixSeconds <= other.expiresAtUnixSeconds) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: another active certificate (${otherId}) is already issued for ${prop.input.targetContractAddress} at nonce ${currentNonce}`);
|
|
3803
|
-
const activeVotes = Array.from(prop.votesBySigner.values()).filter((v) => managerState.signers.includes(v.voterEvmAddress)).sort((a, b) => BigInt(a.voterEvmAddress) < BigInt(b.voterEvmAddress) ? -1 : 1);
|
|
3804
|
-
if (activeVotes.length < managerState.threshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: insufficient active votes (${activeVotes.length} < ${managerState.threshold})`);
|
|
3805
|
-
const seedSignedCount = activeVotes.filter((v) => managerState.seedSigners.includes(v.voterEvmAddress)).length;
|
|
3806
|
-
if (seedSignedCount < managerState.seedThreshold) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: insufficient seed signer votes (${seedSignedCount} < ${managerState.seedThreshold})`);
|
|
3807
|
-
const selectorHex = MULTISIG_SELECTOR_HEX_MAP[prop.input.operation];
|
|
3808
|
-
const unsignedCert = {
|
|
3809
|
-
kind: "OcapPublishedMultiSigCert",
|
|
3810
|
-
schemaVersion: 1,
|
|
3811
|
-
proposalId: prop.input.proposalId,
|
|
3812
|
-
ledgerMode: prop.input.ledgerMode,
|
|
3813
|
-
vledgerProposalHash: prop.vledgerProposalHash,
|
|
3814
|
-
vledgerStateRoot: this.vledgerStateRoot,
|
|
3815
|
-
proposerDid: prop.input.proposerDid,
|
|
3816
|
-
proposerEvmAddress: prop.input.proposerEvmAddress,
|
|
3817
|
-
title: prop.input.title,
|
|
3818
|
-
rationale: prop.input.rationale,
|
|
3819
|
-
category: prop.input.category,
|
|
3820
|
-
evmChainId: prop.input.evmChainId,
|
|
3821
|
-
signerManagerAddress: prop.input.signerManagerAddress,
|
|
3822
|
-
targetContractAddress: prop.input.targetContractAddress,
|
|
3823
|
-
operation: prop.input.operation,
|
|
3824
|
-
selectorHex,
|
|
3825
|
-
nonce: prop.input.nonce,
|
|
3826
|
-
paramsHash: prop.input.paramsHash,
|
|
3827
|
-
proposedAtUnixSeconds: prop.input.proposedAtUnixSeconds,
|
|
3828
|
-
executableAfterUnixSeconds: prop.executableAfterUnixSeconds,
|
|
3829
|
-
expiresAtUnixSeconds: prop.expiresAtUnixSeconds,
|
|
3830
|
-
issuedAtUnixSeconds: params.nowUnixSeconds,
|
|
3831
|
-
...prop.clearSigningPreview ? { clearSigningPreview: prop.clearSigningPreview } : {},
|
|
3832
|
-
votes: activeVotes
|
|
3833
|
-
};
|
|
3834
|
-
const certHash = computePublishedMultiSigCertificateHash(unsignedCert);
|
|
3835
|
-
const frozenCert = freezePublishedCertificate({
|
|
3836
|
-
...unsignedCert,
|
|
3837
|
-
certificateHash: certHash
|
|
3838
|
-
});
|
|
3839
|
-
prop.issuedCert = frozenCert;
|
|
3840
|
-
return frozenCert;
|
|
3841
|
-
}
|
|
3842
|
-
/**
|
|
3843
|
-
* Stage 3 (Holder Hardware Final Release on Foreign Chain):
|
|
3844
|
-
* Delegates to `this.signerManager.verifyAndConsumePublishedCertificate` (stateless foreign-chain contract verifier)
|
|
3845
|
-
* AND verifies VLedger state consistency, then marks the proposal `EXECUTED`.
|
|
3846
|
-
*/
|
|
3847
|
-
executeWithPublishedCertificate(params) {
|
|
3848
|
-
if (!params || typeof params !== "object" || !params.certificate || typeof params.certificate !== "object") throw new _ocap_util_lib_error.CustomError(ErrorCode.InvalidBridge, "OcapPublishedMultiSigCert: certificate object is required");
|
|
3849
|
-
const cert = params.certificate;
|
|
3850
|
-
const prop = this.proposals.get(cert.proposalId);
|
|
3851
|
-
if (!prop || prop.vetoed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: proposal does not exist or was vetoed on OCAP/VLedger");
|
|
3852
|
-
if (prop.executed) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate for proposal ${cert.proposalId} has already been executed`);
|
|
3853
|
-
if (!prop.issuedCert) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, `OcapPublishedMultiSigCert: certificate has not been issued for proposal ${cert.proposalId}`);
|
|
3854
|
-
if (cert.vledgerProposalHash !== prop.vledgerProposalHash || cert.certificateHash !== prop.issuedCert.certificateHash) throw new _ocap_util_lib_error.CustomError(ErrorCode.ForbiddenBridge, "OcapPublishedMultiSigCert: certificate does not match VLedger issuedCert");
|
|
3855
|
-
const effectiveNow = params.nowUnixSeconds ?? cert.issuedAtUnixSeconds;
|
|
3856
|
-
const consumed = this.signerManager.verifyAndConsumePublishedCertificate({
|
|
3857
|
-
certificate: cert,
|
|
3858
|
-
executorEvmAddress: params.executorEvmAddress,
|
|
3859
|
-
holderReleaseSignature: params.holderReleaseSignature,
|
|
3860
|
-
nowUnixSeconds: effectiveNow,
|
|
3861
|
-
minCooldownSeconds: this.minCooldownSeconds
|
|
3862
|
-
});
|
|
3863
|
-
prop.executed = true;
|
|
3864
|
-
return {
|
|
3865
|
-
executed: true,
|
|
3866
|
-
proposalId: cert.proposalId,
|
|
3867
|
-
vledgerProposalHash: consumed.vledgerProposalHash,
|
|
3868
|
-
certificateHash: consumed.certificateHash,
|
|
3869
|
-
executorEvmAddress: consumed.executorEvmAddress,
|
|
3870
|
-
consumedNonce: consumed.consumedNonce,
|
|
3871
|
-
verifiedSigners: consumed.verifiedSigners
|
|
3872
|
-
};
|
|
3873
|
-
}
|
|
3874
|
-
};
|
|
3875
|
-
|
|
3876
|
-
//#endregion
|
|
3877
|
-
exports.ARC_EVM_BRIDGE_GATEWAY_SOLIDITY_SPEC = ARC_EVM_BRIDGE_GATEWAY_SOLIDITY_SPEC;
|
|
3878
|
-
exports.BRIDGE_CHARTER_KIND = BRIDGE_CHARTER_KIND;
|
|
3879
|
-
exports.DEFAULT_MAX_ROLLUP_BLOCK_SIZE = DEFAULT_MAX_ROLLUP_BLOCK_SIZE;
|
|
3880
|
-
exports.DEFAULT_MIN_EVM_CONFIRMATIONS = DEFAULT_MIN_EVM_CONFIRMATIONS;
|
|
3881
|
-
exports.DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS = DEFAULT_MIN_MULTISIG_COOLDOWN_SECONDS;
|
|
3882
|
-
exports.DEFAULT_MULTISIG_CERT_TTL_SECONDS = DEFAULT_MULTISIG_CERT_TTL_SECONDS;
|
|
3883
|
-
exports.DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT = DEFAULT_ROLLUP_SUNSET_ACTIVATION_HEIGHT;
|
|
3884
|
-
exports.DEFAULT_VERIFYING_CONTRACT_ADDRESS = DEFAULT_VERIFYING_CONTRACT_ADDRESS;
|
|
3885
|
-
exports.DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS = DEFAULT_WITHDRAW_TIMELOCK_DELAY_SECONDS;
|
|
3886
|
-
exports.DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS = DEPRECATED_ROLLUP_PROTOCOL_TYPE_URLS;
|
|
3887
|
-
exports.DIRECT_WITHDRAW_TYPEHASH = DIRECT_WITHDRAW_TYPEHASH;
|
|
3888
|
-
exports.EIP712_BRIDGE_DOMAIN_NAME = EIP712_BRIDGE_DOMAIN_NAME;
|
|
3889
|
-
exports.EIP712_BRIDGE_DOMAIN_VERSION = EIP712_BRIDGE_DOMAIN_VERSION;
|
|
3890
|
-
exports.EIP712_DOMAIN_TYPEHASH = EIP712_DOMAIN_TYPEHASH;
|
|
3891
|
-
exports.EMPTY_ROLLUP_MERKLE_ROOT = EMPTY_ROLLUP_MERKLE_ROOT;
|
|
3892
|
-
exports.EXPECTED_CATEGORY_BY_OPERATION = EXPECTED_CATEGORY_BY_OPERATION;
|
|
3893
|
-
exports.HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS = HARD_FLOOR_MULTISIG_COOLDOWN_SECONDS;
|
|
3894
|
-
exports.HOLDER_RELEASE_INTENT_TYPEHASH = HOLDER_RELEASE_INTENT_TYPEHASH;
|
|
3895
|
-
exports.HardenedMultiSigSignerManagerV2 = HardenedMultiSigSignerManagerV2;
|
|
3896
|
-
exports.MAX_DIRECT_VOUCHER_TTL_SECONDS = MAX_DIRECT_VOUCHER_TTL_SECONDS;
|
|
3897
|
-
exports.MAX_EDGE_WEBHOOK_BODY_BYTES = MAX_EDGE_WEBHOOK_BODY_BYTES;
|
|
3898
|
-
exports.MAX_EDGE_WEBHOOK_SKEW_SECONDS = MAX_EDGE_WEBHOOK_SKEW_SECONDS;
|
|
3899
|
-
exports.MAX_MULTISIG_CERT_TTL_SECONDS = MAX_MULTISIG_CERT_TTL_SECONDS;
|
|
3900
|
-
exports.MAX_MULTISIG_VOTES_PER_CERT = MAX_MULTISIG_VOTES_PER_CERT;
|
|
3901
|
-
exports.MAX_PUBLISHED_MULTISIG_PROPOSALS = MAX_PUBLISHED_MULTISIG_PROPOSALS;
|
|
3902
|
-
exports.MAX_TRACKED_WEBHOOK_NONCES = MAX_TRACKED_WEBHOOK_NONCES;
|
|
3903
|
-
exports.MIN_DIRECT_VOUCHER_TTL_SECONDS = MIN_DIRECT_VOUCHER_TTL_SECONDS;
|
|
3904
|
-
exports.MIN_MULTISIG_CERT_TTL_SECONDS = MIN_MULTISIG_CERT_TTL_SECONDS;
|
|
3905
|
-
exports.MULTISIG_OP_TYPEHASH = MULTISIG_OP_TYPEHASH;
|
|
3906
|
-
exports.MULTISIG_VETO_ATTESTATION_TYPEHASH = MULTISIG_VETO_ATTESTATION_TYPEHASH;
|
|
3907
|
-
exports.OcapLocalEvmBridgeTestnetHarness = OcapLocalEvmBridgeTestnetHarness;
|
|
3908
|
-
exports.OcapOnChainBridgeGovernanceRegistry = OcapOnChainBridgeGovernanceRegistry;
|
|
3909
|
-
exports.OcapPublishedMultiSigEngine = OcapPublishedMultiSigEngine;
|
|
3910
|
-
exports.OcapSimplifiedEvmBridgeNode = OcapSimplifiedEvmBridgeNode;
|
|
3911
|
-
exports.PUBLISHED_MULTISIG_CERT_OP_TYPEHASH = PUBLISHED_MULTISIG_CERT_OP_TYPEHASH;
|
|
3912
|
-
exports.TWO_PHASE_CHALLENGE_TYPEHASH = TWO_PHASE_CHALLENGE_TYPEHASH;
|
|
3913
|
-
exports.ZERO_BYTES32_HASH = ZERO_BYTES32_HASH;
|
|
3914
|
-
exports.ZERO_EVM_ADDRESS = ZERO_EVM_ADDRESS;
|
|
3915
|
-
exports.assertRollupProtocolNotSunset = assertRollupProtocolNotSunset;
|
|
3916
|
-
exports.buildEvmBridgeMerkleTree = buildEvmBridgeMerkleTree;
|
|
3917
|
-
exports.buildPublishedMultiSigClearSigningPreview = buildPublishedMultiSigClearSigningPreview;
|
|
3918
|
-
exports.computeBridgeGovernanceCharterHash = computeBridgeGovernanceCharterHash;
|
|
3919
|
-
exports.computeDirectWithdrawVoucherDigest = computeDirectWithdrawVoucherDigest;
|
|
3920
|
-
exports.computeEdgeWebhookHmac = computeEdgeWebhookHmac;
|
|
3921
|
-
exports.computeEip712BridgeDomainSeparator = computeEip712BridgeDomainSeparator;
|
|
3922
|
-
exports.computeEip712WithdrawStructHash = computeEip712WithdrawStructHash;
|
|
3923
|
-
exports.computeEvmBridgeBlockHash = computeEvmBridgeBlockHash;
|
|
3924
|
-
exports.computeEvmBridgeTxsHash = computeEvmBridgeTxsHash;
|
|
3925
|
-
exports.computeEvmBridgeWithdrawLeafHash = computeEvmBridgeWithdrawLeafHash;
|
|
3926
|
-
exports.computeEvmTwoPhaseChallengeHash = computeEvmTwoPhaseChallengeHash;
|
|
3927
|
-
exports.computeHardenedMultiSigOpDigest = computeHardenedMultiSigOpDigest;
|
|
3928
|
-
exports.computeHolderFinalReleaseDigest = computeHolderFinalReleaseDigest;
|
|
3929
|
-
exports.computeMultiSigOperationParamsHash = computeMultiSigOperationParamsHash;
|
|
3930
|
-
exports.computeMultiSigVetoAttestationDigest = computeMultiSigVetoAttestationDigest;
|
|
3931
|
-
exports.computePublishedMultiSigCertificateHash = computePublishedMultiSigCertificateHash;
|
|
3932
|
-
exports.computePublishedMultiSigVoteDigest = computePublishedMultiSigVoteDigest;
|
|
3933
|
-
exports.computeVLedgerMultiSigProposalHash = computeVLedgerMultiSigProposalHash;
|
|
3934
|
-
exports.computeValidatorBlockSignatureDigest = computeValidatorBlockSignatureDigest;
|
|
3935
|
-
exports.computeValidatorVoucherSignatureDigest = computeValidatorVoucherSignatureDigest;
|
|
3936
|
-
exports.deriveEvmAddressFromPrivateKeyHex = deriveEvmAddressFromPrivateKeyHex;
|
|
3937
|
-
exports.ecrecoverEvmAddress = ecrecoverEvmAddress;
|
|
3938
|
-
exports.encodeEvmBridgeWithdrawPackedPreimage = encodeEvmBridgeWithdrawPackedPreimage;
|
|
3939
|
-
exports.isDeprecatedRollupWriteProtocol = isDeprecatedRollupWriteProtocol;
|
|
3940
|
-
exports.parseLegacyRollupReadOnlyRecord = parseLegacyRollupReadOnlyRecord;
|
|
3941
|
-
exports.signDigestWithSecp256k1PrivateKey = signDigestWithSecp256k1PrivateKey;
|
|
3942
|
-
exports.verifyDirectWithdrawVoucher = verifyDirectWithdrawVoucher;
|
|
3943
|
-
exports.verifyEvmBridgeMerkleProof = verifyEvmBridgeMerkleProof;
|