Nim: better handling of trusted setup (#231)

This commit is contained in:
andri lim 2023-03-21 09:30:50 +07:00 committed by GitHub
parent b7902b2300
commit bf99ed5b91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 22 additions and 4 deletions

View File

@ -208,6 +208,9 @@ proc verifyProofs*(ctx: KzgCtx,
template loadTrustedSetupFile*(input: File | string): untyped =
loadTrustedSetup(input)
template freeTrustedSetup*(ctx: KzgCtx) =
free_trusted_setup(ctx.val)
template blobToKzgCommitment*(ctx: KzgCtx,
blob: KzgBlob): untyped =
toCommitment(ctx, blob)

View File

@ -22,12 +22,16 @@ else:
# Private helpers
##############################################################
var gCtx: KzgCtx
var gCtx = KzgCtx(nil)
const
GlobalCtxErr = "kzg global context not loaded"
TrustedSetupNotLoadedErr = "Trusted setup not loaded."
TrustedSetupAlreadyLoadedErr =
"Trusted setup is already loaded. Free it before loading a new one."
template setupCtx(body: untyped): untyped =
if not gCtx.isNil:
return err(TrustedSetupAlreadyLoadedErr)
let res = body
if res.isErr:
return err(res.error)
@ -37,7 +41,7 @@ template setupCtx(body: untyped): untyped =
template verifyCtx(body: untyped): untyped =
{.gcsafe.}:
if gCtx.isNil:
return err(GlobalCtxErr)
return err(TrustedSetupNotLoadedErr)
body
##############################################################
@ -65,6 +69,12 @@ proc loadTrustedSetupFromString*(_: type Kzg,
setupCtx:
kzg.loadTrustedSetupFromString(input)
proc freeTrustedSetup*(_: type Kzg): Result[void, string] =
verifyCtx:
gCtx.freeTrustedSetup()
gCtx = nil
ok()
proc toCommitment*(blob: KzgBlob):
Result[KzgCommitment, string] {.gcsafe.} =
verifyCtx:

View File

@ -75,7 +75,8 @@ suite "verify proof (extended version)":
test "template aliases":
# no need to check return value
# only test if those templates can be compiled succesfully
discard Kzg.loadTrustedSetupFile(trustedSetupFile)
check Kzg.freeTrustedSetup().isOk
check Kzg.loadTrustedSetupFile(trustedSetupFile).isOk
discard blobToKzgCommitment(blob)
let kp = computeKzgProof(blob, inputPoint)
discard computeBlobKzgProof(blob, commitment)
@ -83,3 +84,7 @@ suite "verify proof (extended version)":
discard verifyBlobKzgProof(blob, commitment, proof)
let kb = createKateBlobs(1)
discard verifyBlobKzgProofBatch(kb.blobs, kb.kates, [kp.get.proof])
test "load trusted setup more than once":
let res = Kzg.loadTrustedSetupFromString(trustedSetup)
check res.isErr