nim-dagger/benchmarks/circomcompat_cli.nim

282 lines
7.4 KiB
Nim
Raw Normal View History

2024-05-10 16:12:34 +03:00
import std/[sequtils, strformat, os, options, importutils]
2024-05-23 21:59:05 +03:00
import std/[times, os, strutils, terminal, parseopt, json]
2024-05-10 16:12:34 +03:00
import pkg/questionable
import pkg/questionable/results
2024-05-28 15:57:28 +01:00
import pkg/serde/json except `%*`, `%`
2024-05-10 16:12:34 +03:00
2024-05-23 21:59:05 +03:00
import pkg/circomcompat
import pkg/poseidon2/io
2024-05-10 16:12:34 +03:00
import ./utils
import ./create_circuits
2024-05-28 15:57:28 +01:00
import ./clitypes
2024-05-10 16:12:34 +03:00
2024-05-28 15:39:17 +01:00
type CircomCircuit* = object
r1csPath*: string
wasmPath*: string
zkeyPath*: string
inputsPath*: string
dir*: string
circName*: string
backendCfg: ptr CircomBn254Cfg
vkp*: ptr VerifyingKey
2024-05-23 21:59:05 +03:00
proc release*(self: CircomCircuit) =
2024-05-10 22:38:35 +03:00
## Release the ctx
##
if not isNil(self.backendCfg):
self.backendCfg.unsafeAddr.releaseCfg()
if not isNil(self.vkp):
self.vkp.unsafeAddr.release_key()
2024-05-28 15:39:17 +01:00
proc initialize*(self: var CircomCircuit) =
2024-05-24 15:49:56 +03:00
## Create a new ctx
##
var cfg: ptr CircomBn254Cfg
2024-05-28 15:39:17 +01:00
var zkey = if self.zkeyPath.len > 0: self.zkeyPath.cstring else: nil
2024-05-24 15:49:56 +03:00
2024-05-28 15:39:17 +01:00
if initCircomConfig(
self.r1csPath.cstring, self.wasmPath.cstring, self.zkeyPath.cstring, cfg.addr
) != ERR_OK or cfg == nil:
2024-05-24 15:49:56 +03:00
if cfg != nil:
cfg.addr.releaseCfg()
raiseAssert("failed to initialize circom compat config")
var vkpPtr: ptr VerifyingKey = nil
if cfg.getVerifyingKey(vkpPtr.addr) != ERR_OK or vkpPtr == nil:
if vkpPtr != nil:
vkpPtr.addr.releaseKey()
raiseAssert("Failed to get verifying key")
2024-05-28 15:39:17 +01:00
self.backendCfg = cfg
self.vkp = vkpPtr
2024-05-24 15:49:56 +03:00
2024-05-28 19:52:10 +01:00
proc parseJsons(
ctx: var ptr CircomCompatCtx,
key: string,
value: JsonNode
) =
if value.kind == JString:
var num = value.parseBigInt()
echo "Big NUM: ", num
if ctx.pushInputU256Array(key.cstring, num.addr, 1) != ERR_OK:
raise newException(ValueError, "Failed to push BigInt from dec string")
elif value.kind == JInt:
var num = value.getInt().uint64
2024-05-28 23:27:17 +01:00
echo "NUM: ", num, " orig: ", value.getInt()
2024-05-28 19:52:10 +01:00
if ctx.pushInputU64(key.cstring, num) != ERR_OK:
raise newException(ValueError, "Failed to push JInt")
elif value.kind == JArray:
2024-05-28 23:35:56 +01:00
var inputs = newSeq[UInt256]()
2024-05-28 19:52:10 +01:00
for item in value:
2024-05-28 23:35:56 +01:00
if item.kind == JString:
inputs.add item.parseBigInt()
elif item.kind == JArray:
for subitem in item:
doAssert subitem.kind == JString
inputs.add subitem.parseBigInt()
if ctx.pushInputU256Array(key.cstring, inputs[0].addr, inputs.len.uint) != ERR_OK:
raise newException(ValueError, "Failed to push BigInt from dec string")
2024-05-28 19:52:10 +01:00
else:
echo "unhandled val: " & $value
raise newException(ValueError, "Failed to push Json of " & $value.kind)
2024-05-28 23:27:17 +01:00
proc initCircomCtx*(
self: CircomCircuit, input: JsonNode
): ptr CircomCompatCtx =
2024-05-10 22:38:35 +03:00
# TODO: All parameters should match circom's static parametter
2024-05-10 22:47:39 +03:00
var ctx: ptr CircomCompatCtx
2024-05-10 22:38:35 +03:00
2024-05-23 22:00:30 +03:00
if initCircomCompat(self.backendCfg, addr ctx) != ERR_OK or ctx == nil:
2024-05-23 21:59:05 +03:00
raiseAssert("failed to initialize CircomCircuit ctx")
2024-05-10 22:38:35 +03:00
2024-05-28 19:52:10 +01:00
for key, value in input:
echo "KEY: ", key, " VAL: ", value.kind
ctx.parseJsons(key, value)
2024-05-28 23:27:17 +01:00
return ctx
2024-05-10 22:38:35 +03:00
2024-05-28 23:27:17 +01:00
proc prove*(
2024-05-28 23:30:16 +01:00
self: CircomCircuit, ctx: ptr CircomCompatCtx
2024-05-28 23:27:17 +01:00
): CircomProof =
## Encode buffers using a ctx
##
2024-05-28 15:24:09 +01:00
2024-05-10 22:47:39 +03:00
var proofPtr: ptr Proof = nil
2024-05-10 22:38:35 +03:00
2024-05-28 15:57:28 +01:00
let proof: Proof =
2024-05-10 22:38:35 +03:00
try:
2024-05-10 22:47:39 +03:00
if (let res = self.backendCfg.proveCircuit(ctx, proofPtr.addr); res != ERR_OK) or
proofPtr == nil:
2024-05-28 15:24:09 +01:00
echo "Failed to prove - err code: " & $res
2024-05-10 22:38:35 +03:00
proofPtr[]
finally:
if proofPtr != nil:
proofPtr.addr.releaseProof()
2024-05-28 19:52:10 +01:00
# echo "Proof:"
# echo proof
2024-05-28 23:27:17 +01:00
echo "\nProof:json: "
2024-05-28 15:57:28 +01:00
let g16proof: Groth16Proof = proof.toGroth16Proof()
echo pretty(%*(g16proof))
2024-05-28 23:27:17 +01:00
return proof
proc verify*(
self: CircomCircuit,
2024-05-28 23:30:16 +01:00
ctx: ptr CircomCompatCtx,
2024-05-28 23:27:17 +01:00
proof: CircomProof,
): bool =
## Verify a proof using a ctx
var inputs: ptr Inputs
doAssert ctx.get_pub_inputs(inputs.addr) == ERR_OK
2024-05-28 23:40:10 +01:00
echo "inputs val: ", inputs.repr
2024-05-28 23:27:17 +01:00
try:
let res = verifyCircuit(proof.unsafeAddr, inputs, self.vkp)
if res == ERR_OK:
result = true
elif res == ERR_FAILED_TO_VERIFY_PROOF:
result = false
else:
raise newException(ValueError, "Failed to verify proof - err code: " & $res)
echo "proof verification result: ", result
finally:
release_inputs(inputs.addr)
2024-05-10 22:38:35 +03:00
2024-05-10 16:12:34 +03:00
proc printHelp() =
echo "usage:"
2024-05-10 22:38:35 +03:00
echo " ./circom_ark_prover_cli [options] "
2024-05-10 16:12:34 +03:00
echo ""
echo "available options:"
echo " -h, --help : print this help"
echo " -v, --verbose : verbose output (print the actual parameters)"
2024-05-24 15:49:56 +03:00
echo " --r1cs:$FILE : r1cs file path"
echo " --wasm:$FILE : wasm file path"
echo " --zkey:$FILE : zkey file path"
echo " --inputs:$FILE : inputs.json file path"
2024-05-10 16:12:34 +03:00
echo ""
echo "Must provide files options. Use either:"
echo " --dir:$CIRCUIT_DIR --name:$CIRCUIT_NAME"
echo "or:"
echo " --r1cs:$R1CS --wasm:$WASM --zkey:$ZKEY"
echo ""
quit(1)
2024-05-27 14:47:24 +01:00
proc parseCliOptions(self: var CircomCircuit) =
2024-05-10 16:12:34 +03:00
var argCtr: int = 0
template expectPath(val: string): string =
if val == "":
echo "ERROR: expected path a but got empty for: ", key
printHelp()
val.absolutePath
2024-05-28 15:39:17 +01:00
let params =
@[
"--dir:benchmarks/circuit_bench_depth32_maxslots256_cellsize2048_blocksize65536_nsamples1_entropy1234567_seed12345_nslots11_ncells512_index3/",
"--name:proof_main"
]
2024-05-27 14:47:24 +01:00
for kind, key, value in getOpt(params):
2024-05-10 16:12:34 +03:00
case kind
# Positional arguments
of cmdArgument:
echo "\nERROR: got unexpected arg: ", key, "\n"
printHelp()
# Switches
of cmdLongOption, cmdShortOption:
case key
of "h", "help":
printHelp()
of "r1cs":
2024-05-24 15:23:09 +03:00
self.r1csPath = value.expectPath()
2024-05-10 16:12:34 +03:00
of "wasm":
2024-05-24 15:23:09 +03:00
self.wasmPath = value.expectPath()
2024-05-10 16:12:34 +03:00
of "zkey":
2024-05-24 15:23:09 +03:00
self.zkeyPath = value.expectPath()
2024-05-10 16:12:34 +03:00
of "inputs":
2024-05-24 15:23:09 +03:00
self.inputsPath = value.expectPath()
2024-05-10 16:12:34 +03:00
of "dir":
2024-05-24 15:23:09 +03:00
self.dir = value.expectPath()
2024-05-10 16:12:34 +03:00
of "name":
2024-05-24 15:23:09 +03:00
self.circName = value
2024-05-10 16:12:34 +03:00
else:
echo "Unknown option: ", key
echo "use --help to get a list of options"
quit()
of cmdEnd:
discard
proc run*() =
## Run Codex Ark/Circom based prover
##
echo "Running prover"
# prove wasm ${CIRCUIT_MAIN}.zkey witness.wtns proof.json public.json
2024-05-28 15:39:17 +01:00
var self = CircomCircuit()
2024-05-10 16:12:34 +03:00
2024-05-27 14:47:24 +01:00
parseCliOptions(self)
2024-05-10 16:12:34 +03:00
let dir =
2024-05-24 15:23:09 +03:00
if self.dir != "":
self.dir
2024-05-10 16:12:34 +03:00
else:
getCurrentDir()
2024-05-24 15:23:09 +03:00
if self.circName != "":
if self.r1csPath == "":
self.r1csPath = dir / fmt"{self.circName}.r1cs"
if self.wasmPath == "":
self.wasmPath = dir / fmt"{self.circName}.wasm"
if self.zkeyPath == "":
self.zkeyPath = dir / fmt"{self.circName}.zkey"
2024-05-10 16:12:34 +03:00
2024-05-24 15:23:09 +03:00
if self.inputsPath == "":
self.inputsPath = dir / fmt"input.json"
2024-05-10 16:12:34 +03:00
2024-05-24 15:23:09 +03:00
echo "Got file args: ", self
2024-05-10 16:12:34 +03:00
var fileErrors = false
template checkFile(file, name: untyped) =
if file == "" or not file.fileExists():
echo "\nERROR: must provide `" & name & "` file"
fileErrors = true
2024-05-24 15:23:09 +03:00
checkFile self.inputsPath, "inputs.json"
checkFile self.r1csPath, "r1cs"
checkFile self.wasmPath, "wasm"
checkFile self.zkeyPath, "zkey"
2024-05-10 16:12:34 +03:00
if fileErrors:
echo "ERROR: couldn't find all files"
printHelp()
2024-05-28 15:39:17 +01:00
self.initialize()
2024-05-10 16:12:34 +03:00
var
2024-05-24 15:23:09 +03:00
inputData = self.inputsPath.readFile()
2024-05-10 16:12:34 +03:00
inputs: JsonNode = !JsonNode.parse(inputData)
2024-05-28 15:39:17 +01:00
2024-05-28 23:30:16 +01:00
var ctx = initCircomCtx(self, inputs)
defer:
if ctx != nil:
ctx.addr.releaseCircomCompat()
let proof = prove(self, ctx)
let verified = verify(self, ctx, proof)
2024-05-10 16:12:34 +03:00
when isMainModule:
run()