Skip to content

Commit

Permalink
ios snark impl success
Browse files Browse the repository at this point in the history
  • Loading branch information
kyoungbinkim committed Feb 6, 2023
1 parent ede9ab4 commit dd9ad3c
Show file tree
Hide file tree
Showing 12 changed files with 253 additions and 6 deletions.
2 changes: 2 additions & 0 deletions ios/LibsnarkModule.m
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ @interface RCT_EXTERN_MODULE(LibsnarkModule, NSObject)

RCT_EXTERN_METHOD(createCircuitContext:(NSString *)circuitName treeHeight:(NSString *)treeHeight hashType:(NSString *)hashType serializeFormat:(NSInteger)serializeFormat ecSelection:(NSInteger)ecSelection resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(createGenTradeCircuitContext:(NSString *)circuitName serializeFormat:(NSInteger)serializeFormat ecSelection:(NSInteger)ecSelection resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(buildCircuit:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)

RCT_EXTERN_METHOD(runSetup:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Expand Down
20 changes: 19 additions & 1 deletion ios/LibsnarkModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class LibsnarkModule: NSObject {
public static let EC_BLS12_381 : Int32 = 2

private var context_id : Int32 = 0
private var context_id_map: [String: Int32] = ["ZKlay": 0, "ZKlay_nft": 0];
private var context_id_map: [String: Int32] = ["ZKlay": 0, "ZKlay_nft": 0, "GenTrade":0];
var contextID : Int { get { return Int(context_id) } }

@objc(getContextId:resolver:rejecter:)
Expand Down Expand Up @@ -83,6 +83,24 @@ class LibsnarkModule: NSObject {
resolve(resolveData)
}

@objc(createGenTradeCircuitContext:serializeFormat:ecSelection:resolver:rejecter:)
func createGenTradeCircuitContext(_ circuitName: String, serializeFormat: Int32 = serializeFormatZKlay, ecSelection: Int32 = EC_ALT_BN128, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
let _circuitName = CString(circuitName)
let contextId: Int32 = CSnark.createCircuitContext(_circuitName.char(),
R1CS_GG,
ecSelection,
CString("").char(),
CString("").char(),
CString("").char())
context_id_map[circuitName] = contextId;
context_id = contextId;

CSnark.serializeFormat(contextId , serializeFormat )

let resolveData: [String: String] = ["circuitName": circuitName, "contextId": "\(contextId)"]
resolve(resolveData)
}

@objc(buildCircuit:rejecter:)
func buildCircuit(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) -> Void {
let rtn = CSnark.buildCircuit(context_id)
Expand Down
4 changes: 2 additions & 2 deletions ios/dataTradeApp.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
3B6E8A2C298CB9B800BB4A23 /* libomp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B6E8A24298CB9AF00BB4A23 /* libomp.a */; };
3B6E8A2D298CB9B800BB4A23 /* libssl.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B6E8A26298CB9AF00BB4A23 /* libssl.a */; };
3B6E8A2E298CB9D300BB4A23 /* libgmpxx.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 3B6E8A28298CB9B000BB4A23 /* libgmpxx.a */; };
3BA6CED62990D6820062EE86 /* crs in Resources */ = {isa = PBXBuildFile; fileRef = 3BE3666E29882E4500A702E3 /* crs */; };
3BB244B82988EC9900EFD587 /* libPods-dataTradeApp-dataTradeAppTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-dataTradeApp-dataTradeAppTests.a */; };
3BB244BA2988EED800EFD587 /* zkSnark in Frameworks */ = {isa = PBXBuildFile; productRef = 3BB244B92988EED800EFD587 /* zkSnark */; };
3BC88AAE298B59C00097527D /* LibsnarkModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BE3666829882DA700A702E3 /* LibsnarkModule.swift */; };
3BE3666929882DA700A702E3 /* LibsnarkModule.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3BE3666829882DA700A702E3 /* LibsnarkModule.swift */; };
3BE3666C29882DD200A702E3 /* LibsnarkModule.m in Sources */ = {isa = PBXBuildFile; fileRef = 3BE3666A29882DD200A702E3 /* LibsnarkModule.m */; };
3BE36671298844C500A702E3 /* dataTradeApp.app in Resources */ = {isa = PBXBuildFile; fileRef = 13B07F961A680F5B00A75B9A /* dataTradeApp.app */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */

Expand Down Expand Up @@ -297,8 +297,8 @@
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
3BA6CED62990D6820062EE86 /* crs in Resources */,
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
3BE36671298844C500A702E3 /* dataTradeApp.app in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
Expand Down
26 changes: 26 additions & 0 deletions shim.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
if (typeof __dirname === 'undefined') global.__dirname = '/'
if (typeof __filename === 'undefined') global.__filename = ''
if (typeof process === 'undefined') {
global.process = require('process')
} else {
const bProcess = require('process')
for (var p in bProcess) {
if (!(p in process)) {
process[p] = bProcess[p]
}
}
}

process.browser = false
if (typeof Buffer === 'undefined') global.Buffer = require('buffer').Buffer

// global.location = global.location || { port: 80 }
const isDev = typeof __DEV__ === 'boolean' && __DEV__
process.env['NODE_ENV'] = isDev ? 'development' : 'production'
if (typeof localStorage !== 'undefined') {
localStorage.debug = isDev ? '*' : ''
}

// If using the crypto shim, uncomment the following line to ensure
// crypto is loaded first, so it can populate global.crypto
// require('crypto')
9 changes: 9 additions & 0 deletions src/components/init.page.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { StyleSheet, View } from 'react-native';
import { Text, Icon, Button } from 'react-native-elements';
import CustomChipButton from '../elements/chipButton';

import testSnark from '../core/snark/test';

const InitWalletPage = ({ navigation }) => {

useLayoutEffect(() => {
Expand All @@ -25,6 +27,13 @@ const InitWalletPage = ({ navigation }) => {
containerStyle={[styles.containerBt]}
onPress={() => {navigation.navigate('Login') }}
/>
<CustomChipButton
title={'snarkTest'}
containerStyle={[styles.containerBt]}
onPress={() => {
testSnark();
}}
/>

</View>
)
Expand Down
1 change: 1 addition & 0 deletions src/components/page.home.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ const PageHome = ({navigation}) => {
dispatch(setData(data));
}}
/>

</View>
)
}
Expand Down
6 changes: 4 additions & 2 deletions src/core/snark/bridge/libsnark.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export default class Libsnark {
* @param {string} hashType
* @param {string} serializeFormat
*/
constructor(circuitName, treeHeight = '32', hashType = 'MiMC7', serializeFormat = 'SERIALIZE_FORMAT_ZKLAY') {
constructor(circuitName='GenTrade', treeHeight = '32', hashType = 'MiMC7', serializeFormat = 'SERIALIZE_FORMAT_ZKLAY') {
this.circuitName = circuitName;
this.treeHeight = treeHeight;
this.hashType = hashType;
Expand All @@ -38,7 +38,9 @@ export default class Libsnark {
console.debug('[LIBSNARK] finalizeCircuit !', this.contextId);
await modules.finalizeCircuit(this.contextId);
}
const resolveDataCreateCircuitContext = await modules.createCircuitContext(this.circuitName, this.treeHeight, this.hashType, this.serializeFormat, this.ecSelection);
const resolveDataCreateCircuitContext = await modules.createCircuitContext(this.circuitName, this.serializeFormat, this.ecSelection);
// const resolveDataCreateCircuitContext = await modules.createGenTradeCircuitContext(this.circuitName, this.serializeFormat, this.ecSelection);

this.contextId = Number(_.get(resolveDataCreateCircuitContext, 'contextId'));
console.debug('[LIBSNARK] createCircuitContext !', resolveDataCreateCircuitContext);
const resolveDataBuildCircuit = await modules.buildCircuit();
Expand Down
2 changes: 1 addition & 1 deletion src/core/snark/bridge/modules.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ async function createCircuitContext(circuitName, treeHeight='', hashType='', ser
if (typeof ecSelection === 'string') {
ecSelection = EC_SELECTION[ecSelection];
}
return LibsnarkModule.createCircuitContext(circuitName, treeHeight, hashType, serializeFormat, ecSelection);
return LibsnarkModule.createGenTradeCircuitContext(circuitName, serializeFormat, ecSelection);
}

async function buildCircuit() {
Expand Down
61 changes: 61 additions & 0 deletions src/core/snark/struct/cm.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// import crypto from 'crypto';

import Config from '../../utils/config';
import CurveParam from '../../crypto/curveParam';
import types from "../../utils/types";
import mimc from "../../crypto/mimc";


export default class CoinCommitment {
constructor(
cm_own = undefined,
cm_del = undefined
) {
this.cm_own = cm_own
this.cm_del = cm_del
}

static makeCm({
pk_own_peer,
pk_own_del,
pk_enc_cons,
r_cm,
fee_own,
fee_del,
h_k
}) {
const mimc7 = new mimc.MiMC7();

const cm_own = mimc7.hash(pk_own_peer, r_cm, fee_own, h_k, pk_enc_cons);
const cm_del = mimc7.hash(pk_own_del, r_cm, fee_del, h_k, pk_enc_cons);

return new CoinCommitment(cm_own, cm_del);
}

static genCm({
pk_own_peer,
pk_own_del,
pk_enc_cons,
fee_own,
fee_del,
h_k,
}) {
let prime = CurveParam(Config.EC_TYPE).prime
let bitLength = parseInt(prime.toString(2).length);
// let randomHex = '0x' + crypto.randomBytes(bitLength).toString('hex');
let randomHex = '0x1122ffffffff'
return this.makeCm({
pk_own_peer : pk_own_peer,
pk_own_del : pk_own_del,
pk_enc_cons : pk_enc_cons,
r_cm : randomHex,
fee_own : fee_own,
fee_del : fee_del,
h_k : h_k,
})
}

toJson(){
return JSON.stringify(this, null, 2);
}
}
47 changes: 47 additions & 0 deletions src/core/snark/struct/order.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import _ from 'lodash'
import CoinCommitment from "./cm"

const fee_ratio = 0.3

export default class Order {

pk_enc_cons = undefined
pk_own_cons = undefined
r_cm = undefined
fee_del = undefined
fee_own = undefined
h_k = undefined

constructor(
pk_enc_cons = undefined,
pk_own_cons = undefined,
r_cm = undefined,
fee_del = undefined,
fee_own = undefined,
h_k = undefined
){
this.pk_own_cons = pk_own_cons
this.pk_enc_cons = pk_enc_cons
this.r_cm = r_cm
this.fee_del = fee_del
this.fee_own = fee_own
this.h_k = h_k
}

toJson(){
return JSON.stringify(this, null, 2);
}


makeCoinCommitment(pk_own_peer, pk_own_del) {
const cmInfo = _.merge(
JSON.parse(this.toJson()),
{
'pk_own_peer' : pk_own_peer,
'pk_own_del' : pk_own_del
}
)
console.log(cmInfo);
return CoinCommitment.makeCm(cmInfo)
}
}
23 changes: 23 additions & 0 deletions src/core/snark/struct/pk.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@


export default class PublicKey{
type = undefined
pk_enc = undefined
pk_own = undefined

constructor(pk_own='', pk_enc='', type=''){
this.type = type
this.pk_enc = pk_enc
this.pk_own = pk_own
}

toJson() {
const pk_own_type = `pk_own_${this.type}`
const pk_enc_type = `pk_enc_${this.type}`
let pk = {}
pk[pk_own_type] = this.pk_own
pk[pk_enc_type] = this.pk_enc

return JSON.stringify(pk, null, 2)
}
}
58 changes: 58 additions & 0 deletions src/core/snark/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import _ from 'lodash'

import Libsnark from "./bridge/libsnark"
import Order from "./struct/order"
import SnarkInput from "./struct/snarkInput";

const testSnark = async () => {
let snarkClass = new Libsnark();

await snarkClass.init();

await snarkClass.readVerifyKeyFromFile('/crs/');
await snarkClass.readProofKeyFromFile('/crs/');

const sampleInput = {
"g_r" : "137",
"c1" : "123",
"cm_own" : "123",
"cm_del" : "123",
"ENA" : ["123", "233"],
"ENA_" :["112", "233"],
"fee_del" : "321",
"fee_own" : "123",
"CT_cons" : ["12","22","32","42","52","62"],
"CT_r" : "123"
}

const proof = await snarkClass.runProof(sampleInput);
console.log(proof);

const vf = await snarkClass.runVerify(proof, sampleInput);
console.log('vf:', vf);

}

export const testOrder = () => {

console.log("hi" , Number.parseInt(100 * 0.3))

const ord = new Order(
1,
1,
1,
1,
1,
1
)
console.log(ord.toJson());
const cm = ord.makeCoinCommitment(1, 1);
console.log(cm.toJson());

const snarkInputs = new SnarkInput();
snarkInputs.uploadOrder(ord);

console.log(snarkInputs.toJson())
}

export default testSnark;

0 comments on commit dd9ad3c

Please sign in to comment.