Skip to content

Commit 1de746b

Browse files
committed
synchronize Circom prover access using a semaphore
1 parent c486e8c commit 1de746b

File tree

1 file changed

+28
-19
lines changed

1 file changed

+28
-19
lines changed

Diff for: codex/slots/proofs/backends/circomcompat.nim

+28-19
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
{.push raises: [].}
1111

12-
import std/[sugar, atomics]
12+
import std/[sugar, atomics, locks]
1313

1414
import pkg/chronos
1515
import pkg/taskpools
@@ -39,6 +39,7 @@ type
3939
backendCfg: ptr CircomBn254Cfg
4040
vkp*: ptr CircomKey
4141
taskpool: Taskpool
42+
lock: ptr Lock
4243

4344
NormalizedProofInputs*[H] {.borrow: `.`.} = distinct ProofInputs[H]
4445

@@ -97,24 +98,29 @@ proc release*(self: CircomCompat) =
9798
if not isNil(self.vkp):
9899
self.vkp.unsafeAddr.release_key()
99100

101+
if not isNil(self.lock):
102+
deinitLock(self.lock[]) # Cleanup the lock
103+
dealloc(self.lock) # Free the memory
104+
100105
proc circomProveTask(task: ptr ProveTask) {.gcsafe.} =
101-
defer:
102-
discard task[].signal.fireSync()
106+
withLock task[].circom.lock[]:
107+
defer:
108+
discard task[].signal.fireSync()
103109

104-
var proofPtr: ptr Proof = nil
105-
try:
106-
if (
107-
let res = task.circom.backendCfg.prove_circuit(task.ctx, proofPtr.addr)
108-
res != ERR_OK
109-
) or proofPtr == nil:
110-
task.success.store(false)
111-
return
112-
113-
copyProof(task.proof, proofPtr[])
114-
task.success.store(true)
115-
finally:
116-
if proofPtr != nil:
117-
proofPtr.addr.release_proof()
110+
var proofPtr: ptr Proof = nil
111+
try:
112+
if (
113+
let res = task.circom.backendCfg.prove_circuit(task.ctx, proofPtr.addr)
114+
res != ERR_OK
115+
) or proofPtr == nil:
116+
task.success.store(false)
117+
return
118+
119+
copyProof(task.proof, proofPtr[])
120+
task.success.store(true)
121+
finally:
122+
if proofPtr != nil:
123+
proofPtr.addr.release_proof()
118124

119125
proc asyncProve*[H](
120126
self: CircomCompat, input: NormalizedProofInputs[H], proof: ptr Proof
@@ -328,9 +334,11 @@ proc init*(
328334
numSamples = DefaultSamplesNum,
329335
taskpool: Taskpool,
330336
): CircomCompat =
331-
## Create a new ctx
332-
##
337+
# Allocate and initialize the lock
338+
var lockPtr = create(Lock) # Allocate memory for the lock
339+
initLock(lockPtr[]) # Initialize the lock
333340

341+
## Create a new ctx
334342
var cfg: ptr CircomBn254Cfg
335343
var zkey = if zkeyPath.len > 0: zkeyPath.cstring else: nil
336344

@@ -359,4 +367,5 @@ proc init*(
359367
backendCfg: cfg,
360368
vkp: vkpPtr,
361369
taskpool: taskpool,
370+
lock: lockPtr,
362371
)

0 commit comments

Comments
 (0)