Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WEB3-262: Add [Groth16] Seal utilities #365

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 102 additions & 2 deletions contracts/src/groth16.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,82 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use alloy::sol_types::SolValue;
use alloy::{hex, primitives::Bytes, sol_types::SolValue};
use anyhow::Result;
use risc0_zkvm::{sha::Digestible, Groth16ReceiptVerifierParameters};
use risc0_zkvm::{
sha::Digestible, FakeReceipt, Groth16Receipt, Groth16ReceiptVerifierParameters, InnerReceipt,
MaybePruned, Receipt, ReceiptClaim,
};

alloy::sol!(
#![sol(all_derives)]
struct Seal {
uint256[2] a;
uint256[2][2] b;
uint256[2] c;
}
);

impl Seal {
fn flatten(self) -> Vec<u8> {
self.a
.iter()
.map(|x| x.to_be_bytes_vec())
.chain(
self.b
.iter()
.flat_map(|x| x.iter().map(|y| y.to_be_bytes_vec())),
)
.chain(self.c.iter().map(|x| x.to_be_bytes_vec()))
.flatten()
.collect()
}

/// Convert the [Seal] into a [Receipt] constructed with the given [ReceiptClaim] and
/// journal. The verifier parameters are optional and default to the current zkVM version.
pub fn to_receipt(
self,
claim: ReceiptClaim,
journal: impl AsRef<[u8]>,
verifier_parameters: Option<Groth16ReceiptVerifierParameters>,
) -> Receipt {
let inner = risc0_zkvm::InnerReceipt::Groth16(Groth16Receipt::new(
self.flatten(),
MaybePruned::Value(claim),
verifier_parameters.unwrap_or_default().digest(),
));
Receipt::new(inner, journal.as_ref().to_vec())
}
}

/// Decode a seal with selector as [Bytes] into a [Receipt] constructed with the given [ReceiptClaim]
/// and journal. The verifier parameters are optional and default to the current zkVM version.
pub fn decode_seal(
seal: Bytes,
claim: ReceiptClaim,
journal: impl AsRef<[u8]>,
verifier_parameters: Option<Groth16ReceiptVerifierParameters>,
) -> Result<Receipt> {
let seal_bytes = seal.to_vec();
let (selector, stripped_seal) = seal_bytes.split_at(4);
// Fake receipt seal is 32 bytes
let receipt = if stripped_seal.len() == 32 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A set inclusion seal with one path element will also be 32 bytes.

if selector != [0u8; 4] {
return Err(anyhow::anyhow!(
"Invalid selector {} for fake receipt",
hex::encode(selector)
));
};
Receipt::new(
InnerReceipt::Fake(FakeReceipt::new(claim)),
journal.as_ref().to_vec(),
)
} else {
Comment on lines +74 to +85
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this function should handle fake receipts. It's currently an odd compromise, where it handles Groth16 and Fake receipts, but not set inclusion receipts and it would not handle e.g. Plonk receipts if we add them later. We probably needs two types of decoding. One would be a method that decodes to a specific type (e.g. Groth16, Fake, or SetInclusion), and another that decodes any seal in a list of known types. For the later, we will need a table included in the library mapping selectors to verifier parameter (digests). At the very least, that table should include Groth16, SetInclusion and Fake verifier parameters for the current version. We could additionally include previous versions in the this table as well. We've discussed this elsewhere, and it seems likely to be useful.

let seal = Seal::abi_decode(stripped_seal, true)?;
seal.to_receipt(claim, journal, verifier_parameters)
};
Ok(receipt)
}

/// ABI encoding of the seal.
pub fn abi_encode(seal: impl AsRef<[u8]>) -> Result<Vec<u8>> {
Expand Down Expand Up @@ -44,13 +117,18 @@ pub fn encode(seal: impl AsRef<[u8]>) -> Result<Vec<u8>> {
mod tests {
use anyhow::anyhow;
use regex::Regex;
use risc0_zkvm::sha::Digest;

use super::*;
use std::fs;

const CONTROL_ID_PATH: &str = "./src/groth16/ControlID.sol";
const CONTROL_ROOT: &str = "CONTROL_ROOT";
const BN254_CONTROL_ID: &str = "BN254_CONTROL_ID";
const TEST_RECEIPT_PATH: &str = "./test/TestReceipt.sol";
const SEAL: &str = "SEAL";
const JOURNAL: &str = "JOURNAL";
const IMAGE_ID: &str = "IMAGE_ID";

fn parse_digest(file_path: &str, name: &str) -> Result<String, anyhow::Error> {
let content = fs::read_to_string(file_path)?;
Expand Down Expand Up @@ -78,4 +156,26 @@ mod tests {

assert_eq!(bn254_control_id, expected_bn254_control_id);
}

#[test]
fn test_decode_seal() {
let seal_bytes =
Bytes::from(hex::decode(parse_digest(TEST_RECEIPT_PATH, SEAL).unwrap()).unwrap());
let journal =
Bytes::from(hex::decode(parse_digest(TEST_RECEIPT_PATH, JOURNAL).unwrap()).unwrap())
.to_vec();
let image_id = Digest::try_from(
Bytes::from(hex::decode(parse_digest(TEST_RECEIPT_PATH, IMAGE_ID).unwrap()).unwrap())
.as_ref(),
)
.unwrap();
let receipt = decode_seal(
seal_bytes,
ReceiptClaim::ok(image_id, journal.clone()),
&journal,
None,
)
.unwrap();
receipt.verify(image_id).unwrap();
}
}
Loading