2022-04-08 21:58:16 +00:00
|
|
|
import std/sets
|
|
|
|
import std/times
|
|
|
|
import pkg/upraises
|
|
|
|
import pkg/questionable
|
2022-04-20 10:39:40 +00:00
|
|
|
import pkg/chronicles
|
2022-04-13 16:41:48 +00:00
|
|
|
import ./por/timing/proofs
|
2022-04-08 21:58:16 +00:00
|
|
|
|
|
|
|
export sets
|
2022-04-13 16:41:48 +00:00
|
|
|
export proofs
|
2022-04-08 21:58:16 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
Proving* = ref object
|
2022-04-13 16:41:48 +00:00
|
|
|
proofs: Proofs
|
2022-05-17 14:40:21 +00:00
|
|
|
loop: ?Future[void]
|
2022-04-08 21:58:16 +00:00
|
|
|
contracts*: HashSet[ContractId]
|
|
|
|
onProofRequired: ?OnProofRequired
|
|
|
|
OnProofRequired* = proc (id: ContractId) {.gcsafe, upraises:[].}
|
|
|
|
|
2022-04-13 16:41:48 +00:00
|
|
|
func new*(_: type Proving, proofs: Proofs): Proving =
|
|
|
|
Proving(proofs: proofs)
|
2022-04-08 21:58:16 +00:00
|
|
|
|
|
|
|
proc `onProofRequired=`*(proving: Proving, callback: OnProofRequired) =
|
|
|
|
proving.onProofRequired = some callback
|
|
|
|
|
|
|
|
func add*(proving: Proving, id: ContractId) =
|
|
|
|
proving.contracts.incl(id)
|
|
|
|
|
|
|
|
proc removeEndedContracts(proving: Proving) {.async.} =
|
|
|
|
let now = getTime().toUnix().u256
|
|
|
|
var ended: HashSet[ContractId]
|
|
|
|
for id in proving.contracts:
|
2022-04-13 16:41:48 +00:00
|
|
|
if now >= (await proving.proofs.getProofEnd(id)):
|
2022-04-08 21:58:16 +00:00
|
|
|
ended.incl(id)
|
|
|
|
proving.contracts.excl(ended)
|
|
|
|
|
|
|
|
proc run(proving: Proving) {.async.} =
|
2022-04-20 10:39:40 +00:00
|
|
|
try:
|
2022-05-17 14:40:21 +00:00
|
|
|
while true:
|
2022-04-20 10:39:40 +00:00
|
|
|
let currentPeriod = await proving.proofs.getCurrentPeriod()
|
|
|
|
await proving.removeEndedContracts()
|
|
|
|
for id in proving.contracts:
|
|
|
|
if (await proving.proofs.isProofRequired(id)) or
|
|
|
|
(await proving.proofs.willProofBeRequired(id)):
|
|
|
|
if callback =? proving.onProofRequired:
|
|
|
|
callback(id)
|
|
|
|
await proving.proofs.waitUntilPeriod(currentPeriod + 1)
|
|
|
|
except CatchableError as e:
|
|
|
|
error "Proving failed", msg = e.msg
|
2022-04-08 21:58:16 +00:00
|
|
|
|
2022-05-17 14:40:21 +00:00
|
|
|
proc start*(proving: Proving) {.async.} =
|
|
|
|
if proving.loop.isSome:
|
|
|
|
return
|
2022-04-08 21:58:16 +00:00
|
|
|
|
2022-05-17 14:40:21 +00:00
|
|
|
proving.loop = some proving.run()
|
|
|
|
|
|
|
|
proc stop*(proving: Proving) {.async.} =
|
|
|
|
if loop =? proving.loop:
|
|
|
|
proving.loop = Future[void].none
|
|
|
|
if not loop.finished:
|
|
|
|
await loop.cancelAndWait()
|
2022-04-13 16:41:48 +00:00
|
|
|
|
|
|
|
proc submitProof*(proving: Proving, id: ContractId, proof: seq[byte]) {.async.} =
|
|
|
|
await proving.proofs.submitProof(id, proof)
|
|
|
|
|
|
|
|
proc subscribeProofSubmission*(proving: Proving,
|
|
|
|
callback: OnProofSubmitted):
|
|
|
|
Future[Subscription] =
|
|
|
|
proving.proofs.subscribeProofSubmission(callback)
|