How to use snarkjs - 10 common examples

To help you get started, we’ve selected a few snarkjs examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github barryWhiteHat / maci / test / testMerkleTree.js View on Github external
before('Setup Hasher Library', async () => {
    hasherContract = await hasherFactory.deploy()

    // Load circuits
    mtInsertCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeInsert_test.circom'))
    )

    mtLeafExistsCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeLeafExists_test.circom'))
    )

    mtCheckRootCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeCheckRoot_test.circom'))
    )
  })
github barryWhiteHat / maci / test / testMACILogic.js View on Github external
// Submits it to the smart contract
      cmdTree.insert(user2NewLeaf, user2NewMessage)

      // Construct circuit inputs
      const [cmdTreePathElements, cmdTreePathIndex] = cmdTree.getPathUpdate(cmdTree.nextIndex - 1)

      // 1st index because we're getting user 2
      const [stateTreePathElements, stateTreePathIndex] = stateTree.getPathUpdate(1)

      const ecdhPrivateKey = ecdh(
        user2NewSecretKey,
        coordinatorPublicKey
      )

      const circuit = new Circuit(updateStateTreeCircuitDef)

      const circuitInput = {
        cmd_tree_root: stringifyBigInts(cmdTree.root),
        cmd_tree_path_elements: stringifyBigInts(cmdTreePathElements),
        cmd_tree_path_index: stringifyBigInts(cmdTreePathIndex),
        state_tree_root: stringifyBigInts(stateTree.root),
        state_tree_path_elements: stringifyBigInts(stateTreePathElements),
        state_tree_path_index: stringifyBigInts(stateTreePathIndex),
        encrypted_data: stringifyBigInts(user2NewEncryptedMsg),
        existing_public_key: stringifyBigInts(user2PublicKey),
        existing_state_tree_leaf: stringifyBigInts(user2Leaf),
        ecdh_private_key: stringifyBigInts(ecdhPrivateKey)
      }

      const witness = circuit.calculateWitness(circuitInput)
      assert(circuit.checkWitness(witness))
github barryWhiteHat / maci / test / testMerkleTree.js View on Github external
before('Setup Hasher Library', async () => {
    hasherContract = await hasherFactory.deploy()

    // Load circuits
    mtInsertCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeInsert_test.circom'))
    )

    mtLeafExistsCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeLeafExists_test.circom'))
    )

    mtCheckRootCircuit = new Circuit(
      await compiler(path.join(__dirname, '../test/merkleTreeCheckRoot_test.circom'))
    )
  })
github eddieoz / haal / test / vote_zk.js View on Github external
it("Verify proof-of-vote", () => {
        // Verify the proof
        const vk_verifier = setup.vk_verifier;
        assert.isTrue(zkSnark.original.isValid(vk_verifier, proof.proof, proof.publicSignals));
    }).timeout(10000000);
});
github eddieoz / haal / test / vote_zk.js View on Github external
it("Create a trusted setup", () => {
        // Trusted setup
        setup = zkSnark.original.setup(circuit);
        setup.toxic  // Must be discarded.
        assert.equal(setup.vk_verifier.nPublic, 7);
    }).timeout(10000000);
github weijiekoh / zkmm / mastermind / src / trustedsetup.ts View on Github external
console.error(input, 'does not exist')
        return
    }

    // Run the trusted setup process if the output keyfiles don't exist, or the
    // user wants to overwrite them
    if (overwrite || !existsSync(provingKeyOutput) || !existsSync(verifyingKeyOutput)) {
        try {
            // Load the circuit
            const circuitDef = JSON.parse(
                readFileSync(input, 'utf8')
            )
            const circuit = new snarkjs.Circuit(circuitDef);

            // Perform the setup
            const setup = snarkjs.groth.setup(circuit);

            // Save the keys
            const provingKey = setup.vk_proof
            const verifyingKey = setup.vk_verifier

            writeFileSync(
                provingKeyOutput,
                JSON.stringify(stringifyBigInts(provingKey)),
                'utf8'
            )

            writeFileSync(
                verifyingKeyOutput,
                JSON.stringify(stringifyBigInts(verifyingKey)),
                'utf8'
            )
github weijiekoh / zkmm / mastermind / src / old.ts View on Github external
pubGuessC: testCase.guess[2],
            pubGuessD: testCase.guess[3],
            privSolnA: testCase.soln[0],
            privSolnB: testCase.soln[1],
            privSolnC: testCase.soln[2],
            privSolnD: testCase.soln[3],
        }

        try {
            console.log('The codemaster calculates the witness')
            const witness = circuit.calculateWitness(testInput)

            console.log('The codemaster generates a proof', new Date())

            // Codemaster generates the proof and public signals
            const { proof, publicSignals } = snarkjs.genProof(provingKey, witness);

            // Save to file
            writeFileSync(
                PROOF_AND_SIGNALS_DIR + '/' + i.toString() + '.json',
                JSON.stringify(
                    stringifyBigInts({ proof, publicSignals }),
                ),
                'utf8'
            )

            console.log('Verifying proof', new Date())
            const isValid: boolean = snarkjs.isValid(verifyingKey, proof, publicSignals)

            if (!isValid) {
                throw new Error('Invalid proof')
            } else {
github weijiekoh / zkmm / mastermind / src / old.ts View on Github external
console.log('The codemaster generates a proof', new Date())

            // Codemaster generates the proof and public signals
            const { proof, publicSignals } = snarkjs.genProof(provingKey, witness);

            // Save to file
            writeFileSync(
                PROOF_AND_SIGNALS_DIR + '/' + i.toString() + '.json',
                JSON.stringify(
                    stringifyBigInts({ proof, publicSignals }),
                ),
                'utf8'
            )

            console.log('Verifying proof', new Date())
            const isValid: boolean = snarkjs.isValid(verifyingKey, proof, publicSignals)

            if (!isValid) {
                throw new Error('Invalid proof')
            } else {
                console.log('Valid proof')
            }

            console.log('correctNumBlacks calculated by circuit:', witness[circuit.getSignalIdx('main.correctNumBlacks')])
            console.log('correctNumWhites calculated by circuit:', witness[circuit.getSignalIdx('main.correctNumWhites')])
            console.log('Hash calculated by JS     :', testInput.pubSolnHash)
            console.log('Hash calculated by circuit:', witness[circuit.getSignalIdx('main.solnHashOut')])
        } catch (e) {
            console.log(e)
        }

        i++
github weijiekoh / zkmm / mastermind / src / old.ts View on Github external
console.log('Reusing', SETUP_FILEPATH)
            // The override flag isn't present and the setup exists, so read it
            setup = unstringifyBigInts(
                JSON.parse(
                    readFileSync(
                        SETUP_FILEPATH, 
                        'utf8'
                    )
                )
            )
            provingKey = setup.provingKey
            verifyingKey = setup.verifyingKey
        } else {
            // The override flag is present, so generate the setup
            console.log('Generating setup', SETUP_FILEPATH)
            setup = snarkjs.setup(circuit);
            provingKey = setup.vk_proof
            verifyingKey = setup.vk_verifier

            writeFileSync(
                SETUP_FILEPATH,
                JSON.stringify(
                    stringifyBigInts({
                        provingKey,
                        verifyingKey
                    })
                ),
                'utf8'
            )
        }
    } catch (err) {
        console.log('Error with the trusted setup')
github barryWhiteHat / maci / app / utils / crypto.js View on Github external
const sign = (prv: BigInt, _msg: BigInt): { R8: BigInt, S: BigInt } => {
  // Doing this as bigInt2Buffer requires a custom
  // methods 'greater' than isn't in the standard bigint
  // object (its a snarkjs custom bigint obj method)
  const msg = bigInt(_msg)

  const h1 = bigInt2Buffer(hash(prv))
  const sBuff = eddsa.pruneBuffer(h1.slice(0, 32))
  const s = bigInt.leBuff2int(sBuff)
  const A = babyJub.mulPointEscalar(babyJub.Base8, s.shr(3))

  const msgBuff = bigInt.leInt2Buff(
    msg,
    32
  )

  const rBuff = bigInt2Buffer(hash(
    buffer2BigInt(Buffer.concat(
      [h1.slice(32, 64), msgBuff]
    ))
  ))