Proofs for Inner Pairing Products and Applications代码解析

2023-10-10 20:40

本文主要是介绍Proofs for Inner Pairing Products and Applications代码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1. 引言

Benedikt Bünz 等人(standford,ethereum,berkeley) 2019年论文《Proofs for Inner Pairing Products and Applications》。

视频介绍:(2020年3月31日)
https://www.youtube.com/watch?v=oYdkGIoHKt0

代码实现:

  • https://github.com/scipr-lab/ripp【本文重点解析本代码库】
  • https://github.com/qope/SIPP(Rust,基于Plonky2和Starky的BN254 pairing以及 ecdsa):在M1 MacBookPro(2021)机器上运行cargo test test_sipp_circuit -r -- --nocapture,基本性能为:【排除circuit building时间,做128个pairing聚合用时约145秒。】
    Aggregating 128 pairings into 1
    Start: cirucit build
    End: circuit build. took 35.545641375s
    Start: proof generation
    End: proof generation. took 145.043526708s
    

注意该代码使用rust stable版本,且低版本可能会报错,建议升级到最新的stable版本:

rustup install stable

代码总体基本结构为:

  • examples:scaling-ipp.rs,执行方式可为cargo run --release --example scaling-ipp 10 20 .
    在这里插入图片描述

  • plot:ipp-scaling.gnuplot为gnuplot脚本,使用examples/scaling-ipp 输出的*.csv作图。

  • src:主源代码。
    – rng.rs:主要实现FiatShamirRng,基于Fiat-Shamir来实现non-interactive proof。【注意,与Merlin实现Fiat-Shamir transform方案有所不同,Merlin transcript是基于STROBE的 封装。Strobe的主要涉及原则为:在任意阶段的密码学输出,除依赖于密钥外,还依赖于之前所有的输入。strobe主要采用对称加密方案,更侧重于简单和安全,而不是速度;noise协议采用非对称加密方案,已在WhatsAPP上落地应用。】(详细参加博客 Merlin——零知识证明(1)理论篇 和博客 strobe——面向IoT物联网应用的密码学协议框架)

/// A `SeedableRng` that refreshes its seed by hashing together the previous seed
/// and the new seed material.
// TODO: later: re-evaluate decision about ChaChaRng
pub struct FiatShamirRng<D: Digest> {r: ChaChaRng,seed: GenericArray<u8, D::OutputSize>,#[doc(hidden)]digest: PhantomData<D>,
}

– lib.rs:实现了论文《Proofs for Inner Pairing Products and Applications》中的SIPP协议。

2. 主要依赖

参见https://github.com/scipr-lab/ripp/blob/master/Cargo.toml中内容,分为[dependencies][dev-dependencies],两者的异同点有:

  • [dev-dependencies]段落的格式等同于[dependencies]段落,
  • 不同之处在于,[dependencies]段落声明的依赖用于构建软件包,
  • 而[dev-dependencies]段落声明的依赖仅用于构建测试和性能评估。
  • 此外,[dev-dependencies]段落声明的依赖不会传递给其他依赖本软件包的项目

[dependencies]依赖主要有:

  • algebra-core = { git = “https://github.com/scipr-lab/zexe”, features = [ “parallel” ] }:为Rust crate that provides generic arithmetic for finite fields and elliptic curves。其中features parallel = [ "std", "rayon" ]
  • rayon:为data-parallelism Rust库。非常轻量,很容易convert a sequential computation into a parallel one。(具体可参加博客 Rayon: data parallelism in Rust)
// sequential iterator
let total_price = stores.iter().map(|store| store.compute_price(&list)).sum();
// parallel iterator
let total_price = stores.par_iter().map(|store| store.compute_price(&list)).sum();
  • rand_core:主要用于实现the core trait:RngCore
  • rand_chacha:为使用ChaCha算法实现的密码学安全的随机数生成器。
  • digest:为https://github.com/RustCrypto/traits中的digest算法。

[dev-dependencies]依赖主要有:

  • blake2:BLAKE2 hash function family库。
  • rand:provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms.
  • csv:A fast and flexible CSV reader and writer for Rust, with support for Serde.
  • serde = { version = “1”, features = [ “derive” ] }:Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.
  • algebra = { git = “https://github.com/scipr-lab/zexe”, features = [ “bls12_377” ] }:为 Rust crate that provides concrete instantiations of some finite fields and elliptic curves。

3. SIPP协议实现

参见博客 Proofs for Inner Pairing Products and Applications 学习笔记第3.1节“SIPP的构建”。
在这里插入图片描述
lib.rs中的实现为 A ⃗ = { r 1 a 1 , ⋯ , r m a m } , B ⃗ = { b 1 , ⋯ , b m } \vec{A}=\{r_1a_1,\cdots,r_ma_m\},\vec{B}=\{b_1,\cdots,b_m\} A ={r1a1,,rmam},B ={b1,,bm},其中 r i ∈ F r , a i ∈ G 1 , b i ∈ G 2 r_i\in\mathbb{F}_r,a_i\in\mathbb{G}_1,b_i\in\mathbb{G}_2 riFr,aiG1,biG2
在SIPP协议中 A ⃗ , B ⃗ , Z = A ⃗ ∗ B ⃗ = ∏ i = 1 m e ( A i , B i ) \vec{A},\vec{B},Z=\vec{A}*\vec{B}=\prod_{i=1}^{m}e(A_i,B_i) A ,B ,Z=A B =i=1me(Ai,Bi)均为。在实际Verify时,并未逐轮计算 A ⃗ ′ , B ⃗ ′ \vec{A}',\vec{B}' A ,B ,而是将其展开了利用multi_scalar_mul来计算。同时使用FiatShamirRng将interactive proof转为了non-interactive proof。
详细的代码实现为:

  • 初始化 a ⃗ , r ⃗ , B ⃗ \vec{a},\vec{r},\vec{B} a ,r ,B vector信息:
        for _ in 0..32 {a.push(G1Projective::rand(&mut rng).into_affine());b.push(G2Projective::rand(&mut rng).into_affine());r.push(Fr::rand(&mut rng));}
  • 计算 Z = A ⃗ ∗ B ⃗ = ∏ i = 1 m e ( r i a i , B i ) Z=\vec{A}*\vec{B}=\prod_{i=1}^{m}e(r_ia_i,B_i) Z=A B =i=1me(riai,Bi)
let z = product_of_pairings_with_coeffs::<Bls12_377>(&a, &b, &r);/// Compute the product of pairings of `r_i * a_i` and `b_i`.
pub fn product_of_pairings_with_coeffs<E: PairingEngine>(a: &[E::G1Affine],b: &[E::G2Affine],r: &[E::Fr],
) -> E::Fqk {let a = a.into_par_iter().zip(r).map(|(a, r)| a.mul(*r)).collect::<Vec<_>>();let a = E::G1Projective::batch_normalization_into_affine(&a);let elements = a.par_iter().zip(b).map(|(a, b)| (E::G1Prepared::from(*a), E::G2Prepared::from(*b))).collect::<Vec<_>>();let num_chunks = elements.len() / rayon::current_num_threads();let num_chunks = if num_chunks == 0 { elements.len() } else { num_chunks };let ml_result = elements.par_chunks(num_chunks).map(E::miller_loop).product();E::final_exponentiation(&ml_result).unwrap()
}
  • SIPP prove证明:(输入为 a ⃗ , r ⃗ , B ⃗ , Z \vec{a},\vec{r},\vec{B},Z a ,r ,B ,Z
let proof = SIPP::<Bls12_377, Blake2s>::prove(&a, &b, &r, z);/// Produce a proof of the inner pairing product.pub fn prove(a: &[E::G1Affine],b: &[E::G2Affine],r: &[E::Fr],value: E::Fqk) -> Result<Proof<E>, ()> {assert_eq!(a.len(), b.len());// Ensure the order of the input vectors is a power of 2assert_eq!(a.len().count_ones(), 1);let mut length = a.len();assert_eq!(length, b.len());assert_eq!(length.count_ones(), 1);let mut proof_vec = Vec::new();// TODO(psi): should we also input a succinct bilinear group description to the rng?let mut rng = FiatShamirRng::<D>::from_seed(&to_bytes![a, b, r, value].unwrap());let a = a.into_par_iter().zip(r).map(|(a, r)| a.mul(*r)).collect::<Vec<_>>();let mut a = E::G1Projective::batch_normalization_into_affine(&a);let mut b = b.to_vec();while length != 1 {length /= 2;let a_l = &a[..length];let a_r = &a[length..];let b_l = &b[..length];let b_r = &b[length..];let z_l = product_of_pairings::<E>(a_r, b_l);let z_r = product_of_pairings::<E>(a_l, b_r);proof_vec.push((z_l, z_r));rng.absorb(&to_bytes![z_l, z_r].unwrap());let x: E::Fr = u128::rand(&mut rng).into();let a_proj = a_l.par_iter().zip(a_r).map(|(a_l, a_r)| {let mut temp = a_r.mul(x);temp.add_assign_mixed(a_l);temp}).collect::<Vec<_>>();a = E::G1Projective::batch_normalization_into_affine(&a_proj);let x_inv = x.inverse().unwrap();let b_proj = b_l.par_iter().zip(b_r).map(|(b_l, b_r)| {let mut temp = b_r.mul(x_inv);temp.add_assign_mixed(b_l);temp}).collect::<Vec<_>>();b = E::G2Projective::batch_normalization_into_affine(&b_proj);}Ok(Proof {gt_elems: proof_vec})}
  • SIPP verify 验证:(输入为 a ⃗ , r ⃗ , B ⃗ , Z , p r o o f ⃗ \vec{a},\vec{r},\vec{B},Z,\vec{proof} a ,r ,B ,Z,proof
let accept = SIPP::<Bls12_377, Blake2s>::verify(&a, &b, &r, z, &proof);/// Verify an inner-pairing-product proof.pub fn verify(a: &[E::G1Affine],b: &[E::G2Affine],r: &[E::Fr],claimed_value: E::Fqk,proof: &Proof<E>) -> Result<bool, ()> {// Ensure the order of the input vectors is a power of 2let length = a.len();assert_eq!(length.count_ones(), 1);assert!(length >= 2);assert_eq!(length, b.len());// Ensure there are the correct number of proof elementslet proof_len = proof.gt_elems.len();assert_eq!(proof_len as f32, f32::log2(length as f32));// TODO(psi): should we also input a succinct bilinear group description to the rng?let mut rng = FiatShamirRng::<D>::from_seed(&to_bytes![a, b, r, claimed_value].unwrap());let x_s = proof.gt_elems.iter().map(|(z_l, z_r)| {rng.absorb(&to_bytes![z_l, z_r].unwrap());let x: E::Fr = u128::rand(&mut rng).into();x}).collect::<Vec<_>>();let mut x_invs = x_s.clone();algebra_core::batch_inversion(&mut x_invs);let z_prime = claimed_value * &proof.gt_elems.par_iter().zip(&x_s).zip(&x_invs).map(|(((z_l, z_r), x), x_inv)| {z_l.pow(x.into_repr()) * &z_r.pow(x_inv.into_repr())}).reduce(|| E::Fqk::one(), |a, b| a * &b);let mut s: Vec<E::Fr> = vec![E::Fr::one(); length];let mut s_invs: Vec<E::Fr> = vec![E::Fr::one(); length];// TODO(psi): batch verifyfor (j, (x, x_inv)) in x_s.into_iter().zip(x_invs).enumerate() {for i in 0..length {if i & (1 << (proof_len - j - 1)) != 0 {s[i] *= &x;s_invs[i] *= &x_inv;}}}let s = s.into_iter().zip(r).map(|(x, r)| (x * r).into_repr()).collect::<Vec<_>>();let s_invs = s_invs.iter().map(|x_inv| x_inv.into_repr()).collect::<Vec<_>>();let a_prime = VariableBaseMSM::multi_scalar_mul(&a, &s);let b_prime = VariableBaseMSM::multi_scalar_mul(&b, &s_invs);let accept = E::pairing(a_prime, b_prime) == z_prime;Ok(accept)}
}

这篇关于Proofs for Inner Pairing Products and Applications代码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/182962

相关文章

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

一文解析C#中的StringSplitOptions枚举

《一文解析C#中的StringSplitOptions枚举》StringSplitOptions是C#中的一个枚举类型,用于控制string.Split()方法分割字符串时的行为,核心作用是处理分割后... 目录C#的StringSplitOptions枚举1.StringSplitOptions枚举的常用

Python函数作用域与闭包举例深度解析

《Python函数作用域与闭包举例深度解析》Python函数的作用域规则和闭包是编程中的关键概念,它们决定了变量的访问和生命周期,:本文主要介绍Python函数作用域与闭包的相关资料,文中通过代码... 目录1. 基础作用域访问示例1:访问全局变量示例2:访问外层函数变量2. 闭包基础示例3:简单闭包示例4

MyBatis延迟加载与多级缓存全解析

《MyBatis延迟加载与多级缓存全解析》文章介绍MyBatis的延迟加载与多级缓存机制,延迟加载按需加载关联数据提升性能,一级缓存会话级默认开启,二级缓存工厂级支持跨会话共享,增删改操作会清空对应缓... 目录MyBATis延迟加载策略一对多示例一对多示例MyBatis框架的缓存一级缓存二级缓存MyBat

前端缓存策略的自解方案全解析

《前端缓存策略的自解方案全解析》缓存从来都是前端的一个痛点,很多前端搞不清楚缓存到底是何物,:本文主要介绍前端缓存的自解方案,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录一、为什么“清缓存”成了技术圈的梗二、先给缓存“把个脉”:浏览器到底缓存了谁?三、设计思路:把“发版”做成“自愈”四、代码

Java集合之Iterator迭代器实现代码解析

《Java集合之Iterator迭代器实现代码解析》迭代器Iterator是Java集合框架中的一个核心接口,位于java.util包下,它定义了一种标准的元素访问机制,为各种集合类型提供了一种统一的... 目录一、什么是Iterator二、Iterator的核心方法三、基本使用示例四、Iterator的工

Java 线程池+分布式实现代码

《Java线程池+分布式实现代码》在Java开发中,池通过预先创建并管理一定数量的资源,避免频繁创建和销毁资源带来的性能开销,从而提高系统效率,:本文主要介绍Java线程池+分布式实现代码,需要... 目录1. 线程池1.1 自定义线程池实现1.1.1 线程池核心1.1.2 代码示例1.2 总结流程2. J

JS纯前端实现浏览器语音播报、朗读功能的完整代码

《JS纯前端实现浏览器语音播报、朗读功能的完整代码》在现代互联网的发展中,语音技术正逐渐成为改变用户体验的重要一环,下面:本文主要介绍JS纯前端实现浏览器语音播报、朗读功能的相关资料,文中通过代码... 目录一、朗读单条文本:① 语音自选参数,按钮控制语音:② 效果图:二、朗读多条文本:① 语音有默认值:②