2022-05-19 19:56:03 +00:00
|
|
|
## Nim-Codex
|
2022-01-10 15:32:56 +00:00
|
|
|
## Copyright (c) 2021 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2022-03-18 22:17:51 +00:00
|
|
|
import pkg/upraises
|
|
|
|
|
|
|
|
push: {.upraises: [].}
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
|
|
|
|
import std/sequtils
|
|
|
|
|
|
|
|
import pkg/questionable
|
|
|
|
import pkg/questionable/results
|
|
|
|
import pkg/chronicles
|
|
|
|
import pkg/chronos
|
|
|
|
import pkg/presto
|
|
|
|
import pkg/libp2p
|
2022-04-06 00:34:29 +00:00
|
|
|
import pkg/stew/base10
|
2022-05-11 08:51:59 +00:00
|
|
|
import pkg/stew/byteutils
|
2022-05-12 21:52:03 +00:00
|
|
|
import pkg/confutils
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2023-06-19 06:21:03 +00:00
|
|
|
import pkg/libp2p
|
2022-01-10 15:32:56 +00:00
|
|
|
import pkg/libp2p/routing_record
|
2022-06-14 23:34:56 +00:00
|
|
|
import pkg/libp2pdht/discv5/spr as spr
|
2023-06-19 06:21:03 +00:00
|
|
|
import pkg/libp2pdht/discv5/routing_table as rt
|
|
|
|
import pkg/libp2pdht/discv5/node as dn
|
2022-01-10 15:32:56 +00:00
|
|
|
|
|
|
|
import ../node
|
2022-04-06 00:34:29 +00:00
|
|
|
import ../blocktype
|
2022-05-12 21:52:03 +00:00
|
|
|
import ../conf
|
2022-04-21 08:12:16 +00:00
|
|
|
import ../contracts
|
2022-06-14 15:19:35 +00:00
|
|
|
import ../streams
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-11-14 23:42:57 +00:00
|
|
|
import ./coders
|
2022-05-09 13:15:23 +00:00
|
|
|
import ./json
|
|
|
|
|
2022-11-14 23:42:57 +00:00
|
|
|
logScope:
|
|
|
|
topics = "codex restapi"
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
proc validate(
|
|
|
|
pattern: string,
|
|
|
|
value: string): int
|
|
|
|
{.gcsafe, raises: [Defect].} =
|
|
|
|
0
|
|
|
|
|
2023-06-19 06:21:03 +00:00
|
|
|
proc formatAddress(address: Option[dn.Address]): string =
|
|
|
|
if address.isSome():
|
|
|
|
return $address.get()
|
|
|
|
return "<none>"
|
|
|
|
|
|
|
|
proc formatNode(node: dn.Node): JsonNode =
|
|
|
|
let jobj = %*{
|
|
|
|
"nodeId": $node.id,
|
|
|
|
"peerId": $node.record.data.peerId,
|
|
|
|
"record": $node.record,
|
|
|
|
"address": formatAddress(node.address),
|
|
|
|
"seen": $node.seen
|
|
|
|
}
|
|
|
|
return jobj
|
|
|
|
|
|
|
|
proc formatTable(routingTable: rt.RoutingTable): JsonNode =
|
|
|
|
let jarray = newJArray()
|
|
|
|
for bucket in routingTable.buckets:
|
|
|
|
for node in bucket.nodes:
|
|
|
|
jarray.add(formatNode(node))
|
|
|
|
|
|
|
|
let jobj = %*{
|
|
|
|
"localNode": formatNode(routingTable.localNode),
|
|
|
|
"nodes": jarray
|
|
|
|
}
|
|
|
|
return jobj
|
|
|
|
|
|
|
|
proc formatPeerRecord(peerRecord: PeerRecord): JsonNode =
|
|
|
|
let jarray = newJArray()
|
|
|
|
for maddr in peerRecord.addresses:
|
|
|
|
jarray.add(%*{
|
|
|
|
"address": $maddr.address
|
|
|
|
})
|
|
|
|
|
|
|
|
let jobj = %*{
|
|
|
|
"peerId": $peerRecord.peerId,
|
|
|
|
"seqNo": $peerRecord.seqNo,
|
|
|
|
"addresses": jarray
|
|
|
|
}
|
|
|
|
return jobj
|
|
|
|
|
2022-05-19 19:56:03 +00:00
|
|
|
proc initRestApi*(node: CodexNodeRef, conf: CodexConf): RestRouter =
|
2022-01-10 15:32:56 +00:00
|
|
|
var router = RestRouter.init(validate)
|
|
|
|
router.api(
|
|
|
|
MethodGet,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/connect/{peerId}") do (
|
2023-03-10 07:02:54 +00:00
|
|
|
peerId: PeerId,
|
2022-01-10 15:32:56 +00:00
|
|
|
addrs: seq[MultiAddress]) -> RestApiResponse:
|
2022-01-10 20:35:52 +00:00
|
|
|
## Connect to a peer
|
|
|
|
##
|
|
|
|
## If `addrs` param is supplied, it will be used to
|
|
|
|
## dial the peer, otherwise the `peerId` is used
|
|
|
|
## to invoke peer discovery, if it succeeds
|
|
|
|
## the returned addresses will be used to dial
|
|
|
|
##
|
2023-03-15 13:10:53 +00:00
|
|
|
## `addrs` the listening addresses of the peers to dial, eg the one specified with `--listen-addrs`
|
|
|
|
##
|
2022-01-10 20:35:52 +00:00
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
if peerId.isErr:
|
|
|
|
return RestApiResponse.error(
|
|
|
|
Http400,
|
|
|
|
$peerId.error())
|
|
|
|
|
|
|
|
let addresses = if addrs.isOk and addrs.get().len > 0:
|
|
|
|
addrs.get()
|
|
|
|
else:
|
2022-04-13 16:32:35 +00:00
|
|
|
without peerRecord =? (await node.findPeer(peerId.get())):
|
2022-01-10 15:32:56 +00:00
|
|
|
return RestApiResponse.error(
|
|
|
|
Http400,
|
|
|
|
"Unable to find Peer!")
|
2022-04-13 16:32:35 +00:00
|
|
|
peerRecord.addresses.mapIt(it.address)
|
2022-01-20 01:07:30 +00:00
|
|
|
try:
|
|
|
|
await node.connect(peerId.get(), addresses)
|
|
|
|
return RestApiResponse.response("Successfully connected to peer")
|
2023-03-09 11:23:45 +00:00
|
|
|
except DialFailedError:
|
2022-01-20 01:07:30 +00:00
|
|
|
return RestApiResponse.error(Http400, "Unable to dial peer")
|
2023-03-09 11:23:45 +00:00
|
|
|
except CatchableError:
|
2022-01-20 01:07:30 +00:00
|
|
|
return RestApiResponse.error(Http400, "Unknown error dialling peer")
|
2022-01-10 15:32:56 +00:00
|
|
|
|
|
|
|
router.api(
|
|
|
|
MethodGet,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/download/{id}") do (
|
2022-01-10 15:32:56 +00:00
|
|
|
id: Cid, resp: HttpResponseRef) -> RestApiResponse:
|
2022-01-10 20:35:52 +00:00
|
|
|
## Download a file from the node in a streaming
|
|
|
|
## manner
|
|
|
|
##
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
if id.isErr:
|
|
|
|
return RestApiResponse.error(
|
|
|
|
Http400,
|
|
|
|
$id.error())
|
|
|
|
|
2022-03-30 02:43:35 +00:00
|
|
|
var
|
|
|
|
stream: LPStream
|
2022-01-10 15:32:56 +00:00
|
|
|
|
|
|
|
var bytes = 0
|
|
|
|
try:
|
2022-04-06 00:34:29 +00:00
|
|
|
without stream =? (await node.retrieve(id.get())), error:
|
|
|
|
return RestApiResponse.error(Http404, error.msg)
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-01-20 01:07:30 +00:00
|
|
|
resp.addHeader("Content-Type", "application/octet-stream")
|
2022-01-10 15:32:56 +00:00
|
|
|
await resp.prepareChunked()
|
2022-03-30 02:43:35 +00:00
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
while not stream.atEof:
|
|
|
|
var
|
2022-04-06 00:34:29 +00:00
|
|
|
buff = newSeqUninitialized[byte](BlockSize)
|
2022-01-10 15:32:56 +00:00
|
|
|
len = await stream.readOnce(addr buff[0], buff.len)
|
|
|
|
|
|
|
|
buff.setLen(len)
|
|
|
|
if buff.len <= 0:
|
|
|
|
break
|
|
|
|
|
|
|
|
bytes += buff.len
|
2022-02-03 14:02:18 +00:00
|
|
|
trace "Sending chunk", size = buff.len
|
2022-01-10 15:32:56 +00:00
|
|
|
await resp.sendChunk(addr buff[0], buff.len)
|
2022-02-03 14:02:18 +00:00
|
|
|
await resp.finish()
|
2022-01-10 15:32:56 +00:00
|
|
|
except CatchableError as exc:
|
|
|
|
trace "Excepting streaming blocks", exc = exc.msg
|
|
|
|
return RestApiResponse.error(Http500)
|
|
|
|
finally:
|
2022-11-14 23:42:57 +00:00
|
|
|
trace "Sent bytes", cid = id.get(), bytes
|
2022-03-30 02:43:35 +00:00
|
|
|
if not stream.isNil:
|
|
|
|
await stream.close()
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-05-10 12:13:39 +00:00
|
|
|
router.rawApi(
|
2022-04-06 00:34:29 +00:00
|
|
|
MethodPost,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/storage/request/{cid}") do (cid: Cid) -> RestApiResponse:
|
2022-04-06 00:34:29 +00:00
|
|
|
## Create a request for storage
|
|
|
|
##
|
2023-03-27 13:47:25 +00:00
|
|
|
## cid - the cid of a previously uploaded dataset
|
|
|
|
## duration - the duration of the request in seconds
|
|
|
|
## proofProbability - how often storage proofs are required
|
|
|
|
## reward - the maximum amount of tokens paid per second per slot to hosts the client is willing to pay
|
|
|
|
## expiry - timestamp, in seconds, when the request expires if the Request does not find requested amount of nodes to host the data
|
|
|
|
## nodes - minimal number of nodes the content should be stored on
|
|
|
|
## tolerance - allowed number of nodes that can be lost before pronouncing the content lost
|
2023-04-14 09:04:17 +00:00
|
|
|
## colateral - requested collateral from hosts when they fill slot
|
2022-04-06 00:34:29 +00:00
|
|
|
|
2022-05-10 12:13:39 +00:00
|
|
|
without cid =? cid.tryGet.catch, error:
|
|
|
|
return RestApiResponse.error(Http400, error.msg)
|
2022-04-06 00:34:29 +00:00
|
|
|
|
2022-05-10 12:13:39 +00:00
|
|
|
let body = await request.getBody()
|
2022-04-06 00:34:29 +00:00
|
|
|
|
2022-05-10 12:13:39 +00:00
|
|
|
without params =? StorageRequestParams.fromJson(body), error:
|
|
|
|
return RestApiResponse.error(Http400, error.msg)
|
|
|
|
|
2022-08-02 15:50:57 +00:00
|
|
|
let nodes = params.nodes |? 1
|
2023-03-13 12:23:50 +00:00
|
|
|
let tolerance = params.tolerance |? 0
|
2022-08-02 15:50:57 +00:00
|
|
|
|
2022-11-14 23:42:57 +00:00
|
|
|
without purchaseId =? await node.requestStorage(
|
|
|
|
cid,
|
|
|
|
params.duration,
|
2023-03-27 13:47:25 +00:00
|
|
|
params.proofProbability,
|
2022-11-14 23:42:57 +00:00
|
|
|
nodes,
|
|
|
|
tolerance,
|
|
|
|
params.reward,
|
2023-04-14 09:04:17 +00:00
|
|
|
params.collateral,
|
2022-11-14 23:42:57 +00:00
|
|
|
params.expiry), error:
|
|
|
|
|
2022-05-10 12:13:39 +00:00
|
|
|
return RestApiResponse.error(Http500, error.msg)
|
|
|
|
|
2022-05-11 07:01:31 +00:00
|
|
|
return RestApiResponse.response(purchaseId.toHex)
|
2022-04-06 00:34:29 +00:00
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
router.rawApi(
|
|
|
|
MethodPost,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/upload") do (
|
2022-01-10 15:32:56 +00:00
|
|
|
) -> RestApiResponse:
|
2023-03-15 13:10:53 +00:00
|
|
|
## Upload a file in a streaming manner
|
2022-01-10 20:35:52 +00:00
|
|
|
##
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
trace "Handling file upload"
|
|
|
|
var bodyReader = request.getBodyReader()
|
|
|
|
if bodyReader.isErr():
|
|
|
|
return RestApiResponse.error(Http500)
|
|
|
|
|
|
|
|
# Attempt to handle `Expect` header
|
2022-01-10 20:35:52 +00:00
|
|
|
# some clients (curl), wait 1000ms
|
2022-01-10 15:32:56 +00:00
|
|
|
# before giving up
|
|
|
|
#
|
|
|
|
await request.handleExpect()
|
|
|
|
|
|
|
|
let
|
|
|
|
reader = bodyReader.get()
|
|
|
|
|
|
|
|
try:
|
2022-06-14 15:19:35 +00:00
|
|
|
without cid =? (
|
|
|
|
await node.store(AsyncStreamWrapper.new(reader = AsyncStreamReader(reader)))), error:
|
|
|
|
trace "Error uploading file", exc = error.msg
|
2022-04-06 00:34:29 +00:00
|
|
|
return RestApiResponse.error(Http500, error.msg)
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2022-10-27 13:41:34 +00:00
|
|
|
trace "Uploaded file", cid
|
2022-01-10 15:32:56 +00:00
|
|
|
return RestApiResponse.response($cid)
|
2023-03-09 11:23:45 +00:00
|
|
|
except CancelledError:
|
2022-01-10 15:32:56 +00:00
|
|
|
return RestApiResponse.error(Http500)
|
|
|
|
except AsyncStreamError:
|
|
|
|
return RestApiResponse.error(Http500)
|
|
|
|
finally:
|
|
|
|
await reader.closeWait()
|
|
|
|
|
|
|
|
# if we got here something went wrong?
|
|
|
|
return RestApiResponse.error(Http500)
|
|
|
|
|
2022-11-14 23:42:57 +00:00
|
|
|
router.api(
|
|
|
|
MethodPost,
|
|
|
|
"/api/codex/v1/debug/chronicles/loglevel") do (
|
|
|
|
level: Option[string]) -> RestApiResponse:
|
|
|
|
## Set log level at run time
|
|
|
|
##
|
|
|
|
## e.g. `chronicles/loglevel?level=DEBUG`
|
|
|
|
##
|
|
|
|
## `level` - chronicles log level
|
|
|
|
##
|
|
|
|
|
|
|
|
without res =? level and level =? res:
|
|
|
|
return RestApiResponse.error(Http400, "Missing log level")
|
|
|
|
|
|
|
|
try:
|
|
|
|
{.gcsafe.}:
|
|
|
|
updateLogLevel(level)
|
|
|
|
except CatchableError as exc:
|
|
|
|
return RestApiResponse.error(Http500, exc.msg)
|
|
|
|
|
|
|
|
return RestApiResponse.response("")
|
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
router.api(
|
|
|
|
MethodGet,
|
2022-11-14 23:42:57 +00:00
|
|
|
"/api/codex/v1/debug/info") do () -> RestApiResponse:
|
2022-01-10 20:35:52 +00:00
|
|
|
## Print rudimentary node information
|
|
|
|
##
|
|
|
|
|
2022-11-02 00:58:41 +00:00
|
|
|
let
|
|
|
|
json = %*{
|
|
|
|
"id": $node.switch.peerInfo.peerId,
|
|
|
|
"addrs": node.switch.peerInfo.addrs.mapIt( $it ),
|
|
|
|
"repo": $conf.dataDir,
|
|
|
|
"spr":
|
|
|
|
if node.discovery.dhtRecord.isSome:
|
|
|
|
node.discovery.dhtRecord.get.toURI
|
|
|
|
else:
|
2023-03-08 11:45:55 +00:00
|
|
|
"",
|
2023-06-19 06:21:03 +00:00
|
|
|
"table": formatTable(node.discovery.protocol.routingTable),
|
2023-03-08 11:45:55 +00:00
|
|
|
"codex": {
|
|
|
|
"version": $codexVersion,
|
|
|
|
"revision": $codexRevision
|
|
|
|
}
|
2022-11-02 00:58:41 +00:00
|
|
|
}
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2023-06-13 13:33:01 +00:00
|
|
|
return RestApiResponse.response($json, contentType="application/json")
|
2022-01-10 15:32:56 +00:00
|
|
|
|
2023-06-19 06:21:03 +00:00
|
|
|
when codex_enable_api_debug_peers:
|
|
|
|
router.api(
|
|
|
|
MethodGet,
|
|
|
|
"/api/codex/v1/debug/peer/{peerId}") do (peerId: PeerId) -> RestApiResponse:
|
|
|
|
|
|
|
|
trace "debug/peer start"
|
|
|
|
without peerRecord =? (await node.findPeer(peerId.get())):
|
|
|
|
trace "debug/peer peer not found!"
|
|
|
|
return RestApiResponse.error(
|
|
|
|
Http400,
|
|
|
|
"Unable to find Peer!")
|
|
|
|
|
|
|
|
let json = formatPeerRecord(peerRecord)
|
|
|
|
trace "debug/peer returning peer record"
|
|
|
|
return RestApiResponse.response($json)
|
|
|
|
|
2022-05-09 14:51:08 +00:00
|
|
|
router.api(
|
|
|
|
MethodGet,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/sales/availability") do () -> RestApiResponse:
|
2022-05-09 14:51:08 +00:00
|
|
|
## Returns storage that is for sale
|
|
|
|
|
[marketplace] Add Reservations Module (#340)
* [marketplace] reservations module
- add de/serialization for Availability
- add markUsed/markUnused in persisted availability
- add query for unused
- add reserve/release
- reservation module tests
- split ContractInteractions into client contracts and host contracts
- remove reservations start/stop as the repo start/stop is being managed by the node
- remove dedicated reservations metadata store and use the metadata store from the repo instead
- Split ContractInteractions into:
- ClientInteractions (with purchasing)
- HostInteractions (with sales and proving)
- compilation fix for nim 1.2
[repostore] fix started flag, add tests
[marketplace] persist slot index
For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded.
* Revert repostore changes
In favour of separate PR https://github.com/status-im/nim-codex/pull/374.
* remove warnings
* clean up
* tests: stop repostore during teardown
* change constructor type identifier
Change Contracts constructor to accept Contracts type instead of ContractInteractions.
* change constructor return type to Result instead of Option
* fix and split interactions tests
* clean up, fix tests
* find availability by slot id
* remove duplication in host/client interactions
* add test for finding availability by slotId
* log instead of raiseAssert when failed to mark availability as unused
* move to SaleErrored state instead of raiseAssert
* remove unneeded reverse
It appears that order is not preserved in the repostore, so reversing does not have the intended effect here.
* update open api spec for potential rest endpoint errors
* move functions about available bytes to repostore
* WIP: reserve and release availabilities as needed
WIP: not tested yet
Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use.
As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well.
During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes.
Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur.
* delete availability when all bytes released
* fix tests + cleanup
* remove availability from SalesContext callbacks
Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart.
Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed.
* test clean up
* - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie)
- fix integration test that checks availabilities
- there was a bug fixed that crashed the node due to a missing `return success` in onStore
- the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced
- change Availability back to non-ref object and constructor back to init
- add trace logging of all state transitions in state machine
- add generally useful trace logging
* fixes after rebase
1. Fix onProve callbacks
2. Use Slot type instead of tuple for retrieving active slot.
3. Bump codex-contracts-eth that exposes getActivceSlot call.
* swap contracts branch to not support slot collateral
Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit.
* modify Interactions and Deployment constructors
- `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads
- `Interactions` prepared simplified so there are no overloads
- `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]`
* Move `batchProc` declaration
`batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency.
* [reservations] rename `available` to `hasAvailable`
* [reservations] default error message to inner error msg
* add SaleIngored state
When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
|
|
|
without contracts =? node.contracts.host:
|
2022-05-09 14:51:08 +00:00
|
|
|
return RestApiResponse.error(Http503, "Sales unavailable")
|
|
|
|
|
[marketplace] Add Reservations Module (#340)
* [marketplace] reservations module
- add de/serialization for Availability
- add markUsed/markUnused in persisted availability
- add query for unused
- add reserve/release
- reservation module tests
- split ContractInteractions into client contracts and host contracts
- remove reservations start/stop as the repo start/stop is being managed by the node
- remove dedicated reservations metadata store and use the metadata store from the repo instead
- Split ContractInteractions into:
- ClientInteractions (with purchasing)
- HostInteractions (with sales and proving)
- compilation fix for nim 1.2
[repostore] fix started flag, add tests
[marketplace] persist slot index
For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded.
* Revert repostore changes
In favour of separate PR https://github.com/status-im/nim-codex/pull/374.
* remove warnings
* clean up
* tests: stop repostore during teardown
* change constructor type identifier
Change Contracts constructor to accept Contracts type instead of ContractInteractions.
* change constructor return type to Result instead of Option
* fix and split interactions tests
* clean up, fix tests
* find availability by slot id
* remove duplication in host/client interactions
* add test for finding availability by slotId
* log instead of raiseAssert when failed to mark availability as unused
* move to SaleErrored state instead of raiseAssert
* remove unneeded reverse
It appears that order is not preserved in the repostore, so reversing does not have the intended effect here.
* update open api spec for potential rest endpoint errors
* move functions about available bytes to repostore
* WIP: reserve and release availabilities as needed
WIP: not tested yet
Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use.
As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well.
During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes.
Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur.
* delete availability when all bytes released
* fix tests + cleanup
* remove availability from SalesContext callbacks
Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart.
Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed.
* test clean up
* - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie)
- fix integration test that checks availabilities
- there was a bug fixed that crashed the node due to a missing `return success` in onStore
- the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced
- change Availability back to non-ref object and constructor back to init
- add trace logging of all state transitions in state machine
- add generally useful trace logging
* fixes after rebase
1. Fix onProve callbacks
2. Use Slot type instead of tuple for retrieving active slot.
3. Bump codex-contracts-eth that exposes getActivceSlot call.
* swap contracts branch to not support slot collateral
Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit.
* modify Interactions and Deployment constructors
- `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads
- `Interactions` prepared simplified so there are no overloads
- `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]`
* Move `batchProc` declaration
`batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency.
* [reservations] rename `available` to `hasAvailable`
* [reservations] default error message to inner error msg
* add SaleIngored state
When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
|
|
|
without unused =? (await contracts.sales.context.reservations.unused), err:
|
|
|
|
return RestApiResponse.error(Http500, err.msg)
|
|
|
|
|
|
|
|
let json = %unused
|
2023-06-13 13:33:01 +00:00
|
|
|
return RestApiResponse.response($json, contentType="application/json")
|
2022-05-09 14:51:08 +00:00
|
|
|
|
2022-05-09 13:15:23 +00:00
|
|
|
router.rawApi(
|
|
|
|
MethodPost,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/sales/availability") do () -> RestApiResponse:
|
2022-04-21 08:12:16 +00:00
|
|
|
## Add available storage to sell
|
|
|
|
##
|
2023-04-14 09:04:17 +00:00
|
|
|
## size - size of available storage in bytes
|
|
|
|
## duration - maximum time the storage should be sold for (in seconds)
|
|
|
|
## minPrice - minimum price to be paid (in amount of tokens)
|
|
|
|
## maxCollateral - maximum collateral user is willing to pay per filled Slot (in amount of tokens)
|
2022-04-21 08:12:16 +00:00
|
|
|
|
[marketplace] Add Reservations Module (#340)
* [marketplace] reservations module
- add de/serialization for Availability
- add markUsed/markUnused in persisted availability
- add query for unused
- add reserve/release
- reservation module tests
- split ContractInteractions into client contracts and host contracts
- remove reservations start/stop as the repo start/stop is being managed by the node
- remove dedicated reservations metadata store and use the metadata store from the repo instead
- Split ContractInteractions into:
- ClientInteractions (with purchasing)
- HostInteractions (with sales and proving)
- compilation fix for nim 1.2
[repostore] fix started flag, add tests
[marketplace] persist slot index
For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded.
* Revert repostore changes
In favour of separate PR https://github.com/status-im/nim-codex/pull/374.
* remove warnings
* clean up
* tests: stop repostore during teardown
* change constructor type identifier
Change Contracts constructor to accept Contracts type instead of ContractInteractions.
* change constructor return type to Result instead of Option
* fix and split interactions tests
* clean up, fix tests
* find availability by slot id
* remove duplication in host/client interactions
* add test for finding availability by slotId
* log instead of raiseAssert when failed to mark availability as unused
* move to SaleErrored state instead of raiseAssert
* remove unneeded reverse
It appears that order is not preserved in the repostore, so reversing does not have the intended effect here.
* update open api spec for potential rest endpoint errors
* move functions about available bytes to repostore
* WIP: reserve and release availabilities as needed
WIP: not tested yet
Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use.
As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well.
During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes.
Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur.
* delete availability when all bytes released
* fix tests + cleanup
* remove availability from SalesContext callbacks
Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart.
Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed.
* test clean up
* - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie)
- fix integration test that checks availabilities
- there was a bug fixed that crashed the node due to a missing `return success` in onStore
- the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced
- change Availability back to non-ref object and constructor back to init
- add trace logging of all state transitions in state machine
- add generally useful trace logging
* fixes after rebase
1. Fix onProve callbacks
2. Use Slot type instead of tuple for retrieving active slot.
3. Bump codex-contracts-eth that exposes getActivceSlot call.
* swap contracts branch to not support slot collateral
Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit.
* modify Interactions and Deployment constructors
- `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads
- `Interactions` prepared simplified so there are no overloads
- `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]`
* Move `batchProc` declaration
`batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency.
* [reservations] rename `available` to `hasAvailable`
* [reservations] default error message to inner error msg
* add SaleIngored state
When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
|
|
|
without contracts =? node.contracts.host:
|
2022-05-09 14:51:08 +00:00
|
|
|
return RestApiResponse.error(Http503, "Sales unavailable")
|
|
|
|
|
2022-05-09 13:15:23 +00:00
|
|
|
let body = await request.getBody()
|
2022-04-21 08:12:16 +00:00
|
|
|
|
2022-05-09 13:15:23 +00:00
|
|
|
without availability =? Availability.fromJson(body), error:
|
|
|
|
return RestApiResponse.error(Http400, error.msg)
|
2022-04-21 08:12:16 +00:00
|
|
|
|
[marketplace] Add Reservations Module (#340)
* [marketplace] reservations module
- add de/serialization for Availability
- add markUsed/markUnused in persisted availability
- add query for unused
- add reserve/release
- reservation module tests
- split ContractInteractions into client contracts and host contracts
- remove reservations start/stop as the repo start/stop is being managed by the node
- remove dedicated reservations metadata store and use the metadata store from the repo instead
- Split ContractInteractions into:
- ClientInteractions (with purchasing)
- HostInteractions (with sales and proving)
- compilation fix for nim 1.2
[repostore] fix started flag, add tests
[marketplace] persist slot index
For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded.
* Revert repostore changes
In favour of separate PR https://github.com/status-im/nim-codex/pull/374.
* remove warnings
* clean up
* tests: stop repostore during teardown
* change constructor type identifier
Change Contracts constructor to accept Contracts type instead of ContractInteractions.
* change constructor return type to Result instead of Option
* fix and split interactions tests
* clean up, fix tests
* find availability by slot id
* remove duplication in host/client interactions
* add test for finding availability by slotId
* log instead of raiseAssert when failed to mark availability as unused
* move to SaleErrored state instead of raiseAssert
* remove unneeded reverse
It appears that order is not preserved in the repostore, so reversing does not have the intended effect here.
* update open api spec for potential rest endpoint errors
* move functions about available bytes to repostore
* WIP: reserve and release availabilities as needed
WIP: not tested yet
Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use.
As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well.
During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes.
Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur.
* delete availability when all bytes released
* fix tests + cleanup
* remove availability from SalesContext callbacks
Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart.
Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed.
* test clean up
* - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie)
- fix integration test that checks availabilities
- there was a bug fixed that crashed the node due to a missing `return success` in onStore
- the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced
- change Availability back to non-ref object and constructor back to init
- add trace logging of all state transitions in state machine
- add generally useful trace logging
* fixes after rebase
1. Fix onProve callbacks
2. Use Slot type instead of tuple for retrieving active slot.
3. Bump codex-contracts-eth that exposes getActivceSlot call.
* swap contracts branch to not support slot collateral
Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit.
* modify Interactions and Deployment constructors
- `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads
- `Interactions` prepared simplified so there are no overloads
- `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]`
* Move `batchProc` declaration
`batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency.
* [reservations] rename `available` to `hasAvailable`
* [reservations] default error message to inner error msg
* add SaleIngored state
When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
|
|
|
let reservations = contracts.sales.context.reservations
|
|
|
|
|
|
|
|
if not reservations.hasAvailable(availability.size.truncate(uint)):
|
|
|
|
return RestApiResponse.error(Http422, "Not enough storage quota")
|
|
|
|
|
|
|
|
if err =? (await reservations.reserve(availability)).errorOption:
|
|
|
|
return RestApiResponse.error(Http500, err.msg)
|
2022-05-09 14:51:08 +00:00
|
|
|
|
|
|
|
let json = %availability
|
2023-06-13 13:33:01 +00:00
|
|
|
return RestApiResponse.response($json, contentType="application/json")
|
2022-04-21 08:12:16 +00:00
|
|
|
|
2022-05-11 08:51:59 +00:00
|
|
|
router.api(
|
|
|
|
MethodGet,
|
2022-05-19 19:56:03 +00:00
|
|
|
"/api/codex/v1/storage/purchases/{id}") do (
|
2022-08-17 02:29:44 +00:00
|
|
|
id: PurchaseId) -> RestApiResponse:
|
2022-05-11 08:51:59 +00:00
|
|
|
|
[marketplace] Add Reservations Module (#340)
* [marketplace] reservations module
- add de/serialization for Availability
- add markUsed/markUnused in persisted availability
- add query for unused
- add reserve/release
- reservation module tests
- split ContractInteractions into client contracts and host contracts
- remove reservations start/stop as the repo start/stop is being managed by the node
- remove dedicated reservations metadata store and use the metadata store from the repo instead
- Split ContractInteractions into:
- ClientInteractions (with purchasing)
- HostInteractions (with sales and proving)
- compilation fix for nim 1.2
[repostore] fix started flag, add tests
[marketplace] persist slot index
For loading the sales state from chain, the slot index was not previously persisted in the contract. Will retrieve the slot index from the contract when the sales state is loaded.
* Revert repostore changes
In favour of separate PR https://github.com/status-im/nim-codex/pull/374.
* remove warnings
* clean up
* tests: stop repostore during teardown
* change constructor type identifier
Change Contracts constructor to accept Contracts type instead of ContractInteractions.
* change constructor return type to Result instead of Option
* fix and split interactions tests
* clean up, fix tests
* find availability by slot id
* remove duplication in host/client interactions
* add test for finding availability by slotId
* log instead of raiseAssert when failed to mark availability as unused
* move to SaleErrored state instead of raiseAssert
* remove unneeded reverse
It appears that order is not preserved in the repostore, so reversing does not have the intended effect here.
* update open api spec for potential rest endpoint errors
* move functions about available bytes to repostore
* WIP: reserve and release availabilities as needed
WIP: not tested yet
Availabilities are marked as used when matched (just before downloading starts) so that future matching logic does not match an availability currently in use.
As the download progresses, batches of blocks are written to disk, and the equivalent bytes are released from the reservation module. The size of the availability is reduced as well.
During a reserve or release operation, availability updates occur after the repo is manipulated. If the availability update operation fails, the reserve or release is rolled back to maintain correct accounting of bytes.
Finally, once download completes, or if an error occurs, the availability is marked as unused so future matching can occur.
* delete availability when all bytes released
* fix tests + cleanup
* remove availability from SalesContext callbacks
Availability is no longer used past the SaleDownloading state in the state machine. Cleanup of Availability (marking unused) is handled directly in the SaleDownloading state, and no longer in SaleErrored or SaleFinished. Likewise, Availabilities shouldn’t need to be handled on node restart.
Additionally, Availability was being passed in SalesContext callbacks, and now that Availability is only used temporarily in the SaleDownloading state, Availability is contextually irrelevant to the callbacks, except in OnStore possibly, though it was not being consumed.
* test clean up
* - remove availability from callbacks and constructors from previous commit that needed to be removed (oopsie)
- fix integration test that checks availabilities
- there was a bug fixed that crashed the node due to a missing `return success` in onStore
- the test was fixed by ensuring that availabilities are remaining on the node, and the size has been reduced
- change Availability back to non-ref object and constructor back to init
- add trace logging of all state transitions in state machine
- add generally useful trace logging
* fixes after rebase
1. Fix onProve callbacks
2. Use Slot type instead of tuple for retrieving active slot.
3. Bump codex-contracts-eth that exposes getActivceSlot call.
* swap contracts branch to not support slot collateral
Slot collateral changes in the contracts require further changes in the client code, so we’ll skip those changes for now and add in a separate commit.
* modify Interactions and Deployment constructors
- `HostInteractions` and `ClientInteractions` constructors were simplified to take a contract address and no overloads
- `Interactions` prepared simplified so there are no overloads
- `Deployment` constructor updated so that it takes an optional string parameter, instead `Option[string]`
* Move `batchProc` declaration
`batchProc` needs to be consumed by both `node` and `salescontext`, and they can’t reference each other as it creates a circular dependency.
* [reservations] rename `available` to `hasAvailable`
* [reservations] default error message to inner error msg
* add SaleIngored state
When a storage request is handled but the request does match availabilities, the sales agent machine is sent to the SaleIgnored state. In addition, the agent is constructed in a way that if the request is ignored, the sales agent is removed from the list of active agents being tracked in the sales module.
2023-04-04 07:05:16 +00:00
|
|
|
without contracts =? node.contracts.client:
|
2022-05-11 08:51:59 +00:00
|
|
|
return RestApiResponse.error(Http503, "Purchasing unavailable")
|
|
|
|
|
|
|
|
without id =? id.tryGet.catch, error:
|
|
|
|
return RestApiResponse.error(Http400, error.msg)
|
|
|
|
|
|
|
|
without purchase =? contracts.purchasing.getPurchase(id):
|
|
|
|
return RestApiResponse.error(Http404)
|
|
|
|
|
|
|
|
let json = %purchase
|
|
|
|
|
2023-06-13 13:33:01 +00:00
|
|
|
return RestApiResponse.response($json, contentType="application/json")
|
2022-05-11 08:51:59 +00:00
|
|
|
|
2022-01-10 15:32:56 +00:00
|
|
|
return router
|