Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
A payer short of the lock or the fee reverts with FilecoinPayV2 `InsufficientBalance`, and a payer whose balance has run out reverts with `Behind`.
A rate above FilecoinPayV2's `uint88` reverts with the new `RateTooLarge` error.
The `settleRail` callback counts neither the reserve nor that lock as held payment.
- After piece removals, `nextProvingPeriod` on a FilecoinPayV2 data set sets its PDP rail rate on FilecoinPayV2 for the remaining leaf count and unlocks the lock difference, instead of calling FilecoinPayV1 and reverting.
The rate change settles the rail first, so the `settleRail` callback arbitrates the epochs since the last settlement at the old rate.
When the rail already has that rate, set by a later `piecesAdded` or kept by rounding, `nextProvingPeriod` leaves the rail alone, so a payer who is behind does not block proving.

## [1.6.0] - FWSS Storage Terms and Piece Metadata Cleanup

Expand Down
3 changes: 2 additions & 1 deletion SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,9 @@ A client opts a new dataset into FilecoinPayV2 by signing the ID of terms regist
On FilecoinPayV2 the client authorizes FWSS with `CREATE_RAIL`, and in one `executeScript` call FWSS opens the rails, locks the terminate fee and the CDN lockups, and pays the creation fee to the payee.
Scheduling piece removals on FilecoinPayV2 pays its fee to the payee at once, with a lock and a disburse on the PDP rail.
Adding pieces on FilecoinPayV2 sets the PDP rail's rate, moves the rate's lockup on the rail, and pays the add fee to the payee, in one script.
After piece removals, `nextProvingPeriod` on FilecoinPayV2 sets the PDP rail's rate for the remaining leaf count and unlocks the lockup difference, in one script with no fee.
That grant has no rate or lockup allowance like the FilecoinPayV1 operator approval, so only FWSS's own logic bounds what it locks and charges on those rails.
The rest of this specification after creation still describes FilecoinPayV1 rails; FilecoinPayV2 data sets do not yet support the rate update in `nextProvingPeriod`, termination or the CDN flows.
The rest of this specification after creation still describes FilecoinPayV1 rails; FilecoinPayV2 data sets do not yet support termination or the CDN flows.
Funds flow to providers over time based on the storage rate.

**Lockup**: To protect providers from non-payment, FWSS requires clients to maintain a 30-day reserve of funds. This "lockup" guarantees the provider will be paid for at least 30 days even if the client stops adding funds. The lockup is not a pre-payment—funds still flow to the provider gradually—but it cannot be withdrawn while the storage agreement is active.
Expand Down
57 changes: 40 additions & 17 deletions service_contracts/src/modules/FWSSProvingModule.sol
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pragma solidity 0.8.37;
import {CHALLENGES_PER_PROOF, NO_PROVING_DEADLINE} from "../lib/FWSSConstants.sol";
import {Errors} from "../Errors.sol";
import {FilecoinPayV1, IValidator} from "@fws-payments/FilecoinPayV1.sol";
import {FilecoinPayV2} from "@filecoin-pay-v2/FilecoinPayV2.sol";
import {IExtsload} from "@filecoin-pay-v2/interfaces/IExtsload.sol";
import {IRailV2} from "@filecoin-pay-v2/interfaces/IRail.sol";
import {RailId, RailIdLibrary} from "@filecoin-pay-v2/lib/RailId.sol";
Expand All @@ -15,13 +16,16 @@ import {FWSSFilecoinPayV2} from "../lib/FWSSFilecoinPayV2.sol";
import {LibProving} from "../lib/LibProving.sol";
import {LibRailsV2} from "../lib/LibRailsV2.sol";
import {LibServiceLifecycleGuards} from "../lib/LibServiceLifecycleGuards.sol";
import {LibStorageTerms} from "../lib/LibStorageTerms.sol";
import {LibStoragePayments} from "../lib/LibStoragePayments.sol";
import {StoragePricing} from "../lib/StoragePricing.sol";
import {FWSSStorage} from "../storage/FWSSStorage.sol";

/// @title FWSSProvingModule
/// @notice Records PDP proofs, advances or configures proving periods, and arbitrates PDP rail payments from them.
contract FWSSProvingModule is IValidator, IRailV2, FWSSStorage, FWSSOwnable, FWSSPDPVerifier, FWSSFilecoinPayV2 {
using LibRailsV2 for FilecoinPayV2;

FilecoinPayV1 internal immutable paymentContract;

/// @notice Configures the immutable dependencies used by this module.
Expand Down Expand Up @@ -124,8 +128,6 @@ contract FWSSProvingModule is IValidator, IRailV2, FWSSStorage, FWSSOwnable, FWS
LibServiceLifecycleGuards.requirePaymentNotBeyondEndEpoch(dataSetId, dataSetInfo[dataSetId].pdpEndEpoch);

DataSetInfo storage info = dataSetInfo[dataSetId];
uint96 pending = info.pendingOneTimePayments;
uint96 reserveBalance = info.lifecycleReserveBalance;

uint256 activationEpoch = provingActivationEpoch[dataSetId];
if (provingDeadlines[dataSetId] == NO_PROVING_DEADLINE) {
Expand Down Expand Up @@ -155,18 +157,7 @@ contract FWSSProvingModule is IValidator, IRailV2, FWSSStorage, FWSSOwnable, FWS
}
provingDeadlines[dataSetId] = firstDeadline;

// Rate was already set in piecesAdded; only update if pieces were removed or fees are pending
if (_consumePieceRemovals(dataSetId, info) || pending > 0) {
LibStoragePayments.updatePaymentRates(
dataSetId,
info,
StoragePricing.calculateStorageRate(leafCount, info.storageTermsId),
pending,
reserveBalance,
false,
paymentContract
);
}
_updateRateAfterRemovals(dataSetId, info, leafCount);

return;
}
Expand Down Expand Up @@ -212,18 +203,50 @@ contract FWSSProvingModule is IValidator, IRailV2, FWSSStorage, FWSSOwnable, FWS
provingDeadlines[dataSetId] = nextDeadline;
provenThisPeriod[dataSetId] = false;

// Additions update rate immediately in piecesAdded; update here if pieces were removed or fees are pending
_updateRateAfterRemovals(dataSetId, info, leafCount);
}

/// @notice Sets the PDP rail rate for the leaf count left after piece removals, and on FilecoinPayV1 flushes the
/// pending one-time fees. Additions already set the rate in piecesAdded.
/// @param dataSetId The data set advancing to its next proving period.
/// @param info The data set's stored info.
/// @param leafCount The data set's leaf count after PDPVerifier dropped the removed pieces.
function _updateRateAfterRemovals(uint256 dataSetId, DataSetInfo storage info, uint256 leafCount) private {
bool hadRemovals = _consumePieceRemovals(dataSetId, info);
if (hadRemovals || pending > 0) {

if (_isV1Rail(info.pdpRailId)) {
uint96 pending = info.pendingOneTimePayments;
if (!hadRemovals && pending == 0) return;
LibStoragePayments.updatePaymentRates(
dataSetId,
info,
StoragePricing.calculateStorageRate(leafCount, info.storageTermsId),
pending,
reserveBalance,
info.lifecycleReserveBalance,
false,
paymentContract
);
} else if (hadRemovals) {
// FilecoinPayV2 data sets pay their fees as they arise, so only removals leave the rate to update.
uint256 newRate = StoragePricing.calculateStorageRate(leafCount, info.storageTermsId);

// The rate may already be right, set by a later piecesAdded or kept by rounding. setRate settles first and
// reverts for a payer who is behind, which an unchanged rate must not do, as on FilecoinPayV1.
uint256 pdpRailId = info.pdpRailId;
if (
newRate == RailIdLibrary.getRail(IExtsload(address(filecoinPayV2)), RailId.wrap(pdpRailId)).incomingRate
) {
return;
}
filecoinPayV2.setPdpRate(
dataSetId,
pdpRailId,
LibStorageTerms.getRecord(info.storageTermsId).token,
info.payer,
info.payee,
newRate,
0
);
}
}

Expand Down
224 changes: 224 additions & 0 deletions service_contracts/test/modules/FWSSProvingModuleFilecoinPayV2.t.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
// SPDX-License-Identifier: Apache-2.0 OR MIT
pragma solidity ^0.8.37;

import {Cids} from "@pdp/Cids.sol";
import {PDPListener} from "@pdp/PDPVerifier.sol";
import {IExtsload} from "@filecoin-pay-v2/interfaces/IExtsload.sol";
import {RailId, RailIdLibrary, StreamState} from "@filecoin-pay-v2/lib/RailId.sol";
import {CHALLENGES_PER_PROOF} from "../../src/lib/FWSSConstants.sol";
import {RailRateUpdated} from "../../src/lib/LibRails.sol";
import {
ADD_PIECES_BASE_FEE,
ADD_PIECES_PER_PIECE_FEE,
CREATE_DATA_SET_FEE,
DEFAULT_LOCKUP_PERIOD,
SCHEDULE_PIECE_REMOVALS_FEE,
STORAGE_PRICE_PER_TIB_PER_MONTH,
TERMINATE_FEE
} from "../../src/lib/PriceListUSDFC.sol";
import {PAY_VERSION_FILECOIN_PAY_V2, StorageTerms} from "../../src/lib/StorageTerms.sol";
import {FWSSProvingModule} from "../../src/modules/FWSSProvingModule.sol";
import {FWSSStorageTermsModule} from "../../src/modules/FWSSStorageTermsModule.sol";
import {FilecoinWarmStorageServiceFixture} from "../helpers/FilecoinWarmStorageServiceFixture.sol";

contract FWSSProvingModuleFilecoinPayV2Test is FilecoinWarmStorageServiceFixture {
uint8 private constant PIECE_HEIGHT = 30;
uint256 private constant FUNDED = 10e18;

address private payer;
uint256 private dataSetId;
uint256 private pdpRailId;
uint256 private activationEpoch;
uint256 private maxProvingPeriod;
uint256 private challengeWindow;
uint256 private leavesPerPiece;
uint256 private piecesAdded;
uint256 private addNonce = 1;

function setUp() public override {
super.setUp();
payer = makeAddr("v2Payer");
_fundV2Payer(payer, FUNDED);
(maxProvingPeriod, challengeWindow,,) = pdpServiceWithPayments.getPDPConfig();
leavesPerPiece = Cids.leafCount(0, PIECE_HEIGHT);

bytes32 termsId = FWSSStorageTermsModule(address(pdpServiceWithPayments))
.registerStorageTerms(
StorageTerms({
token: address(mockUSDFC),
tokenDecimals: 18,
salt: bytes32(0),
pricePerTiBPerMonth: uint96(STORAGE_PRICE_PER_TIB_PER_MONTH),
payVersion: PAY_VERSION_FILECOIN_PAY_V2
})
);
makeSignaturePass(payer);
vm.prank(serviceProvider);
dataSetId = mockPDPVerifier.createDataSet(
PDPListener(address(pdpServiceWithPayments)),
abi.encode(payer, uint256(0), new string[](0), new string[](0), FAKE_SIGNATURE, termsId)
);
pdpRailId = pdpServiceWithPayments.getDataSet(dataSetId).pdpRailId;
_addPieces(4);
}

function _addPieces(uint256 count) private {
Cids.Cid[] memory pieceData = new Cids.Cid[](count);
for (uint256 i = 0; i < count; i++) {
pieceData[i] = Cids.CommPv2FromDigest(0, PIECE_HEIGHT, keccak256(abi.encode(dataSetId, piecesAdded + i)));
}
makeSignaturePass(payer);
mockPDPVerifier.addPieces(
PDPListener(address(pdpServiceWithPayments)),
dataSetId,
piecesAdded,
pieceData,
addNonce++,
FAKE_SIGNATURE,
new string[](0),
new string[](0)
);
piecesAdded += count;
}

/// @dev nextProvingPeriod reads the leaf count after the removals from its argument, as PDPVerifier passes it.
function _scheduleRemoval() private {
makeSignaturePass(payer);
mockPDPVerifier.piecesScheduledRemove(
dataSetId, new uint256[](1), address(pdpServiceWithPayments), abi.encode(FAKE_SIGNATURE)
);
}

function _deadline(uint256 period) private view returns (uint256) {
return activationEpoch + (period + 1) * maxProvingPeriod;
}

function _startProving() private {
activationEpoch = vm.getBlockNumber();
_nextProvingPeriod(dataSetId, _deadline(0) - challengeWindow / 2, 4 * leavesPerPiece);
}

function _proveFirstPeriod() private {
vm.roll(_deadline(0) - challengeWindow / 2);
vm.prank(address(mockPDPVerifier));
FWSSProvingModule(address(pdpServiceWithPayments))
.possessionProven(dataSetId, 4 * leavesPerPiece, 12345, CHALLENGES_PER_PROOF);
}

function _rail() private view returns (StreamState memory) {
return RailIdLibrary.getRail(IExtsload(address(filecoinPayV2)), RailId.wrap(pdpRailId));
}

function _balance(address account) private view returns (uint256) {
return filecoinPayV2.balanceOf(account, uint256(uint160(address(mockUSDFC))));
}

function _feesPaid() private pure returns (uint256) {
return CREATE_DATA_SET_FEE + ADD_PIECES_BASE_FEE + 4 * ADD_PIECES_PER_PIECE_FEE + SCHEDULE_PIECE_REMOVALS_FEE;
}

function testRemovalLowersRateAndUnlocksAfterProvenPeriod() public {
uint256 createdAt = vm.getBlockNumber();
uint256 oldRate = _rateForLeaves(4 * leavesPerPiece);
uint256 newRate = _rateForLeaves(3 * leavesPerPiece);
_startProving();
_proveFirstPeriod();
_scheduleRemoval();

vm.expectEmit(true, false, false, true, address(pdpServiceWithPayments));
emit RailRateUpdated(dataSetId, pdpRailId, newRate);
_nextProvingPeriod(dataSetId, _deadline(1) - challengeWindow / 2, 3 * leavesPerPiece);

// The settleRail callback pays the proven period at the old rate before the rate drops
uint256 earned = (vm.getBlockNumber() - createdAt) * oldRate;
assertEq(_rail().incomingRate, newRate);
assertEq(_rail().available, TERMINATE_FEE + newRate * DEFAULT_LOCKUP_PERIOD, "lock follows the lower rate");
assertEq(_balance(serviceProvider), _feesPaid() + earned, "payee paid for the proven period");
assertEq(
_balance(payer),
FUNDED - TERMINATE_FEE - newRate * DEFAULT_LOCKUP_PERIOD - _feesPaid() - earned,
"payer gets the lock decrease back"
);
}

function testRemovalAfterFaultedPeriodRefundsAndHoldsOpenPeriod() public {
uint256 createdAt = vm.getBlockNumber();
uint256 oldRate = _rateForLeaves(4 * leavesPerPiece);
uint256 newRate = _rateForLeaves(3 * leavesPerPiece);
_startProving();
vm.roll(_deadline(0) + 10);
_scheduleRemoval();

// nextProvingPeriod has already moved the deadline when setRate calls back, and the callback still
// refunds the faulted period and holds the open one
uint256 refund = (_deadline(0) - createdAt) * oldRate;
uint256 held = 10 * oldRate;
vm.expectEmit(true, true, false, true, address(pdpServiceWithPayments));
emit FWSSProvingModule.PDPPaymentSettled(dataSetId, pdpRailId, createdAt, vm.getBlockNumber(), 0, refund, held);
_nextProvingPeriod(dataSetId, _deadline(1) - challengeWindow / 2, 3 * leavesPerPiece);

assertEq(_rail().incomingRate, newRate);
assertEq(_rail().available, TERMINATE_FEE + newRate * DEFAULT_LOCKUP_PERIOD + held);
assertEq(_balance(serviceProvider), _feesPaid(), "faulted period pays nothing");
assertEq(_balance(payer), FUNDED - TERMINATE_FEE - newRate * DEFAULT_LOCKUP_PERIOD - _feesPaid() - held);
}

function testRemovalBeforeProvingLowersRateAtActivation() public {
uint256 newRate = _rateForLeaves(3 * leavesPerPiece);
vm.roll(vm.getBlockNumber() + 50);
_scheduleRemoval();

activationEpoch = vm.getBlockNumber();
_nextProvingPeriod(dataSetId, _deadline(0) - challengeWindow / 2, 3 * leavesPerPiece);

// Epochs before activation are refunded
assertEq(_rail().incomingRate, newRate);
assertEq(_rail().available, TERMINATE_FEE + newRate * DEFAULT_LOCKUP_PERIOD);
assertEq(_balance(serviceProvider), _feesPaid());
assertEq(_balance(payer), FUNDED - TERMINATE_FEE - newRate * DEFAULT_LOCKUP_PERIOD - _feesPaid());
}

function testRemovingEveryPieceDropsRateAndLockToZero() public {
_startProving();
_proveFirstPeriod();
_scheduleRemoval();

_nextProvingPeriod(dataSetId, 0, 0);

assertEq(_rail().incomingRate, 0);
assertEq(_rail().available, TERMINATE_FEE, "only the termination fee stays locked");
}

function testRemovalAlreadyRepricedByAddSkipsSetRateForPayerBehind() public {
uint256 rate = _rateForLeaves(4 * leavesPerPiece);
_startProving();
_proveFirstPeriod();
_scheduleRemoval();

// processPieceDeletions drops the piece without a callback, and the next add sets the rate for the new size
mockPDPVerifier.setDataSetLeafCount(dataSetId, 3 * leavesPerPiece);
_addPieces(1);
assertEq(_rail().incomingRate, rate);
vm.startPrank(payer);
filecoinPayV2.withdraw(address(mockUSDFC), _balance(payer));
vm.stopPrank();
vm.roll(vm.getBlockNumber() + 2);

vm.expectCall(address(filecoinPayV2), abi.encodeWithSignature("executeScript(uint256,bytes)"), 0);
_nextProvingPeriod(dataSetId, _deadline(1) - challengeWindow / 2, 4 * leavesPerPiece);

assertEq(_rail().incomingRate, rate);
}

function testNoRemovalLeavesRateAlone() public {
uint256 rate = _rateForLeaves(4 * leavesPerPiece);
_startProving();
_proveFirstPeriod();

vm.expectCall(address(filecoinPayV2), abi.encodeWithSignature("executeScript(uint256,bytes)"), 0);
_nextProvingPeriod(dataSetId, _deadline(1) - challengeWindow / 2, 4 * leavesPerPiece);

assertEq(_rail().incomingRate, rate);
assertEq(_rail().available, TERMINATE_FEE + rate * DEFAULT_LOCKUP_PERIOD);
}
}
Loading