Skip to content

Commit

Permalink
validate key using the serialize function
Browse files Browse the repository at this point in the history
  • Loading branch information
yuetloo committed May 10, 2024
1 parent e78fc12 commit 6bbd012
Showing 1 changed file with 19 additions and 22 deletions.
41 changes: 19 additions & 22 deletions common/src/keypair.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,34 @@
import { keccak256, isBytesLike, concat, toBeArray } from 'ethers'
import { Keypair as MaciKeypair, PrivKey, PubKey } from 'maci-domainobjs'

const SNARK_FIELD_SIZE = BigInt(
'21888242871839275222246405745257275088548364400416034343698204186575808495617'
)

/**
* Returns a BabyJub-compatible value. This function is modified from
* the MACI's genRandomBabyJubValue(). Instead of returning random value
* for the private key, it derives the private key from the users
* signature hash
* Derives the MACI private key from the users signature hash
* @param hash - user's signature hash
* @return The MACI private key
*/
function genPrivKey(hash: string): PrivKey {
// Prevent modulo bias
//const lim = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000')
//const min = (lim - SNARK_FIELD_SIZE) % SNARK_FIELD_SIZE
const min = BigInt(
'6350874878119819312338956282401532410528162663560392320966563075034087161851'
)

if (!isBytesLike(hash)) {
throw new Error(`Hash must be a hex string: ${hash}`)
throw new Error(`genPrivKey() error. Hash must be a hex string: ${hash}`)
}

let hashBN = BigInt(hash)
// don't think we'll enter the for loop below, but, just in case
for (let counter = 1; hashBN < min; counter++) {
const data = concat([toBeArray(hashBN), toBeArray(counter)])
hashBN = BigInt(keccak256(data))
let rawPrivKey = BigInt(hash)
let pubKey: PubKey | null = null

for (let counter = 1; pubKey === null; counter++) {
try {
const privKey = new PrivKey(rawPrivKey)
const keypair = new Keypair(privKey)

// this will throw 'Invalid public key' if key is not on the Baby Jubjub elliptic curve
keypair.pubKey.serialize()

pubKey = keypair.pubKey
} catch {
const data = concat([toBeArray(rawPrivKey), toBeArray(counter)])
rawPrivKey = BigInt(keccak256(data))
}
}

const rawPrivKey = hashBN % SNARK_FIELD_SIZE
return new PrivKey(rawPrivKey)
}

Expand Down

0 comments on commit 6bbd012

Please sign in to comment.