Skip to content

Commit

Permalink
add grth16
Browse files Browse the repository at this point in the history
  • Loading branch information
Трепачева Алина committed May 6, 2024
1 parent 77c2c16 commit 2f1c7bd
Show file tree
Hide file tree
Showing 4 changed files with 234 additions and 3 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ members = [
"tvm_struct",
"tvm_tl_codegen",
"tvm_types",
"tvm_vm",
"tvm_vm", "vrgrth",
]
[workspace.package]
version = "1.47.0"
Expand Down Expand Up @@ -106,6 +106,9 @@ thiserror = "1.0.56"
tokio = { default-features = false, version = "1.36.0" }
tokio-stream = "0.1.14"
x25519-dalek = "2.0.0"

# fastcrypto-zkp = "0.1.3"
#fastcrypto = "0.1.8"
zstd = "0.13.0"
#
tvm_abi = { path = "./tvm_abi" }
Expand Down
5 changes: 3 additions & 2 deletions tvm_assembler/src/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ impl Engine {
CHKNAN => 0xC5
CHKDEPTH => 0x69
CHKSIGNS => 0xF9, 0x11
VERGRTH16 => 0xF9, 0x12
CHKSIGNU => 0xF9, 0x10
CHKTUPLE => 0x6F, 0x30
CMP => 0xBF
Expand Down Expand Up @@ -839,11 +840,11 @@ impl Engine {
DIFF_PATCH_BINARY_ZIPQ => 0xC7, 0x25
}

#[cfg(feature = "groth")]
/*#[cfg(feature = "groth")]
simple_commands! {
enumerate_groth_commands
VERGRTH16 => 0xF9, 0x12
}
}*/

fn add_commands<'a>(
&mut self,
Expand Down
43 changes: 43 additions & 0 deletions vrgrth/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[package]
name = "vrgrth"
version.workspace = true
rust-version.workspace = true
authors.workspace = true
repository.workspace = true
edition.workspace = true
license.workspace = true

[dependencies]
tvm_block.workspace = true
tvm_types.workspace = true
tvm_assembler.workspace = true
tvm_vm.workspace = true

libloading = '0.6'
log4rs = '1.2'
pprof = { features = [ 'criterion', 'flamegraph' ], version = '0.11' }
pretty_assertions = '1.3'
criterion = '0.4'

im = "15"

ed25519 = '1.2'
ed25519-dalek = '1.0'
anyhow = "1.0.79"
hex = '0.4'
lazy_static = '1.4'
log = '0.4'
num = '0.4'
num-traits = '0.2'
rand = '0.7'
diffy = { optional = true, version = '0.2.2' }
similar = { features = [ 'bytes' ], optional = true, version = '2.2.0' }
zstd = { default-features = false, optional = true, version = '0.11' }
#fastcrypto-zkp = "0.1.3"
fastcrypto = "0.1.8"
ark-std = "0.4.0"

base64ct ={ version = "1.5.3", features = ["alloc"]}

[lints]
workspace = true
184 changes: 184 additions & 0 deletions vrgrth/src/test_zk_.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
/*
* Copyright (C) 2019-2023 TON Labs. All Rights Reserved.
*
* Licensed under the SOFTWARE EVALUATION License (the "License"); you may not use
* this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific TON DEV software governing permissions and
* limitations under the License.
*/

use std::slice;
use ark_std::rand::rngs::StdRng;
use ark_std::rand::SeedableRng;
use base64ct::Encoding as bEncoding;
use fastcrypto::ed25519::Ed25519KeyPair;
use tvm_vm::executor::zk_stuff::utils::{
gen_address_seed
};

use fastcrypto::traits::KeyPair;
use rand::Rng;
//use similar::DiffableStr;
use tvm_block::{
GlobalCapabilities, MsgAddressInt, Serializable, ACTION_CHANGE_LIB, ACTION_COPYLEFT,
ACTION_RESERVE, ACTION_SEND_MSG, ACTION_SET_CODE,
};
use tvm_assembler::compile_code_to_cell;
use tvm_types::{
types::ExceptionCode, AccountId, HashmapE, HashmapType, IBitstring, Result,
Sha256
};

#[cfg(feature = "signature_no_check")]
use ton_vm::executor::BehaviorModifiers;
use tvm_vm::{
boolean,
executor::serialize_currency_collection,
int,
stack::{
integer::{
serialization::{Encoding, UnsignedIntegerBigEndianEncoding},
IntegerData,
},
serialization::{Deserializer, Serializer},
Stack, StackItem,
},
SmartContractInfo,
utils::{pack_string_to_cell, pack_data_to_cell, unpack_string_from_cell},
};


use tvm_assembler::CompileError;
use tvm_types::{BuilderData, Cell, SliceData};
use tvm_vm::executor::zk_stuff::error::ZkCryptoError;
use tvm_vm::executor::zk_stuff::zk_login::{CanonicalSerialize, JWK, JwkId, OIDCProvider, ZkLoginInputs};


use im::hashmap::HashMap as ImHashMap;


pub const VALUE_PORTION_SIZE: usize = 126;

//todo: need mechanism to change these JWK, need JWT fo other open providers
// const GOOGLE_JWK_BYTES: &[u8] = r#"{
// "keys": [
// {
// "n": "4kGxcWQdTW43aszLmftsGswmwDDKdfcse-lKeT_zjZTB2KGw9E6LVY6IThJVxzYF6mcyU-Z5_jDAW_yi7D_gXep2rxchZvoFayXynbhxyfjK6RtJ6_k30j-WpsXCSAiNAkupYHUyDIBNocvUcrDJsC3U65l8jl1I3nW98X6d-IlAfEb2In2f0fR6d-_lhIQZjXLupjymJduPjjA8oXCUZ9bfAYPhGYj3ZELUHkAyDpZNrnSi8hFVMSUSnorAt9F7cKMUJDM4-Uopzaqcl_f-HxeKvxN7NjiLSiIYaHdgtTpCEuNvsch6q6JTsllJNr3c__BxrG4UMlJ3_KsPxbcvXw==",
// "use": "sig",
// "alg": "RS256",
// "e": "AQAB",
// "kid": "911e39e27928ae9f1e9d1e21646de92d19351b44",
// "kty": "RSA"
// },
// {
// "n": "pGMz603XOzO71r-LpW555Etbn2dXAtY4xToNE_Upr1EHxkHFnVnGPsbOeWzP8xU1IpAL56S3sTsbpCR_Ci_PYq8s4I3VWQM0u9w1D_e45S1KJTSex_aiMQ_cjTXb3Iekc00JIkMJhUaNnbsEt7PlOmnyFqvN-G3ZXVDfTuL2Wsn4tRMYf7YU3jgTVN2M_p7bcZYHhkEB-jzNeK7ub-6mOMkKdYWnk0jIoRfV63d32bub0pQpWv8sVmflgK2xKUSJVMZ7CM0FvJYJgF7y42KBPYc6Gm_UWE0uHazDgZgAvQQoNyEF_TRjVfGiihjPFYCPqvFcfLK4773JTD2fLZTgOQ==",
// "kid": "7c9c78e3b00e1bb092d246c887b11220c87b7d20",
// "e": "AQAB",
// "alg": "RS256",
// "kty": "RSA",
// "use": "sig"
// },
// {
// "use": "sig",
// "kid": "fd48a75138d9d48f0aa635ef569c4e196f7ae8d6",
// "e": "AQAB",
// "n": "8KImylelEspnZ0X-ekZb9VPbUFhgB_yEPJuLKOhXOWJLVsU0hJP6B_mQOfVk0CHm66UsAhqV8qrINk-RXgwVaaFLMA827pbOOBhyvHsThcyo7AY5s6M7qbftFKKnkfVHO6c9TsQ9wpIfmhCVL3QgTlqlgFQWcNsY-qemSKpqvVi-We9I3kPvbTf0PKJ_rWA7GQQnU_GA5JRU46uvw4I1ODf0icNBHw7pWc7oTvmSl1G8OWABEyiFakcUG2Xd4qZnmWaKwLHBvifPuIyy2vK-yHH91mVZCuleVu53Vzj77RgUtF2EEuB-zizwC-fzaBmvnfx1kgQLsdK22J0Ivgu4Xw==",
// "kty": "RSA",
// "alg": "RS256"
// }
// ]
// }"#.as_bytes();

#[test]
fn test_vrgrth16() {
let user_pass_salt = "206703048842351542647799591018316385612";

// Generate an ephemeral key pair.
let ephemeral_kp = Ed25519KeyPair::generate(&mut StdRng::from_seed([0; 32]));
let mut eph_pubkey = vec![0x00];
eph_pubkey.extend(ephemeral_kp.public().as_ref());

println!("eph_pubkey: {:?}", hex::encode(eph_pubkey.clone()));
let len = eph_pubkey.clone().len();
println!("len eph_pubkey: {:?}", len);

// Get the zklogin seed.
//This stuff is a kind of bound between smart contract and email (some account)
//It will be stored in smart contract (must be added during contract deployment)
let zk_seed = gen_address_seed(
user_pass_salt,
"sub",
"106294049240999307923",
"25769832374-famecqrhe2gkebt5fvqms2263046lj96.apps.googleusercontent.com",
).unwrap();

println!("zk_seed = {:?}", zk_seed);

let proof_and_jwt = "{\"proofPoints\":{\"a\":[\"8247215875293406890829839156897863742504615191361518281091302475904551111016\",\"6872980335748205979379321982220498484242209225765686471076081944034292159666\",\"1\"],\"b\":[[\"21419680064642047510915171723230639588631899775315750803416713283740137406807\",\"21566716915562037737681888858382287035712341650647439119820808127161946325890\"],[\"17867714710686394159919998503724240212517838710399045289784307078087926404555\",\"21812769875502013113255155836896615164559280911997219958031852239645061854221\"],[\"1\",\"0\"]],\"c\":[\"7530826803702928198368421787278524256623871560746240215547076095911132653214\",\"16244547936249959771862454850485726883972969173921727256151991751860694123976\",\"1\"]},\"issBase64Details\":{\"value\":\"yJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLC\",\"indexMod4\":1},\"headerBase64\":\"eyJhbGciOiJSUzI1NiIsImtpZCI6IjZmNzI1NDEwMWY1NmU0MWNmMzVjOTkyNmRlODRhMmQ1NTJiNGM2ZjEiLCJ0eXAiOiJKV1QifQ\"}";
let len = proof_and_jwt.bytes().len();
println!(" proof_and_jwt_bytes len (in bytes) = {:?}", len);

let zk_login_inputs = ZkLoginInputs::from_json(
&*proof_and_jwt, &*zk_seed.to_string()).unwrap();

let content: JWK = JWK {
kty: "RSA".to_string(),
e: "AQAB".to_string(),
n: "oUriU8GqbRw-avcMn95DGW1cpZR1IoM6L7krfrWvLSSCcSX6Ig117o25Yk7QWBiJpaPV0FbP7Y5-DmThZ3SaF0AXW-3BsKPEXfFfeKVc6vBqk3t5mKlNEowjdvNTSzoOXO5UIHwsXaxiJlbMRalaFEUm-2CKgmXl1ss_yGh1OHkfnBiGsfQUndKoHiZuDzBMGw8Sf67am_Ok-4FShK0NuR3-q33aB_3Z7obC71dejSLWFOEcKUVCaw6DGVuLog3x506h1QQ1r0FXKOQxnmqrRgpoHqGSouuG35oZve1vgCU4vLZ6EAgBAbC0KL35I7_0wUDSMpiAvf7iZxzJVbspkQ".to_string(),
alg: "RS256".to_string(),
};

let mut all_jwk = ImHashMap::new();
all_jwk.insert(
JwkId::new(
OIDCProvider::Google.get_config().iss,
"6f7254101f56e41cf35c9926de84a2d552b4c6f1".to_string(),
),
content,
);

let (iss, kid) = (zk_login_inputs.get_iss().to_string(), zk_login_inputs.get_kid().to_string());
let jwk = all_jwk
.get(&JwkId::new(iss.clone(), kid.clone()))
.ok_or_else(|| {
ZkCryptoError::GeneralError(format!("JWK not found ({} - {})", iss, kid))
}).unwrap();

let max_epoch = 10;

// Decode modulus to bytes.
let modulus = base64ct::Base64UrlUnpadded::decode_vec(&jwk.n).map_err(|_| {
ZkCryptoError::GeneralError("Invalid Base64 encoded jwk modulus".to_string())
}).unwrap();

let proof = &zk_login_inputs.get_proof().as_arkworks().unwrap();
let public_inputs = &[zk_login_inputs.calculate_all_inputs_hash(&eph_pubkey, &modulus, max_epoch).unwrap()];

let mut proof_as_bytes = vec![];
proof.serialize_compressed(&mut proof_as_bytes).unwrap();
println!("proof_as_bytes : {:?}", proof_as_bytes);

let proof_cell = pack_data_to_cell(&proof_as_bytes, &mut 0).unwrap();

let mut public_inputs_as_bytes = vec![];
public_inputs.serialize_compressed(&mut public_inputs_as_bytes).unwrap();
println!("public_inputs_as_bytes : {:?}", public_inputs_as_bytes);

let public_inputs_cell = pack_data_to_cell(&public_inputs_as_bytes, &mut 0).unwrap();

let verification_key_id: u32 = 1;

let mut code = "PUSHREF \n".to_string();
code = code + "PUSHREF \n";
code = code + "PUSHINT " + &*verification_key_id.to_string() + "\n";
code = code + "VERGRTH16";

// ... run 'code', providing proof_cell, public_inputs_cell into stack..
}



0 comments on commit 2f1c7bd

Please sign in to comment.