Skip to content

Implement BLS12-381 contracttype support #1449

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

Merged
merged 14 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 22 additions & 6 deletions soroban-sdk/src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,6 @@ macro_rules! impl_bytesn_repr {
}
}

impl IntoVal<Env, Val> for $elem {
fn into_val(&self, e: &Env) -> Val {
self.0.into_val(e)
}
}

impl TryFromVal<Env, Val> for $elem {
type Error = ConversionError;

Expand All @@ -158,6 +152,28 @@ macro_rules! impl_bytesn_repr {
}
}

impl TryFromVal<Env, $elem> for Val {
type Error = ConversionError;

fn try_from_val(_env: &Env, elt: &$elem) -> Result<Self, Self::Error> {
Ok(elt.to_val())
}
}

#[cfg(not(target_family = "wasm"))]
impl From<&$elem> for ScVal {
fn from(v: &$elem) -> Self {
Self::from(&v.0)
}
}

#[cfg(not(target_family = "wasm"))]
impl From<$elem> for ScVal {
fn from(v: $elem) -> Self {
(&v).into()
}
}

impl IntoVal<Env, BytesN<$size>> for $elem {
fn into_val(&self, _e: &Env) -> BytesN<$size> {
self.0.clone()
Expand Down
30 changes: 24 additions & 6 deletions soroban-sdk/src/crypto/bls12_381.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#[cfg(not(target_family = "wasm"))]
use crate::xdr::ScVal;
use crate::{
env::internal::{self, BytesObject, U256Val, U64Val},
impl_bytesn_repr,
Expand Down Expand Up @@ -464,12 +466,6 @@ impl From<&Fr> for U256Val {
}
}

impl IntoVal<Env, Val> for Fr {
fn into_val(&self, e: &Env) -> Val {
self.0.into_val(e)
}
}

impl TryFromVal<Env, Val> for Fr {
type Error = ConversionError;

Expand All @@ -479,6 +475,28 @@ impl TryFromVal<Env, Val> for Fr {
}
}

impl TryFromVal<Env, Fr> for Val {
type Error = ConversionError;

fn try_from_val(_env: &Env, fr: &Fr) -> Result<Self, Self::Error> {
Ok(fr.to_val())
}
}

#[cfg(not(target_family = "wasm"))]
impl From<&Fr> for ScVal {
fn from(v: &Fr) -> Self {
Self::from(&v.0)
}
}

#[cfg(not(target_family = "wasm"))]
impl From<Fr> for ScVal {
fn from(v: Fr) -> Self {
(&v).into()
}
}

impl Eq for Fr {}

impl PartialEq for Fr {
Expand Down
89 changes: 89 additions & 0 deletions soroban-sdk/src/testutils/arbitrary.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,7 @@ mod objects {

use crate::xdr::{Int256Parts, ScVal, UInt256Parts};
use crate::{
crypto::bls12_381::{Fr, G1Affine, G2Affine},
Address, Bytes, BytesN, Duration, Map, String, Symbol, Timepoint, Val, Vec, I256, U256,
};

Expand Down Expand Up @@ -680,6 +681,94 @@ mod objects {
Ok(sc_duration.into_val(env))
}
}

// For G1Affine (96 bytes)
#[derive(Arbitrary, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ArbitraryG1Affine {
bytes: [u8; 96],
}

impl SorobanArbitrary for G1Affine {
type Prototype = ArbitraryG1Affine;
}

impl TryFromVal<Env, ArbitraryG1Affine> for G1Affine {
type Error = ConversionError;

fn try_from_val(env: &Env, v: &ArbitraryG1Affine) -> Result<Self, Self::Error> {
let mut bytes = v.bytes;
// the top 3 bits in a G1 point are reserved for flags:
// compression_flag (bit 0), infinity_flag (bit 1) and sort_flag
// (bit 2). Only infinity_flag is possible to be set, in which case
// the rest of the bytes must be zeros. The host will reject any
// invalid input. Manually taking care of the flag bits here to give
// it better chance of being a valid input.
const INFINITY_FLAG: u8 = 0b0100_0000;
const FLAG_MASK: u8 = 0b1110_0000;
if (bytes[0] & INFINITY_FLAG) != 0 {
// infinity flag set, clear rest of bits
bytes = [0; 96];
bytes[0] = INFINITY_FLAG;
} else {
// not an infinity point, we clear the flag bits
bytes[0] &= !FLAG_MASK
}
Ok(G1Affine::from_array(env, &bytes))
}
}

// For G2Affine (192 bytes)
#[derive(Arbitrary, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ArbitraryG2Affine {
bytes: [u8; 192],
}

impl SorobanArbitrary for G2Affine {
type Prototype = ArbitraryG2Affine;
}

impl TryFromVal<Env, ArbitraryG2Affine> for G2Affine {
type Error = ConversionError;

fn try_from_val(env: &Env, v: &ArbitraryG2Affine) -> Result<Self, Self::Error> {
let mut bytes = v.bytes;
// the top 3 bits in a G1 point are reserved for flags:
// compression_flag (bit 0), infinity_flag (bit 1) and sort_flag
// (bit 2). Only infinity_flag is possible to be set, in which case
// the rest of the bytes must be zeros. The host will reject any
// invalid input. Manually taking care of the flag bits here to give
// it better chance of being a valid input.
const INFINITY_FLAG: u8 = 0b0100_0000;
const FLAG_MASK: u8 = 0b1110_0000;
if (bytes[0] & INFINITY_FLAG) != 0 {
// infinity flag set, clear rest of bits
bytes = [0; 192];
bytes[0] = INFINITY_FLAG;
} else {
// not an infinity point, we clear the flag bits
bytes[0] &= !FLAG_MASK
}
Ok(G2Affine::from_array(env, &bytes))
}
}

#[derive(Arbitrary, Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct ArbitraryFr {
bytes: [u8; 32],
}

impl SorobanArbitrary for Fr {
type Prototype = ArbitraryFr;
}

impl TryFromVal<Env, ArbitraryFr> for Fr {
type Error = ConversionError;

fn try_from_val(env: &Env, v: &ArbitraryFr) -> Result<Self, Self::Error> {
// Convert bytes to Fr via U256
Ok(Fr::from_bytes(BytesN::from_array(env, &v.bytes)))
}
}
}

/// Implementations of `soroban_sdk::testutils::arbitrary::api` for tuples of Soroban types.
Expand Down
18 changes: 18 additions & 0 deletions tests/bls/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "test_bls"
version.workspace = true
authors = ["Stellar Development Foundation <info@stellar.org>"]
license = "Apache-2.0"
edition = "2021"
publish = false
rust-version = "1.84.0"

[lib]
crate-type = ["cdylib"]
doctest = false

[dependencies]
soroban-sdk = {path = "../../soroban-sdk"}

[dev-dependencies]
soroban-sdk = {path = "../../soroban-sdk", features = ["testutils"]}
99 changes: 99 additions & 0 deletions tests/bls/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#![no_std]
use soroban_sdk::{
contract, contractimpl, contracttype,
crypto::bls12_381::{Fr, G1Affine, G2Affine},
Env,
};

#[derive(Clone)]
#[contracttype]
pub struct DummyProof {
pub g1: G1Affine,
pub g2: G2Affine,
pub fr: Fr,
}

#[contract]
pub struct Contract;

#[contractimpl]
impl Contract {
pub fn g1_mul(env: Env, p: G1Affine, s: Fr) -> G1Affine {
env.crypto().bls12_381().g1_mul(&p, &s)
}

pub fn g2_mul(env: Env, p: G2Affine, s: Fr) -> G2Affine {
env.crypto().bls12_381().g2_mul(&p, &s)
}

pub fn dummy_verify(env: Env, proof: DummyProof) -> bool {
let g1_mul = env.crypto().bls12_381().g1_mul(&proof.g1, &proof.fr);
let g2_mul = env.crypto().bls12_381().g2_mul(&proof.g2, &proof.fr);
let vp1 = soroban_sdk::Vec::from_array(&env, [g1_mul]);
let vp2 = soroban_sdk::Vec::from_array(&env, [g2_mul]);
env.crypto().bls12_381().pairing_check(vp1, vp2)
}
}

#[cfg(test)]
mod test {
use super::*;
use soroban_sdk::{bytesn, Env};

use crate::{Contract, ContractClient};

#[test]
fn test_g1_mul() {
let env = Env::default();
let contract_id = env.register(Contract, ());
let client = ContractClient::new(&env, &contract_id);

// G1 generator and zero scalar
let g1 = G1Affine::from_bytes(bytesn!(&env, 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1));
let zero = Fr::from_bytes(bytesn!(
&env,
0x0000000000000000000000000000000000000000000000000000000000000000
));
let inf = G1Affine::from_bytes(bytesn!(&env, 0x400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000));
let res = client.g1_mul(&g1, &zero);
assert_eq!(res, inf);
}

#[test]
fn test_g2_mul() {
let env = Env::default();
let contract_id = env.register(Contract, ());
let client = ContractClient::new(&env, &contract_id);

// G2 generator and zero scalar
let g2 = G2Affine::from_bytes(bytesn!(&env, 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801));
let zero = Fr::from_bytes(bytesn!(
&env,
0x0000000000000000000000000000000000000000000000000000000000000000
));
let inf = G2Affine::from_bytes(bytesn!(&env, 0x400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000));
let res = client.g2_mul(&g2, &zero);
assert_eq!(res, inf);
}

#[test]
fn test_dummy_verify() {
let env = Env::default();
let contract_id = env.register(Contract, ());
let client = ContractClient::new(&env, &contract_id);

// Use generator points
let g1 = G1Affine::from_bytes(bytesn!(&env, 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1));
let g2 = G2Affine::from_bytes(bytesn!(&env, 0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801));

// Create a scalar value
let fr = Fr::from_bytes(bytesn!(
&env,
0x0000000000000000000000000000000000000000000000000000000000000001
));

let proof = DummyProof { g1, g2, fr };
let res = client.dummy_verify(&proof);
assert!(!res); // The pairing of generator points multiplied by the same scalar should not be the identity
}
}
Loading