
Verify Solidity Bridge Withdrawals Against Proven Locked Value
A valid transfer hash proves that payout data matches a commitment; it does not prove that the source chain locked enough value to fund those payouts. A bridge must verify both properties independently. Before releasing reserves, bind the import to an authenticated source-chain export, derive the export’s spendable amount from proven fields, and ensure the payouts do not exceed that amount for each asset. This guide models that check for a Verus-style import flow, where VerusProof.checkExportAndTransfers validates hashReserveTransfers before TokenManager.processTransactions pays attacker-controlled transfers.
For production, do not compare an aggregate amount unless all values use the same asset and units. Reconcile per asset, account for fees and conversion rules explicitly, and test the invariant that a tiny proven reserve cannot authorize a huge payout. Hash integrity, source-chain proof, and value conservation are separate requirements.
Environment and baseline specifications
Examples target Solidity ^0.8.24, compiled for the Cancun EVM, using Foundry for tests. The example deliberately uses a small interface rather than assuming a particular bridge’s proof format. In a real integration, adapt it to the verifier’s authenticated export structure and the exact transfer encoding. Pin the compiler and dependencies in foundry.toml and your lockfile; compiler settings are part of the reviewed artifact.
[profile.default]
solc_version = "0.8.24"
evm_version = "cancun"
optimizer = true
optimizer_runs = 200
The mechanism to defend against is specific: a verifier accepts an import after checking that cce.hashReserveTransfers matches the hash of serializedTransfers, and that source, destination, and currency identifiers match expected values. The import then reaches TokenManager.processTransactions, which pays the transfers. If the path never relates each payout to value proven reserved on the source chain, a cheap, low-value export can commit to a large payout list. The hash can be perfectly valid while the withdrawal is insolvent.
Integrity is not value conservation
A hash answers: “Is this the data that was committed?” It does not answer: “Was enough value locked to pay this data?” Likewise, chain and currency identifiers establish identity constraints; they do not establish an amount bound.
The vulnerable pattern is structurally equivalent to:
function checkExportAndTransfers(
CCE calldata cce,
Transfer[] calldata transfers
) external view {
bytes32 hashedTransfers = keccak256(abi.encode(transfers));
require(cce.hashReserveTransfers == hashedTransfers);
require(cce.sourceSystemID == VERUS);
require(cce.destSystemID == VETH);
require(cce.destCurrencyID == VETH);
// Missing: compare authorized reserve value with payout value.
}
function submitImport(
CCE calldata cce,
Transfer[] calldata transfers
) external {
proof.verify(cce); // Must authenticate source-chain state.
checkExportAndTransfers(cce, transfers);
tokenManager.processTransactions(transfers);
}
This is not a Solidity hashing defect. A collision-resistant hash can work exactly as intended: it binds a payout list to a commitment. The failure is a missing semantic check between the committed list and the source export’s spendable value. A proof that a tiny export exists does not make a larger payout legitimate.
The Verus-style path makes the distinction important: cce.numInputs may describe a count, while cce.totalamounts or equivalent reserve data must be meaningfully connected to what processTransactions pays. Merely reading a declared total is not sufficient. The total must itself be authenticated, denominated correctly, and derived under the source protocol’s rules.
Production implementation: reconcile by asset
Use an authenticated, per-asset reserve amount and compare it with the corresponding payouts before any external transfer. The following example illustrates the accounting boundary. reserveFor must return a value derived from a verified source export—not a caller-supplied amount or a field that the proof does not authenticate.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
struct Transfer {
address token; // address(0) denotes native ETH
address recipient;
uint256 amount; // smallest units of token
}
struct ProvenReserve {
address token;
uint256 amount; // maximum spendable amount, in token's smallest units
}
interface IExportVerifier {
function verifyExport(bytes calldata proof)
external
view
returns (
bytes32 exportId,
bytes32 transferCommitment,
ProvenReserve[] memory reserves
);
}
contract ImportPayout {
error InvalidCommitment();
error InvalidRecipient();
error UnbackedPayout(address token, uint256 payout, uint256 reserve);
error DuplicateReserveAsset(address token);
error TokenTransferFailed(address token);
IExportVerifier public immutable verifier;
// The production system must also persist replay protection for exportId.
mapping(bytes32 => bool) public consumedExport;
constructor(IExportVerifier verifier_) {
verifier = verifier_;
}
function submitImport(
bytes calldata proof,
Transfer[] calldata transfers
) external {
(
bytes32 exportId,
bytes32 committedTransfers,
ProvenReserve[] memory reserves
) = verifier.verifyExport(proof);
if (consumedExport[exportId]) revert InvalidCommitment();
if (keccak256(abi.encode(transfers)) != committedTransfers) {
revert InvalidCommitment();
}
_checkConservation(transfers, reserves);
// Mark before interactions. A revert from a payout rolls this back.
consumedExport[exportId] = true;
for (uint256 i; i < transfers.length; ++i) {
Transfer calldata t = transfers[i];
if (t.recipient == address(0)) revert InvalidRecipient();
if (t.token == address(0)) {
(bool ok,) = t.recipient.call{value: t.amount}("");
if (!ok) revert TokenTransferFailed(address(0));
} else {
_safeTransfer(t.token, t.recipient, t.amount);
}
}
}
function _checkConservation(
Transfer[] calldata transfers,
ProvenReserve[] memory reserves
) internal pure {
for (uint256 r; r < reserves.length; ++r) {
for (uint256 earlier; earlier < r; ++earlier) {
if (reserves[earlier].token == reserves[r].token) {
revert DuplicateReserveAsset(reserves[r].token);
}
}
}
for (uint256 i; i < transfers.length; ++i) {
address token = transfers[i].token;
uint256 payout;
for (uint256 j; j < transfers.length; ++j) {
if (transfers[j].token == token) {
payout += transfers[j].amount; // checked arithmetic
}
}
uint256 reserve = _reserveOf(reserves, token);
if (payout > reserve) {
revert UnbackedPayout(token, payout, reserve);
}
}
}
function _reserveOf(
ProvenReserve[] memory reserves,
address token
) internal pure returns (uint256) {
for (uint256 i; i < reserves.length; ++i) {
if (reserves[i].token == token) return reserves[i].amount;
}
return 0;
}
function _safeTransfer(address token, address to, uint256 amount) internal {
(bool ok, bytes memory result) = token.call(
abi.encodeWithSignature("transfer(address,uint256)", to, amount)
);
if (!ok || (result.length != 0 && !abi.decode(result, (bool)))) {
revert TokenTransferFailed(token);
}
}
receive() external payable {}
}
This reference implementation emphasizes correctness, not gas efficiency. Its nested loops are quadratic in the transfer count, so it is suitable only when the verifier enforces a small, explicit maximum list size. For larger lists, require canonical ordering by token and aggregate adjacent transfers in one pass, or have the authenticated proof provide a rigorously bound per-asset total. Do not use an unbounded caller-controlled loop in a production import path.
A real bridge must also make the commitment unambiguous. The example hashes abi.encode(transfers); both commitment creation and verification must use the identical schema, including token, recipient, amount, ordering, and any fee fields. The verifier must bind the proof to the correct export, source system, destination system, and destination currency. Value checking does not replace those checks, and a transfer hash does not replace proof verification.
Define the conservation rule before coding
For each asset a, enforce:
sum(payout[a]) <= provenSpendableReserve[a]
“Proven spendable reserve” is a protocol-specific concept. It may be less than the export’s gross amount after fees, prior spends, or conversion rules. If a source export includes multiple inputs, prove that they are valid and that none has already been consumed. If the destination pays a wrapped representation at a different decimal precision, convert using explicit, audited rounding rules before comparing. Never sum USDC, ETH, and tBTC into one raw integer and call that value conservation.
For fee-bearing assets, choose and document whether the bound applies to the amount debited from bridge reserves or the amount received by users. Prefer to check the actual reserve debit. A token that charges transfer fees may cause the recipient’s balance increase to be lower than the debit; it must not cause the bridge’s accounting to authorize more than the proven reserve. For rebasing or otherwise non-standard tokens, define supported behavior explicitly or reject them.
State sequencing matters as much as arithmetic. Mark the export consumed before external payouts so a callback cannot replay it, and rely on transaction atomicity so a failed payout reverts both the consumed marker and all earlier transfers. If payout processing is delegated to another contract, ensure that contract cannot bypass the value check or consume a different transfer list.
For broader bridge invariants, compare this accounting boundary with Validating Cross-Layer Asset Commitments to Secure Solidity Bridges. If a failed recipient can block batch processing, isolate that operational risk using a design such as Preventing Denial-of-Service in Solidity with Pull Payments. Neither measure substitutes for the per-asset reserve bound.
Verification: make “tiny reserve, huge payout” fail
Write the regression test around the missing invariant, not merely around a bad proof or malformed hash. A valid test fixture should return a valid export proof and a matching transfer commitment, then demonstrate that the payout fails solely because the proven reserve is too small.
function testFuzz_TinyReserveCannotAuthorizeLargePayout(
uint96 smallReserve,
uint96 excess
) public {
vm.assume(excess > 0);
uint256 payout = uint256(smallReserve) + uint256(excess);
mockVerifier.setValidExport(
exportId,
keccak256(abi.encode(_oneTransfer(token, recipient, payout))),
token,
smallReserve
);
vm.expectRevert(
abi.encodeWithSelector(
ImportPayout.UnbackedPayout.selector,
token,
payout,
uint256(smallReserve)
)
);
bridge.submitImport(validProof, _oneTransfer(token, recipient, payout));
}
Add boundary cases: payout equal to reserve succeeds; payout one unit over fails; an asset absent from reserves has a zero limit; two transfers of the same token are summed; two different tokens are checked independently; duplicate reserve entries are rejected; and a failed external transfer does not leave the export consumed. Also test that changing any committed transfer field invalidates the commitment.
Run the suite and inspect the compiled artifact with pinned settings:
forge test --match-contract ImportPayoutTest -vvv
forge test --match-test testFuzz_TinyReserveCannotAuthorizeLargePayout --fuzz-runs 10000
forge build --sizes
solc --version
For an important bridge, run the same invariant suite against optimized and unoptimized builds, and compare the deployed bytecode and storage layout as part of release review. Fuzz a stateful model in which exports can be submitted, consumed, and replayed; assert after every successful import that cumulative payouts per asset never exceed cumulative proven reserves. Differentially compare the Solidity verifier’s decoded fields with an independent off-chain decoder for the source-chain proof format. That catches schema disagreements that a Solidity-only test can miss.
Quantitative trade-offs
The following comparison describes design characteristics, not benchmark results for a specific deployed bridge. Gas depends on token behavior, transfer count, compiler settings, and proof verification cost.
| Approach | Amount-check work | Security property | Main trade-off |
|---|---|---|---|
| Hash and identity checks only | O(n) to hash transfers | Integrity and routing checks; no reserve bound | Cheap, but permits unbacked payout lists |
| Nested per-asset aggregation shown above | O(n²) | Bounds payouts by authenticated reserves per asset | Simple to audit; cap list length |
| Canonically sorted transfers, one-pass aggregation | O(n) | Same bound if ordering and duplicate rules are enforced | More complex encoding and validation |
| Authenticated totals supplied by proof | O(n) or less on-chain | Efficient if totals are bound to the exact payout set | Proof format and total derivation become critical |
A per-transaction cap or rate limit can reduce the immediate loss if another validation defect exists, but it is not a conservation proof: repeated imports can still drain funds. Treat limits as defense in depth, alongside replay protection and monitoring, not as a replacement for the reserve comparison.
Production pitfalls
- A declared total is not automatically trustworthy.
cce.totalamountsis useful only if the source proof authenticates it and the protocol defines how it relates to each transfer. - Do not compare unlike units. Per-token base units avoid decimal ambiguity. Cross-asset conversion requires an explicit rate source, rounding direction, and validity window.
- Prevent double spending. An authenticated export must be consumed once, and source inputs must satisfy the source protocol’s spend rules. A value bound without replay protection can authorize the same reserve repeatedly.
- Bound attacker-controlled work. Enforce a maximum number of transfers and reserves, or use a canonical linear-time aggregation scheme.
- Do not silently truncate or wrap. Solidity 0.8 checked arithmetic reverts on overflow; preserve that behavior in accounting. Avoid
uncheckedaround payout sums unless a proven bound makes it safe. - Review the whole payout path. Confirm that every route into
TokenManager.processTransactionspasses the same verifier and conservation check. An alternate entry point can undo a correct check in one function.
Frequently Asked Questions (FAQ)
Does a matching hashReserveTransfers prove that a bridge withdrawal is backed?
No. It proves that the transfer data matches the committed hash, assuming the encoding and hash are correct. The bridge must separately prove that the source export authorizes enough spendable value for each asset paid out.
Is checking cce.totalamounts enough to fix the Verus-style flaw?
Only if that amount is authenticated by the source-chain proof, expressed in the correct units, and correctly related to the transfers. A single aggregate cannot safely cover payouts in multiple assets without a defined conversion rule. Prefer a proven per-asset reserve bound.
Should a bridge rely on withdrawal caps instead of value conservation?
No. A cap limits the maximum loss per transaction or time window, but does not establish that a payout is backed. Enforce value conservation as a correctness invariant; use caps and rate limits as additional containment controls.