Skip to content

Commit 09f4b41

Browse files
committed
feat: debug success & Demo version 0.1.0
1 parent 6900757 commit 09f4b41

File tree

9 files changed

+128
-42
lines changed

9 files changed

+128
-42
lines changed

src/main.cpp

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
#include <rust/include/librustbellman.h>
21
#include <verifier.h>
32
#include <transaction.h>
43
#include <iostream>
54

65
int main(int argc, char** argv) {
7-
hello_world();
8-
96
// transaction needed to be verified
107
auto tx = Transaction::Mock();
118

src/prove.cpp

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,19 @@ Prove::initContext() {
1010
unsigned char* zkproof = (unsigned char*)malloc(GROTH_PROOF_SIZE);
1111
unsigned char* inputs = (unsigned char*)"this is payment address, so let's get started it.";
1212

13-
librust_proof(ctx, inputs, zkproof);
13+
bool proof_ret = librust_proof(ctx, inputs, zkproof);
14+
std::cout << "proof ret: " << std::boolalpha << proof_ret << std::endl;
15+
std::cout << "proof : " << zkproof << std::endl;
16+
17+
librust_proving_ctx_free(ctx);
1418

1519
auto ctx_verify = librust_verification_ctx_init();
16-
bool check_ret = librust_verification_check(ctx_verify, (const char*)zkproof, (const char*)inputs);
17-
std::cout << "proof check result: " << std::boolalpha << check_ret << std::endl;
20+
21+
bool check_ret = false;
22+
std::cout << "check_ret init status = " << std::boolalpha << check_ret << std::endl;
23+
check_ret = librust_verification_check(ctx_verify, (const char*)zkproof, (const char*)inputs);
24+
std::cout << "update check result: " << std::boolalpha << check_ret << std::endl;
25+
1826
librust_verification_ctx_free(ctx_verify);
1927

20-
librust_proving_ctx_free(ctx);
2128
}

src/rust/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ bls12_381 = "0.5"
1515
sha2 = "0.9.5"
1616
rand = "0.8.4"
1717
libc = "0.2.97"
18+
ff = "0.10"
1819

1920

2021
# https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html

src/rust/examples/tx.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
use crate::proof;
2+
3+
pub fn main() {
4+
5+
}

src/rust/include/librustbellman.h

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@
44
#ifdef __cplusplus
55
extern "C" {
66
#endif
7-
void hello_world();
8-
97
/// Creates a proving context. Please free this when you're done.
108
void * librust_proving_ctx_init();
119

@@ -21,11 +19,13 @@ extern "C" {
2119

2220
/// Checks the validity of the
2321
/// transaction given the binding signature.
24-
bool librust_verification_check(void *, const char* proof, const char* inputs);
22+
bool librust_verification_check(void *ctx, const char* proof, const char* inputs);
2523

2624
/// Frees a verification context.
2725
void librust_verification_ctx_free(void *);
2826

27+
void hello_world();
28+
2929
#ifdef __cplusplus
3030
}
3131
#endif

src/rust/src/circuit/tx.rs

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,38 @@ use bellman::{
99
groth16, Circuit, ConstraintSystem, SynthesisError,
1010
};
1111
use sha2::{Digest, Sha256};
12+
use ff::PrimeField;
1213

1314
pub struct Amount {
1415
// pub pay_address: Option<[u8; 2]>,
1516
// pub value: String,
1617
// pub out_address: String,
1718
}
1819

20+
fn sha256d<Scalar: PrimeField, CS: ConstraintSystem<Scalar>>(
21+
mut cs: CS,
22+
data: &[Boolean],
23+
) -> Result<Vec<Boolean>, SynthesisError> {
24+
// Flip endianness of each input byte
25+
let input: Vec<_> = data
26+
.chunks(8)
27+
.map(|c| c.iter().rev())
28+
.flatten()
29+
.cloned()
30+
.collect();
31+
32+
let mid = sha256(cs.namespace(|| "SHA-256(input)"), &input)?;
33+
let res = sha256(cs.namespace(|| "SHA-256(mid)"), &mid)?;
34+
35+
// Flip endianness of each output byte
36+
Ok(res
37+
.chunks(8)
38+
.map(|c| c.iter().rev())
39+
.flatten()
40+
.cloned()
41+
.collect())
42+
}
43+
1944
pub struct Tx {
2045
// pub hash: String,
2146
// pub amount: Amount,
@@ -55,14 +80,7 @@ impl Circuit<bls12_381::Scalar> for Tx {
5580
.collect::<Result<Vec<_>, _>>()?;
5681

5782
// Compute hash = SHA-256(preimage).
58-
let hash = sha256(cs.namespace(|| "SHA-256(mid)"), &preimage_bits)?;
59-
60-
// let public_input = hash
61-
// .chunks(8)
62-
// .map(|c| c.iter().rev())
63-
// .flatten()
64-
// .cloned()
65-
// .collect();
83+
let hash = sha256d(cs.namespace(|| "SHA-256(preimage)"), &preimage_bits)?;
6684

6785
// Expose the vector of 32 boolean variables as compact public inputs.
6886
multipack::pack_into_inputs(cs.namespace(|| "pack hash"), &hash)

src/rust/src/lib.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
#[no_mangle]
2-
pub extern "C" fn hello_world() {
3-
println!("Hello world from Bellman.");
4-
}
5-
61
#[cfg(test)]
72
mod tests {
83
#[test]

src/rust/src/librustbellman.rs

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
1-
2-
use crate::circuit::tx::Tx;
31
use bellman::groth16;
42
use bls12_381::Bls12;
5-
use rand::rngs::OsRng;
6-
use sha2::{Digest, Sha256};
73
use libc::{c_char, c_uchar};
84
use std::ffi::CStr;
95
use crate::proof::VerificationContext;
106
use crate::proof::ProvingContext;
7+
use std::io::{self, Write};
118

129
static mut PVK: Option<groth16::PreparedVerifyingKey<Bls12>> = None;
1310

@@ -27,13 +24,13 @@ pub extern "C" fn librust_proving_ctx_init() -> *mut ProvingContext {
2724

2825
#[no_mangle]
2926
pub extern "C" fn librust_proof(ctx: *mut ProvingContext, inputs: *const c_char, zkproof: *mut [c_uchar; GROTH_PROOF_SIZE]) -> bool {
30-
3127
let s = unsafe {
3228
CStr::from_ptr(inputs).to_string_lossy().into_owned()
3329
};
3430

3531
let mut a: [u8; 33] = [0u8;33];
3632
a.copy_from_slice(&s.as_bytes()[0..33]);
33+
println!("inputs : {:?}", a);
3734

3835
let (proof, pvk) = unsafe { &mut *ctx }.spend_proof(a);
3936

@@ -42,6 +39,8 @@ pub extern "C" fn librust_proof(ctx: *mut ProvingContext, inputs: *const c_char,
4239
.write(&mut (unsafe { &mut *zkproof })[..])
4340
.expect("should be able to serialize a proof");
4441

42+
// println!("zkproof : {:?}", zkproof);
43+
4544
// Write pvk out to caller
4645
// use of mutable static is unsafe and requires unsafe function or block
4746
unsafe {
@@ -61,12 +60,8 @@ pub extern "C" fn librust_proving_ctx_free(ctx: *mut ProvingContext) {
6160
}
6261
}
6362

64-
////
65-
///
66-
///
67-
6863
#[no_mangle]
69-
pub extern "C" fn librust_verification_ctx_init() -> *mut VerificationContext {
64+
pub extern "C" fn librust_verification_ctx_init() -> *mut VerificationContext {
7065
let ctx = Box::new(VerificationContext::new());
7166

7267
Box::into_raw(ctx)
@@ -78,7 +73,10 @@ pub extern "C" fn librust_verification_check(ctx: *mut VerificationContext, proo
7873
let proof = unsafe { CStr::from_ptr(proof) };
7974
let inputs = unsafe { CStr::from_ptr(inputs) };
8075

81-
unsafe { &mut *ctx }.verify_proof(pvk, proof.to_bytes(), inputs.to_bytes())
76+
let proof = proof.to_bytes();
77+
let inputs = inputs.to_bytes();
78+
79+
unsafe { &mut *ctx }.verify_proof(pvk, proof, inputs)
8280
}
8381

8482
#[no_mangle]
@@ -88,4 +86,9 @@ pub extern "C" fn librust_verification_ctx_free(ctx: *mut VerificationContext) {
8886
unsafe {
8987
drop(Box::from_raw(ctx));
9088
}
89+
}
90+
91+
#[no_mangle]
92+
pub extern "C" fn hello_world() {
93+
println!("Hello world from Bellman.");
9194
}

src/rust/src/proof.rs

Lines changed: 68 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,6 @@ impl ProvingContext {
2121
}
2222

2323
pub fn spend_proof(&self, inputs: [u8; 33]) -> (groth16::Proof<Bls12>, groth16::PreparedVerifyingKey<Bls12>) {
24-
println!("spend proof.");
25-
2624
let preimage = inputs;
2725

2826
// Create parameters for our circuit. In a production deployment these would
@@ -36,16 +34,66 @@ impl ProvingContext {
3634
let pvk = groth16::prepare_verifying_key(&params.vk);
3735

3836
// Pick a preimage and compute its hash.
39-
let hash = Sha256::digest(&preimage);
37+
let hash = Sha256::digest(&Sha256::digest(&preimage));
4038

4139
// Create an instance of our circuit (with the preimage as a witness).
4240
let c = Tx {
4341
pay_address: Some(preimage),
4442
};
4543

44+
// let hash_bits = multipack::bytes_to_bits_le(&hash);
45+
// let inputs = multipack::compute_multipacking(&hash_bits);
46+
47+
// Check the proof!
48+
let p = groth16::create_random_proof(c, &params, &mut OsRng).unwrap();
49+
// let ret = groth16::verify_proof(&pvk, &p, &inputs[..]).is_ok();
50+
// assert!(ret);
51+
52+
// let c = Tx {
53+
// pay_address: None,
54+
// };
55+
4656
// Create a Groth16 proof with our parameters.
47-
(groth16::create_random_proof(c, &params, &mut OsRng).unwrap(), pvk)
57+
(p, pvk)
4858
}
59+
60+
// pub fn spend_proof(&self, inputs: [u8; 33]) -> (groth16::Proof<Bls12>, groth16::PreparedVerifyingKey<Bls12>) {
61+
// let params = {
62+
// let c = Tx { pay_address: None };
63+
// groth16::generate_random_parameters::<Bls12, _, _>(c, &mut OsRng).unwrap()
64+
// };
65+
66+
// // Prepare the verification key (for proof verification).
67+
// let pvk = groth16::prepare_verifying_key(&params.vk);
68+
69+
// // Pick a preimage and compute its hash.
70+
// let preimage = [42; 33];
71+
// let hash = Sha256::digest(&Sha256::digest(&preimage));
72+
73+
// // Create an instance of our circuit (with the preimage as a witness).
74+
// let c = Tx {
75+
// pay_address: Some(preimage),
76+
// };
77+
78+
// // Create a Groth16 proof with our parameters.
79+
// let proof = groth16::create_random_proof(c, &params, &mut OsRng).unwrap();
80+
81+
// // Pack the hash as inputs for proof verification.
82+
// let hash_bits = multipack::bytes_to_bits_le(&hash);
83+
// let inputs = multipack::compute_multipacking(&hash_bits);
84+
85+
// // Check the proof!
86+
// assert!(groth16::verify_proof(&pvk, &proof, &inputs).is_ok());
87+
88+
89+
// let c = Tx {
90+
// pay_address: None,
91+
// };
92+
93+
// // Create a Groth16 proof with our parameters.
94+
// (groth16::create_random_proof(c, &params, &mut OsRng).unwrap(), pvk)
95+
96+
// }
4997
}
5098

5199
pub struct VerificationContext {}
@@ -55,15 +103,27 @@ impl VerificationContext {
55103
}
56104

57105
pub fn verify_proof(&self, pvk: &groth16::PreparedVerifyingKey<Bls12>, proof: &[u8], inputs: &[u8]) -> bool {
58-
let proof_data = groth16::Proof::<Bls12>::read(&(unsafe { &*proof })[..]);
59-
if let Ok(proof) = proof_data {
60-
let hash_bits = multipack::bytes_to_bits_le(&inputs);
106+
println!("----------");
107+
108+
let proof_data = groth16::Proof::read( &*proof );
109+
if let Ok(proof) = proof_data {
110+
let mut a: [u8; 33] = [0u8;33];
111+
a.copy_from_slice(&inputs[0..33]);
112+
113+
let hash = Sha256::digest(&Sha256::digest(&a));
114+
115+
let hash_bits = multipack::bytes_to_bits_le(&hash);
61116
let inputs = multipack::compute_multipacking(&hash_bits);
62117

118+
println!("is ok");
63119
// Check the proof!
64120
return groth16::verify_proof(&pvk, &proof, &inputs).is_ok();
121+
} else {
122+
println!("read proof error.");
65123
}
66124

67-
return false;
125+
println!("is false");
126+
127+
false
68128
}
69129
}

0 commit comments

Comments
 (0)