Skip to content

Commit

Permalink
Merge pull request #583 from Chia-Network/fix-pymethods
Browse files Browse the repository at this point in the history
Fix pymethods by moving outside of pybindings modules
  • Loading branch information
matt-o-how authored Jun 24, 2024
2 parents 0a90079 + dc184ce commit f9c3ef1
Show file tree
Hide file tree
Showing 6 changed files with 209 additions and 206 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ future_incompatible = { level = "deny", priority = -1 }
nonstandard_style = { level = "deny", priority = -1 }
unsafe_code = "deny"
non_ascii_idents = "deny"
unused_imports = "deny"
unused_imports = "warn"
unused_import_braces = "deny"
unreachable_code = "deny"
unreachable_patterns = "deny"
Expand Down
150 changes: 73 additions & 77 deletions crates/chia-bls/src/bls_cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,90 +81,86 @@ impl BlsCache {
}

#[cfg(feature = "py-bindings")]
mod python {
use super::*;
use pyo3::{
exceptions::PyValueError,
pybacked::PyBackedBytes,
types::{PyAnyMethods, PyList},
Bound, PyObject, PyResult,
};

use pyo3::{
exceptions::PyValueError,
pybacked::PyBackedBytes,
pymethods,
types::{PyAnyMethods, PyList},
Bound, PyObject, PyResult,
};

#[pymethods]
impl BlsCache {
#[new]
#[pyo3(signature = (size=None))]
pub fn init(size: Option<u32>) -> PyResult<Self> {
let Some(size) = size else {
return Ok(Self::default());
};

let Some(size) = NonZeroUsize::new(size as usize) else {
return Err(PyValueError::new_err(
"Cannot have a cache size less than one.",
));
};

Ok(Self::new(size))
}
#[cfg(feature = "py-bindings")]
#[pyo3::pymethods]
impl BlsCache {
#[new]
#[pyo3(signature = (size=None))]
pub fn init(size: Option<u32>) -> PyResult<Self> {
let Some(size) = size else {
return Ok(Self::default());
};

let Some(size) = NonZeroUsize::new(size as usize) else {
return Err(PyValueError::new_err(
"Cannot have a cache size less than one.",
));
};

Ok(Self::new(size))
}

#[pyo3(name = "aggregate_verify")]
pub fn py_aggregate_verify(
&mut self,
pks: &Bound<'_, PyList>,
msgs: &Bound<'_, PyList>,
sig: &Signature,
) -> PyResult<bool> {
let pks = pks
.iter()?
.map(|item| item?.extract())
.collect::<PyResult<Vec<PublicKey>>>()?;

let msgs = msgs
.iter()?
.map(|item| item?.extract())
.collect::<PyResult<Vec<PyBackedBytes>>>()?;

Ok(self.aggregate_verify(pks, msgs, sig))
}
#[pyo3(name = "aggregate_verify")]
pub fn py_aggregate_verify(
&mut self,
pks: &Bound<'_, PyList>,
msgs: &Bound<'_, PyList>,
sig: &Signature,
) -> PyResult<bool> {
let pks = pks
.iter()?
.map(|item| item?.extract())
.collect::<PyResult<Vec<PublicKey>>>()?;

let msgs = msgs
.iter()?
.map(|item| item?.extract())
.collect::<PyResult<Vec<PyBackedBytes>>>()?;

Ok(self.aggregate_verify(pks, msgs, sig))
}

#[pyo3(name = "len")]
pub fn py_len(&self) -> PyResult<usize> {
Ok(self.len())
}
#[pyo3(name = "len")]
pub fn py_len(&self) -> PyResult<usize> {
Ok(self.len())
}

#[pyo3(name = "items")]
pub fn py_items(&self, py: pyo3::Python<'_>) -> PyResult<PyObject> {
use pyo3::prelude::*;
use pyo3::types::PyBytes;
let ret = PyList::empty_bound(py);
for (key, value) in &self.cache {
ret.append((
PyBytes::new_bound(py, key),
PyBytes::new_bound(py, &value.to_bytes()),
))?;
}
Ok(ret.into())
#[pyo3(name = "items")]
pub fn py_items(&self, py: pyo3::Python<'_>) -> PyResult<PyObject> {
use pyo3::prelude::*;
use pyo3::types::PyBytes;
let ret = PyList::empty_bound(py);
for (key, value) in &self.cache {
ret.append((
PyBytes::new_bound(py, key),
PyBytes::new_bound(py, &value.to_bytes()),
))?;
}
Ok(ret.into())
}

#[pyo3(name = "update")]
pub fn py_update(&mut self, other: &Bound<'_, PyList>) -> PyResult<()> {
for item in other.borrow().iter()? {
let (key, value): (Vec<u8>, Vec<u8>) = item?.extract()?;
self.cache.put(
key.try_into()
.map_err(|_| PyValueError::new_err("invalid key"))?,
GTElement::from_bytes(
(&value[..])
.try_into()
.map_err(|_| PyValueError::new_err("invalid GTElement"))?,
),
);
}
Ok(())
#[pyo3(name = "update")]
pub fn py_update(&mut self, other: &Bound<'_, PyList>) -> PyResult<()> {
for item in other.borrow().iter()? {
let (key, value): (Vec<u8>, Vec<u8>) = item?.extract()?;
self.cache.put(
key.try_into()
.map_err(|_| PyValueError::new_err("invalid key"))?,
GTElement::from_bytes(
(&value[..])
.try_into()
.map_err(|_| PyValueError::new_err("invalid GTElement"))?,
),
);
}
Ok(())
}
}

Expand Down
45 changes: 23 additions & 22 deletions crates/chia-bls/src/gtelement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,33 +102,34 @@ impl Streamable for GTElement {
}

#[cfg(feature = "py-bindings")]
mod pybindings {
use super::*;
#[pyo3::pymethods]
impl GTElement {
#[classattr]
#[pyo3(name = "SIZE")]
pub const PY_SIZE: usize = Self::SIZE;

use chia_traits::{FromJsonDict, ToJsonDict};
use pyo3::{exceptions::PyValueError, prelude::*};
pub fn __str__(&self) -> String {
hex::encode(self.to_bytes())
}

#[pymethods]
impl GTElement {
#[classattr]
#[pyo3(name = "SIZE")]
const PY_SIZE: usize = Self::SIZE;
#[must_use]
pub fn __mul__(&self, rhs: &Self) -> Self {
let mut ret = self.clone();
ret *= rhs;
ret
}

fn __str__(&self) -> String {
hex::encode(self.to_bytes())
}
pub fn __imul__(&mut self, rhs: &Self) {
*self *= rhs;
}
}

#[must_use]
pub fn __mul__(&self, rhs: &Self) -> Self {
let mut ret = self.clone();
ret *= rhs;
ret
}
#[cfg(feature = "py-bindings")]
mod pybindings {
use super::*;

pub fn __imul__(&mut self, rhs: &Self) {
*self *= rhs;
}
}
use chia_traits::{FromJsonDict, ToJsonDict};
use pyo3::{exceptions::PyValueError, prelude::*};

impl ToJsonDict for GTElement {
fn to_json_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
Expand Down
84 changes: 43 additions & 41 deletions crates/chia-bls/src/public_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ impl DerivableKey for PublicKey {
}
}

pub const DST: &[u8] = b"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_";
pub(crate) const DST: &[u8] = b"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_AUG_";

pub fn hash_to_g1(msg: &[u8]) -> PublicKey {
hash_to_g1_with_dst(msg, DST)
Expand All @@ -297,57 +297,59 @@ pub fn hash_to_g1_with_dst(msg: &[u8], dst: &[u8]) -> PublicKey {
}

#[cfg(feature = "py-bindings")]
mod pybindings {
use super::*;
#[pyo3::pymethods]
impl PublicKey {
#[classattr]
pub const SIZE: usize = 48;

use crate::{parse_hex::parse_hex_string, GTElement, Signature};
#[new]
pub fn init() -> Self {
Self::default()
}

use chia_traits::{FromJsonDict, ToJsonDict};
use pyo3::prelude::*;
#[staticmethod]
#[pyo3(name = "generator")]
pub fn py_generator() -> Self {
Self::generator()
}

#[pymethods]
impl PublicKey {
#[classattr]
const SIZE: usize = 48;
pub fn pair(&self, other: &crate::Signature) -> crate::GTElement {
other.pair(self)
}

#[new]
fn init() -> Self {
Self::default()
}
#[pyo3(name = "get_fingerprint")]
pub fn py_get_fingerprint(&self) -> u32 {
self.get_fingerprint()
}

#[staticmethod]
#[pyo3(name = "generator")]
fn py_generator() -> Self {
Self::generator()
}
#[pyo3(name = "derive_unhardened")]
#[must_use]
pub fn py_derive_unhardened(&self, idx: u32) -> Self {
self.derive_unhardened(idx)
}

fn pair(&self, other: &Signature) -> GTElement {
other.pair(self)
}
pub fn __str__(&self) -> String {
hex::encode(self.to_bytes())
}

#[pyo3(name = "get_fingerprint")]
fn py_get_fingerprint(&self) -> u32 {
self.get_fingerprint()
}
#[must_use]
pub fn __add__(&self, rhs: &Self) -> Self {
self + rhs
}

#[pyo3(name = "derive_unhardened")]
fn py_derive_unhardened(&self, idx: u32) -> Self {
self.derive_unhardened(idx)
}
pub fn __iadd__(&mut self, rhs: &Self) {
*self += rhs;
}
}

fn __str__(&self) -> String {
hex::encode(self.to_bytes())
}
#[cfg(feature = "py-bindings")]
mod pybindings {
use super::*;

#[must_use]
pub fn __add__(&self, rhs: &Self) -> Self {
self + rhs
}
use crate::parse_hex::parse_hex_string;

pub fn __iadd__(&mut self, rhs: &Self) {
*self += rhs;
}
}
use chia_traits::{FromJsonDict, ToJsonDict};
use pyo3::prelude::*;

impl ToJsonDict for PublicKey {
fn to_json_dict(&self, py: Python<'_>) -> PyResult<PyObject> {
Expand Down
Loading

0 comments on commit f9c3ef1

Please sign in to comment.