Skip to content

Commit

Permalink
Merge pull request #237 from EYBlockchain/swati/SharedSecret
Browse files Browse the repository at this point in the history
shared secret
  • Loading branch information
SwatiEY authored Jun 19, 2024
2 parents 173eebc + 6f4dbed commit 1823daf
Show file tree
Hide file tree
Showing 21 changed files with 392 additions and 158 deletions.
15 changes: 8 additions & 7 deletions circuits/common/joinCommitments.zok
Original file line number Diff line number Diff line change
Expand Up @@ -93,18 +93,17 @@ def main(\
assert(\
field_to_bool_256(oldCommitment_0_nullifier)[8..256] == field_to_bool_256(oldCommitment_0_nullifier_check_field)[8..256]\
)
assert(\

assert(\
nullifierRoot == checkproof(\
oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\
oldCommitment_0_nullifier\
) )

assert( newNullifierRoot == checkUpdatedPath(oldCommitment_0_nullifier_nonmembershipWitness_newsiblingPath,\
assert( newNullifierRoot == checkUpdatedPath(\
oldCommitment_0_nullifier_nonmembershipWitness_newsiblingPath,\
oldCommitment_0_nullifier) )





// Nullify oldCommitment_1:

Expand All @@ -124,9 +123,11 @@ def main(\
oldCommitment_1_nullifier\
) )

assert( newNullifierRoot == checkUpdatedPath(oldCommitment_1_nullifier_nonmembershipWitness_newsiblingPath,\
assert( newNullifierRoot == checkUpdatedPath(\
oldCommitment_1_nullifier_nonmembershipWitness_newsiblingPath,\
oldCommitment_1_nullifier) )


// oldCommitment_0_commitment: preimage check

field oldCommitment_0_commitment_field = poseidon([\
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ class BoilerplateGenerator {
isPartitioned?: boolean;
isNullified?: boolean;
isAccessed?: boolean;
reinitialisable?: boolean;
initialisationRequired?: boolean;
newCommitmentsRequired?: boolean;
encryptionRequired?: boolean;
Expand All @@ -113,12 +114,12 @@ class BoilerplateGenerator {
mappingName: string;
indicators: any;
newCommitmentValue: any;
containsAccessedOnlyStates: boolean


bpSections: string[] = ['importStatements', 'parameters', 'preStatements', 'postStatements'];

constructor(indicators: StateVariableIndicator) {

// Through prior traversals, a BoilerplateGenerator class for this set of indicators might already be stored in memory:
if (bpCache.has(indicators)) return bpCache.get(indicators);

Expand All @@ -141,6 +142,7 @@ class BoilerplateGenerator {
isPartitioned,
isNullified,
isAccessed,
reinitialisable,
newCommitmentsRequired,
isMapping,
isStruct,
Expand All @@ -155,6 +157,7 @@ class BoilerplateGenerator {
isPartitioned,
isNullified,
isAccessed,
reinitialisable,
newCommitmentsRequired,
isMapping,
isStruct,
Expand Down Expand Up @@ -264,6 +267,7 @@ class BoilerplateGenerator {
...(this.typeName && { typeName: this.typeName}),
...(this.mappingKeyName && { mappingKeyTypeName: this.mappingKeyTypeName }),
...(this.isAccessed && { isAccessed: this.isAccessed }),
...(this.reinitialisable && { reinitialisable: this.reinitialisable }),
...(this.initialisationRequired && { initialisationRequired: this.initialisationRequired }),
...(this.newCommitmentValue && { newCommitmentValue: this.newCommitmentValue }),
// ...(this.burnedOnly && { burnedOnly: this.burnedOnly }), // TODO
Expand Down Expand Up @@ -310,6 +314,9 @@ class BoilerplateGenerator {
addBP('oldCommitmentPreimage');
addBP('oldCommitmentExistence');
}
if(this.reinitialisable){
addBP('oldCommitmentPreimage');
}
if (this.newCommitmentsRequired && !this.burnedOnly) {
addBP('newCommitment');
}
Expand Down
12 changes: 8 additions & 4 deletions src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,25 +166,28 @@ class BoilerplateGenerator {
];
},

parameters({ name: x, typeName }): string[] {
parameters({ name: x, typeName, reinitialisable }): string[] {
// prettier-ignore
if(!reinitialisable)
return [
`private ${typeName ? typeName : 'field'} ${x}_oldCommitment_value`,
`private field ${x}_oldCommitment_salt`,
];
},

preStatements({ name: x, typeName }): string[] {
preStatements({ name: x, typeName, reinitialisable }): string[] {
// For a state variable, we'll have passed in `${x}_oldCommitment_value` as a parameter. But our AST nodes will be using `${x}`. This line resolves the two.
if (reinitialisable)
return [ `${typeName ? typeName : 'field'} ${x} = 0`];
return [
`
${typeName ? typeName : 'field'} ${x} = ${x}_oldCommitment_value`,
];
},

postStatements({ name: x, structProperties, structPropertiesTypes, typeName }): string[] {
postStatements({ name: x, structProperties, reinitialisable, structPropertiesTypes, typeName }): string[] {
const lines: string[] = [];
if (!structProperties ) {
if (!structProperties && !reinitialisable ) {
if (typeName === 'bool'){
lines.push(`field ${x}_oldCommitment_value_field = if ${x}_oldCommitment_value then 1 else 0 fi`);
} else {
Expand Down Expand Up @@ -216,6 +219,7 @@ class BoilerplateGenerator {
])`,
];
}
if(!reinitialisable)
return [

`
Expand Down
4 changes: 4 additions & 0 deletions src/boilerplate/common/bin/setup
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ cp docker-compose.zapp.override.default.yml docker-compose.zapp.override.yml

cp entrypoint_default.sh entrypoint.sh



rm -rf proving-files

perl -i -pe "s,docker-compose.zapp.yml -f docker-compose.zapp.override.yml,docker-compose.zapp.yml,g" package.json

if [[ $network == 'mumbai' ]] || [[ $network == 'sepolia' ]] || [[ $network == 'goerli' ]]
Expand Down
98 changes: 71 additions & 27 deletions src/boilerplate/common/commitment-storage.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,22 @@
Logic for storing and retrieving commitments from a mongo DB.
*/
import config from 'config';
import fs from 'fs';
import gen from 'general-number';
import mongo from './mongo.mjs';
import logger from './logger.mjs';
import utils from 'zkp-utils';
import { poseidonHash } from './number-theory.mjs';
import { sharedSecretKey } from './number-theory.mjs';
import { generateProof } from './zokrates.mjs';
import { SumType, reduceTree, toBinArray, poseidonConcatHash } from './smt_utils.mjs';
import { SumType, reduceTree, toBinArray, poseidonConcatHash,} from './smt_utils.mjs';
import { hlt } from './hash-lookup.mjs';
import fs from "fs";

const { MONGO_URL, COMMITMENTS_DB, COMMITMENTS_COLLECTION } = config;
const { generalise } = gen;

const keyDb = '/app/orchestration/common/db/key.json';

const TRUNC_LENGTH = 32; // Just for testing so we don't make more than 32 deep smt trees.
const WHOLE_STATES = [WHOLE_STATE_NAMES];
// structure for SMT
Expand Down Expand Up @@ -121,18 +124,18 @@ export async function getNullifiedCommitments() {
* @returns {Promise<number>} The sum of the values ​​of all non-nullified commitments
*/
export async function getBalance() {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const commitments = await db
.collection(COMMITMENTS_COLLECTION)
.find({ isNullified: false }) // no nullified
.toArray();
let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += parseInt(commitment.preimage.value, 10);
});
return sumOfValues;
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const commitments = await db
.collection(COMMITMENTS_COLLECTION)
.find({ isNullified: false }) // no nullified
.toArray();

let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += parseInt(commitment.preimage.value, 10);
});
return sumOfValues;
}

export async function getBalanceByState(name, mappingKey = null) {
Expand All @@ -144,23 +147,27 @@ export async function getBalanceByState(name, mappingKey = null) {
.collection(COMMITMENTS_COLLECTION)
.find(query)
.toArray();
let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += commitment.isNullified ? 0 : parseInt(commitment.preimage.value, 10);
});
let sumOfValues = 0;
commitments.forEach(commitment => {
sumOfValues += commitment.isNullified
? 0
: parseInt(commitment.preimage.value, 10);
});
return sumOfValues;
}

/**
* @returns all the commitments existent in this database.
*/
export async function getAllCommitments() {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const allCommitments = await db.collection(COMMITMENTS_COLLECTION).find().toArray();
return allCommitments;
}

export async function getAllCommitments() {
const connection = await mongo.connection(MONGO_URL);
const db = connection.db(COMMITMENTS_DB);
const allCommitments = await db
.collection(COMMITMENTS_COLLECTION)
.find()
.toArray();
return allCommitments;
}

// function to update an existing commitment
export async function updateCommitment(commitment, updates) {
Expand Down Expand Up @@ -679,7 +686,7 @@ export async function splitCommitments(

// Call Zokrates to generate the proof:
const allInputs = [
value.integer,
value.integer,
fromID,
stateVarID,
isMapping,
Expand Down Expand Up @@ -902,4 +909,41 @@ export async function addConstructorNullifiers() {
);

}
}
}
export async function getSharedSecretskeys(
_recipientAddress,
_recipientPublicKey = 0,
) {
const keys = JSON.parse(
fs.readFileSync(keyDb, 'utf-8', err => {
console.log(err);
}),
);
const secretKey = generalise(keys.secretKey);
const publicKey = generalise(keys.publicKey);
let recipientPublicKey = generalise(_recipientPublicKey);
const recipientAddress = generalise(_recipientAddress);
if (_recipientPublicKey === 0) {
recipientPublicKey = await this.instance.methods
.zkpPublicKeys(recipientAddress.hex(20))
.call();
recipientPublicKey = generalise(recipientPublicKey);

if (recipientPublicKey.length === 0) {
throw new Error('WARNING: Public key for given eth address not found.');
}
}

const sharedKey = sharedSecretKey(secretKey, recipientPublicKey);
console.log('sharedKey:', sharedKey);
console.log('sharedKey:', sharedKey[1]);
const keyJson = {
secretKey: secretKey.integer,
publicKey: publicKey.integer,
sharedSecretKey: sharedKey[0].integer,
sharedPublicKey: sharedKey[1].integer, // not req
};
fs.writeFileSync(keyDb, JSON.stringify(keyJson, null, 4));

return sharedKey[1];
}
Empty file.
38 changes: 38 additions & 0 deletions src/boilerplate/common/number-theory.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,43 @@ function decrypt(encryptedMessages, secretKey, encPublicKey) {
return plainText;
}


/**
@param {string} secretKey - hex string
@param {string[2]} recipientPublicKey - hex string[]
@return {string} key - int string
*/
function sharedSecretKey(secretKey, recipientPublicKey) {
const publickKeyPoint = decompressStarlightKey(recipientPublicKey);
const sharedSecret = scalarMult(secretKey.hex(32), [
BigInt(generalise(publickKeyPoint[0]).hex(32)),
BigInt(generalise(publickKeyPoint[1]).hex(32)),
]);
const key = poseidonHash([
sharedSecret[0],
sharedSecret[1],
BigInt(DOMAIN_KEM),
]);

let sharePublicKeyPoint = generalise(
scalarMult(key.hex(32), config.BABYJUBJUB.GENERATOR)
);

let yBits = sharePublicKeyPoint[1].binary;
if (yBits.length > 253)
{
yBits = yBits.slice(yBits.length - 253);
}

const xBits = sharePublicKeyPoint[0].binary;
const sign = xBits[xBits.length - 1];

let sharedPublicKey = new GN(sign + yBits.padStart(253, "0"), "binary");


return [key, sharedPublicKey];
}

// Implements the Poseidon hash, drawing on the ZoKrates implementation
// roundsP values referred from circom library
// https://github.com/iden3/circomlibjs/blob/main/src/poseidon_opt.js
Expand Down Expand Up @@ -386,4 +423,5 @@ export {
decompressStarlightKey,
decrypt,
poseidonHash,
sharedSecretKey,
};
Loading

0 comments on commit 1823daf

Please sign in to comment.