2023-06-22 10:32:18 +00:00
|
|
|
import std/sequtils
|
2023-04-19 13:06:00 +00:00
|
|
|
import std/os
|
2023-06-22 10:32:18 +00:00
|
|
|
from std/times import getTime, toUnix
|
|
|
|
import pkg/chronicles
|
2023-09-01 05:44:41 +00:00
|
|
|
import codex/contracts
|
2023-04-19 13:06:00 +00:00
|
|
|
import codex/periods
|
2023-03-27 13:47:25 +00:00
|
|
|
import ../contracts/time
|
2023-05-03 07:24:25 +00:00
|
|
|
import ../contracts/deployment
|
2023-03-27 13:47:25 +00:00
|
|
|
import ./twonodes
|
2023-06-22 10:32:18 +00:00
|
|
|
import ./multinodes
|
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "test proofs"
|
2023-03-27 13:47:25 +00:00
|
|
|
|
|
|
|
twonodessuite "Proving integration test", debug1=false, debug2=false:
|
2023-04-19 13:06:00 +00:00
|
|
|
let validatorDir = getTempDir() / "CodexValidator"
|
|
|
|
|
2023-03-27 13:47:25 +00:00
|
|
|
var marketplace: Marketplace
|
2023-04-19 13:06:00 +00:00
|
|
|
var period: uint64
|
2023-03-27 13:47:25 +00:00
|
|
|
|
2023-09-01 05:44:41 +00:00
|
|
|
proc purchaseStateIs(client: CodexClient, id: PurchaseId, state: string): bool =
|
|
|
|
client.getPurchase(id).option.?state == some state
|
|
|
|
|
2023-03-27 13:47:25 +00:00
|
|
|
setup:
|
2023-05-03 07:24:25 +00:00
|
|
|
marketplace = Marketplace.new(Marketplace.address, provider)
|
2023-04-19 13:06:00 +00:00
|
|
|
period = (await marketplace.config()).proofs.period.truncate(uint64)
|
2023-04-14 09:04:17 +00:00
|
|
|
|
|
|
|
# Our Hardhat configuration does use automine, which means that time tracked by `provider.currentTime()` is not
|
|
|
|
# advanced until blocks are mined and that happens only when transaction is submitted.
|
|
|
|
# As we use in tests provider.currentTime() which uses block timestamp this can lead to synchronization issues.
|
|
|
|
await provider.advanceTime(1.u256)
|
2023-03-27 13:47:25 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc waitUntilPurchaseIsStarted(proofProbability: uint64 = 3,
|
|
|
|
duration: uint64 = 100 * period,
|
|
|
|
expiry: uint64 = 30) {.async.} =
|
|
|
|
discard client2.postAvailability(
|
2023-09-01 05:44:41 +00:00
|
|
|
size=0xFFFFF.u256,
|
|
|
|
duration=duration.u256,
|
|
|
|
minPrice=300.u256,
|
|
|
|
maxCollateral=200.u256
|
2023-04-19 13:06:00 +00:00
|
|
|
)
|
2023-09-01 05:44:41 +00:00
|
|
|
let cid = client1.upload("some file contents").get
|
2023-04-19 13:06:00 +00:00
|
|
|
let expiry = (await provider.currentTime()) + expiry.u256
|
2023-09-01 05:44:41 +00:00
|
|
|
let id = client1.requestStorage(
|
2023-04-19 13:06:00 +00:00
|
|
|
cid,
|
|
|
|
expiry=expiry,
|
2023-09-01 05:44:41 +00:00
|
|
|
duration=duration.u256,
|
|
|
|
proofProbability=proofProbability.u256,
|
|
|
|
collateral=100.u256,
|
|
|
|
reward=400.u256
|
|
|
|
).get
|
|
|
|
check eventually client1.purchaseStateIs(id, "started")
|
2023-03-27 13:47:25 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc advanceToNextPeriod {.async.} =
|
|
|
|
let periodicity = Periodicity(seconds: period.u256)
|
|
|
|
let currentPeriod = periodicity.periodOf(await provider.currentTime())
|
|
|
|
let endOfPeriod = periodicity.periodEnd(currentPeriod)
|
|
|
|
await provider.advanceTimeTo(endOfPeriod + 1)
|
|
|
|
|
|
|
|
proc startValidator: NodeProcess =
|
2023-09-13 14:17:56 +00:00
|
|
|
let validator = startNode(
|
|
|
|
[
|
|
|
|
"--data-dir=" & validatorDir,
|
|
|
|
"--api-port=8089",
|
|
|
|
"--disc-port=8099",
|
|
|
|
"--validator",
|
|
|
|
"--eth-account=" & $accounts[2]
|
|
|
|
], debug = false
|
|
|
|
)
|
|
|
|
validator.waitUntilStarted()
|
|
|
|
validator
|
2023-03-27 13:47:25 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
proc stopValidator(node: NodeProcess) =
|
|
|
|
node.stop()
|
|
|
|
removeDir(validatorDir)
|
|
|
|
|
|
|
|
test "hosts submit periodic proofs for slots they fill":
|
|
|
|
await waitUntilPurchaseIsStarted(proofProbability=1)
|
2023-03-27 13:47:25 +00:00
|
|
|
var proofWasSubmitted = false
|
|
|
|
proc onProofSubmitted(event: ProofSubmitted) =
|
|
|
|
proofWasSubmitted = true
|
|
|
|
let subscription = await marketplace.subscribe(ProofSubmitted, onProofSubmitted)
|
2023-04-19 13:06:00 +00:00
|
|
|
await provider.advanceTime(period.u256)
|
|
|
|
check eventually proofWasSubmitted
|
|
|
|
await subscription.unsubscribe()
|
|
|
|
|
|
|
|
test "validator will mark proofs as missing":
|
|
|
|
let validator = startValidator()
|
|
|
|
await waitUntilPurchaseIsStarted(proofProbability=1)
|
|
|
|
|
|
|
|
node2.stop()
|
|
|
|
|
|
|
|
var slotWasFreed = false
|
|
|
|
proc onSlotFreed(event: SlotFreed) =
|
|
|
|
slotWasFreed = true
|
|
|
|
let subscription = await marketplace.subscribe(SlotFreed, onSlotFreed)
|
2023-03-27 13:47:25 +00:00
|
|
|
|
|
|
|
for _ in 0..<100:
|
2023-04-19 13:06:00 +00:00
|
|
|
if slotWasFreed:
|
2023-03-27 13:47:25 +00:00
|
|
|
break
|
|
|
|
else:
|
2023-04-19 13:06:00 +00:00
|
|
|
await advanceToNextPeriod()
|
2023-07-13 13:58:35 +00:00
|
|
|
await sleepAsync(1.seconds)
|
2023-03-27 13:47:25 +00:00
|
|
|
|
2023-04-19 13:06:00 +00:00
|
|
|
check slotWasFreed
|
|
|
|
|
2023-03-27 13:47:25 +00:00
|
|
|
await subscription.unsubscribe()
|
2023-04-19 13:06:00 +00:00
|
|
|
stopValidator(validator)
|
2023-06-22 10:32:18 +00:00
|
|
|
|
|
|
|
multinodesuite "Simulate invalid proofs",
|
|
|
|
StartNodes.init(clients=1'u, providers=0'u, validators=1'u),
|
|
|
|
DebugNodes.init(client=false, provider=false, validator=false):
|
|
|
|
|
2023-09-01 05:44:41 +00:00
|
|
|
proc purchaseStateIs(client: CodexClient, id: PurchaseId, state: string): bool =
|
|
|
|
client.getPurchase(id).option.?state == some state
|
|
|
|
|
2023-06-22 10:32:18 +00:00
|
|
|
var marketplace: Marketplace
|
|
|
|
var period: uint64
|
|
|
|
var slotId: SlotId
|
|
|
|
|
|
|
|
setup:
|
|
|
|
marketplace = Marketplace.new(Marketplace.address, provider)
|
|
|
|
let config = await marketplace.config()
|
|
|
|
period = config.proofs.period.truncate(uint64)
|
|
|
|
slotId = SlotId(array[32, byte].default) # ensure we aren't reusing from prev test
|
|
|
|
|
|
|
|
# Our Hardhat configuration does use automine, which means that time tracked by `provider.currentTime()` is not
|
|
|
|
# advanced until blocks are mined and that happens only when transaction is submitted.
|
|
|
|
# As we use in tests provider.currentTime() which uses block timestamp this can lead to synchronization issues.
|
|
|
|
await provider.advanceTime(1.u256)
|
|
|
|
|
|
|
|
proc periods(p: Ordinal | uint): uint64 =
|
|
|
|
when p is uint:
|
|
|
|
p * period
|
|
|
|
else: p.uint * period
|
|
|
|
|
|
|
|
proc advanceToNextPeriod {.async.} =
|
|
|
|
let periodicity = Periodicity(seconds: period.u256)
|
|
|
|
let currentPeriod = periodicity.periodOf(await provider.currentTime())
|
|
|
|
let endOfPeriod = periodicity.periodEnd(currentPeriod)
|
|
|
|
await provider.advanceTimeTo(endOfPeriod + 1)
|
|
|
|
|
|
|
|
proc waitUntilPurchaseIsStarted(proofProbability: uint64 = 1,
|
|
|
|
duration: uint64 = 12.periods,
|
|
|
|
expiry: uint64 = 4.periods) {.async.} =
|
|
|
|
|
|
|
|
if clients().len < 1 or providers().len < 1:
|
|
|
|
raiseAssert("must start at least one client and one provider")
|
|
|
|
|
|
|
|
let client = clients()[0].restClient
|
|
|
|
let storageProvider = providers()[0].restClient
|
|
|
|
|
|
|
|
discard storageProvider.postAvailability(
|
2023-09-01 05:44:41 +00:00
|
|
|
size=0xFFFFF.u256,
|
|
|
|
duration=duration.u256,
|
|
|
|
minPrice=300.u256,
|
|
|
|
maxCollateral=200.u256
|
2023-06-22 10:32:18 +00:00
|
|
|
)
|
2023-09-01 05:44:41 +00:00
|
|
|
let cid = client.upload("some file contents " & $ getTime().toUnix).get
|
2023-06-22 10:32:18 +00:00
|
|
|
let expiry = (await provider.currentTime()) + expiry.u256
|
|
|
|
# avoid timing issues by filling the slot at the start of the next period
|
|
|
|
await advanceToNextPeriod()
|
2023-09-01 05:44:41 +00:00
|
|
|
let id = client.requestStorage(
|
2023-06-22 10:32:18 +00:00
|
|
|
cid,
|
|
|
|
expiry=expiry,
|
2023-09-01 05:44:41 +00:00
|
|
|
duration=duration.u256,
|
|
|
|
proofProbability=proofProbability.u256,
|
|
|
|
collateral=100.u256,
|
|
|
|
reward=400.u256
|
|
|
|
).get
|
|
|
|
check eventually client.purchaseStateIs(id, "started")
|
|
|
|
let purchase = client.getPurchase(id).get
|
|
|
|
slotId = slotId(purchase.requestId, 0.u256)
|
2023-06-22 10:32:18 +00:00
|
|
|
|
|
|
|
# TODO: these are very loose tests in that they are not testing EXACTLY how
|
|
|
|
# proofs were marked as missed by the validator. These tests should be
|
|
|
|
# tightened so that they are showing, as an integration test, that specific
|
|
|
|
# proofs are being marked as missed by the validator.
|
|
|
|
|
|
|
|
test "slot is freed after too many invalid proofs submitted":
|
|
|
|
let failEveryNProofs = 2'u
|
|
|
|
let totalProofs = 100'u
|
|
|
|
startProviderNode(failEveryNProofs)
|
|
|
|
|
|
|
|
await waitUntilPurchaseIsStarted(duration=totalProofs.periods)
|
|
|
|
|
|
|
|
var slotWasFreed = false
|
|
|
|
proc onSlotFreed(event: SlotFreed) =
|
Slot queue (#455)
## Slot queue
Adds a slot queue, as per the [slot queue design](https://github.com/codex-storage/codex-research/blob/master/design/sales.md#slot-queue).
Any time storage is requested, all slots from that request are immediately added to the queue. Finished, Canclled, Failed requests remove all slots with that request id from the queue. SlotFreed events add a new slot to the queue and SlotFilled events remove the slot from the queue. This allows popping of a slot each time one is processed, making things much simpler.
When an entire request of slots is added to the queue, the slot indices are shuffled randomly to hopefully prevent nodes that pick up the same storage requested event from clashing on the first processed slot index. This allowed removal of assigning a random slot index in the SalePreparing state and it also ensured that all SalesAgents will have a slot index assigned to them at the start thus the removal of the optional slotIndex.
Remove slotId from SlotFreed event as it was not being used. RequestId and slotIndex were added to the SlotFreed event earlier and those are now being used
The slot queue invariant that prioritises queue items added to the queue relies on a scoring mechanism to sort them based on the [sort order in the design document](https://github.com/codex-storage/codex-research/blob/master/design/sales.md#sort-order).
When a storage request is handled by the sales module, a slot index was randomly assigned and then the slot was filled. Now, a random slot index is only assigned when adding an entire request to the slot queue. Additionally, the slot is checked that its state is `SlotState.Free` before continuing with the download process.
SlotQueue should always ensure the underlying AsyncHeapQueue has one less than the maximum items, ensuring the SlotQueue can always have space to add an additional item regardless if it’s full or not.
Constructing `SlotQueue.workers` in `SlotQueue.new` calls `newAsyncQueue` which causes side effects, so the construction call had to be moved to `SlotQueue.start`.
Prevent loading request from contract (network request) if there is an existing item in queue for that request.
Check availability before adding request to queue.
Add ability to query market contract for past events. When new availabilities are added, the `onReservationAdded` callback is triggered in which past `StorageRequested` events are queried, and those slots are added to the queue (filtered by availability on `push` and filtered by state in `SalePreparing`).
#### Request Workers
Limit the concurrent requests being processed in the queue by using a limited pool of workers (default = 3). Workers are in a data structure of type `AsyncQueue[SlotQueueWorker]`. This allows us to await a `popFirst` for available workers inside of the main SlotQueue event loop
Add an `onCleanUp` that stops the agents and removes them from the sales module agent list. `onCleanUp` is called from sales end states (eg ignored, cancelled, finished, failed, errored).
Add a `doneProcessing` future to `SlotQueueWorker` to be completed in the `OnProcessSlot` callback. Each `doneProcessing` future created is cancelled and awaited in `SlotQueue.stop` (thanks to `TrackableFuturees`), which forced `stop` to become async.
- Cancel dispatched workers and the `onProcessSlot` callbacks, prevents zombie callbacks
#### Add TrackableFutures
Allow tracking of futures in a module so they can be cancelled at a later time. Useful for asyncSpawned futures, but works for any future.
### Sales module
The sales module needed to subscribe to request events to ensure that the request queue was managed correctly on each event. In the process of doing this, the sales agents were updated to avoid subscribing to events in each agent, and instead dispatch received events from the sales module to all created sales agents. This would prevent memory leaks on having too many eventemitters subscribed to.
- prevent removal of agents from sales module while stopping, otherwise the agents seq len is modified while iterating
An additional sales agent state was added, `SalePreparing`, that handles all state machine setup, such as retrieving the request and subscribing to events that were previously in the `SaleDownloading` state.
Once agents have parked in an end state (eg ignored, cancelled, finished, failed, errored), they were not getting cleaned up and the sales module was keeping a handle on their reference. An `onCleanUp` callback was created to be called after the state machine enters an end state, which could prevent a memory leak if the number of requests coming in is high.
Move the SalesAgent callback raises pragmas from the Sales module to the proc definition in SalesAgent. This avoids having to catch `Exception`.
- remove unneeded error handling as pragmas were moved
Move sales.subscriptions from an object containing named subscriptions to a `seq[Subscription]` directly on the sales object.
Sales tests: shut down repo after sales stop, to fix SIGABRT in CI
### Add async Promise API
- modelled after JavaScript Promise API
- alternative to `asyncSpawn` that allows handling of async calls in a synchronous context (including access to the synchronous closure) with less additional procs to be declared
- Write less code, catch errors that would otherwise defect in asyncspawn, and execute a callback after completion
- Add cancellation callbacks to utils/then, ensuring cancellations are handled properly
## Dependencies
- bump codex-contracts-eth to support slot queue (https://github.com/codex-storage/codex-contracts-eth/pull/61)
- bump nim-ethers to 0.5.0
- Bump nim-json-rpc submodule to 0bf2bcb
---------
Co-authored-by: Jaremy Creechley <creechley@gmail.com>
2023-07-25 02:50:30 +00:00
|
|
|
if slotId(event.requestId, event.slotIndex) == slotId:
|
2023-06-22 10:32:18 +00:00
|
|
|
slotWasFreed = true
|
|
|
|
let subscription = await marketplace.subscribe(SlotFreed, onSlotFreed)
|
|
|
|
|
|
|
|
for _ in 0..<totalProofs:
|
|
|
|
if slotWasFreed:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
await advanceToNextPeriod()
|
2023-07-13 13:58:35 +00:00
|
|
|
await sleepAsync(1.seconds)
|
2023-06-22 10:32:18 +00:00
|
|
|
|
|
|
|
check slotWasFreed
|
|
|
|
|
|
|
|
await subscription.unsubscribe()
|
|
|
|
|
|
|
|
test "slot is not freed when not enough invalid proofs submitted":
|
|
|
|
let failEveryNProofs = 3'u
|
|
|
|
let totalProofs = 12'u
|
|
|
|
startProviderNode(failEveryNProofs)
|
|
|
|
|
|
|
|
await waitUntilPurchaseIsStarted(duration=totalProofs.periods)
|
|
|
|
|
|
|
|
var slotWasFreed = false
|
|
|
|
proc onSlotFreed(event: SlotFreed) =
|
Slot queue (#455)
## Slot queue
Adds a slot queue, as per the [slot queue design](https://github.com/codex-storage/codex-research/blob/master/design/sales.md#slot-queue).
Any time storage is requested, all slots from that request are immediately added to the queue. Finished, Canclled, Failed requests remove all slots with that request id from the queue. SlotFreed events add a new slot to the queue and SlotFilled events remove the slot from the queue. This allows popping of a slot each time one is processed, making things much simpler.
When an entire request of slots is added to the queue, the slot indices are shuffled randomly to hopefully prevent nodes that pick up the same storage requested event from clashing on the first processed slot index. This allowed removal of assigning a random slot index in the SalePreparing state and it also ensured that all SalesAgents will have a slot index assigned to them at the start thus the removal of the optional slotIndex.
Remove slotId from SlotFreed event as it was not being used. RequestId and slotIndex were added to the SlotFreed event earlier and those are now being used
The slot queue invariant that prioritises queue items added to the queue relies on a scoring mechanism to sort them based on the [sort order in the design document](https://github.com/codex-storage/codex-research/blob/master/design/sales.md#sort-order).
When a storage request is handled by the sales module, a slot index was randomly assigned and then the slot was filled. Now, a random slot index is only assigned when adding an entire request to the slot queue. Additionally, the slot is checked that its state is `SlotState.Free` before continuing with the download process.
SlotQueue should always ensure the underlying AsyncHeapQueue has one less than the maximum items, ensuring the SlotQueue can always have space to add an additional item regardless if it’s full or not.
Constructing `SlotQueue.workers` in `SlotQueue.new` calls `newAsyncQueue` which causes side effects, so the construction call had to be moved to `SlotQueue.start`.
Prevent loading request from contract (network request) if there is an existing item in queue for that request.
Check availability before adding request to queue.
Add ability to query market contract for past events. When new availabilities are added, the `onReservationAdded` callback is triggered in which past `StorageRequested` events are queried, and those slots are added to the queue (filtered by availability on `push` and filtered by state in `SalePreparing`).
#### Request Workers
Limit the concurrent requests being processed in the queue by using a limited pool of workers (default = 3). Workers are in a data structure of type `AsyncQueue[SlotQueueWorker]`. This allows us to await a `popFirst` for available workers inside of the main SlotQueue event loop
Add an `onCleanUp` that stops the agents and removes them from the sales module agent list. `onCleanUp` is called from sales end states (eg ignored, cancelled, finished, failed, errored).
Add a `doneProcessing` future to `SlotQueueWorker` to be completed in the `OnProcessSlot` callback. Each `doneProcessing` future created is cancelled and awaited in `SlotQueue.stop` (thanks to `TrackableFuturees`), which forced `stop` to become async.
- Cancel dispatched workers and the `onProcessSlot` callbacks, prevents zombie callbacks
#### Add TrackableFutures
Allow tracking of futures in a module so they can be cancelled at a later time. Useful for asyncSpawned futures, but works for any future.
### Sales module
The sales module needed to subscribe to request events to ensure that the request queue was managed correctly on each event. In the process of doing this, the sales agents were updated to avoid subscribing to events in each agent, and instead dispatch received events from the sales module to all created sales agents. This would prevent memory leaks on having too many eventemitters subscribed to.
- prevent removal of agents from sales module while stopping, otherwise the agents seq len is modified while iterating
An additional sales agent state was added, `SalePreparing`, that handles all state machine setup, such as retrieving the request and subscribing to events that were previously in the `SaleDownloading` state.
Once agents have parked in an end state (eg ignored, cancelled, finished, failed, errored), they were not getting cleaned up and the sales module was keeping a handle on their reference. An `onCleanUp` callback was created to be called after the state machine enters an end state, which could prevent a memory leak if the number of requests coming in is high.
Move the SalesAgent callback raises pragmas from the Sales module to the proc definition in SalesAgent. This avoids having to catch `Exception`.
- remove unneeded error handling as pragmas were moved
Move sales.subscriptions from an object containing named subscriptions to a `seq[Subscription]` directly on the sales object.
Sales tests: shut down repo after sales stop, to fix SIGABRT in CI
### Add async Promise API
- modelled after JavaScript Promise API
- alternative to `asyncSpawn` that allows handling of async calls in a synchronous context (including access to the synchronous closure) with less additional procs to be declared
- Write less code, catch errors that would otherwise defect in asyncspawn, and execute a callback after completion
- Add cancellation callbacks to utils/then, ensuring cancellations are handled properly
## Dependencies
- bump codex-contracts-eth to support slot queue (https://github.com/codex-storage/codex-contracts-eth/pull/61)
- bump nim-ethers to 0.5.0
- Bump nim-json-rpc submodule to 0bf2bcb
---------
Co-authored-by: Jaremy Creechley <creechley@gmail.com>
2023-07-25 02:50:30 +00:00
|
|
|
if slotId(event.requestId, event.slotIndex) == slotId:
|
2023-06-22 10:32:18 +00:00
|
|
|
slotWasFreed = true
|
|
|
|
let subscription = await marketplace.subscribe(SlotFreed, onSlotFreed)
|
|
|
|
|
|
|
|
for _ in 0..<totalProofs:
|
|
|
|
if slotWasFreed:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
await advanceToNextPeriod()
|
2023-07-13 13:58:35 +00:00
|
|
|
await sleepAsync(1.seconds)
|
2023-06-22 10:32:18 +00:00
|
|
|
|
|
|
|
check not slotWasFreed
|
|
|
|
|
|
|
|
await subscription.unsubscribe()
|