Skip to content

Commit

Permalink
Pyo3 0.22.5 (#120)
Browse files Browse the repository at this point in the history
* cargo updates

* migration to 0.22.5 and py-async-runtimes

* ScriptBuilder &Bound<T>

* PyUtxoEntries generator & utils

* PyOutputs generator & utils

* lints and cleanup
  • Loading branch information
smartgoo authored Nov 2, 2024
1 parent 2081aff commit b2cbfae
Show file tree
Hide file tree
Showing 33 changed files with 189 additions and 121 deletions.
58 changes: 26 additions & 32 deletions Cargo.lock

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

6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,8 @@ pbkdf2 = "0.12.2"
portable-atomic = { version = "1.5.1", features = ["float"] }
prost = "0.12.1"
# prost = "0.13.1"
pyo3 = { version = "0.21.0", features = ["multiple-pymethods"] }
pyo3-asyncio-0-21 = { version = "0.21", features = ["attributes", "tokio-runtime"] }
pyo3 = { version = "0.22.5", features = ["multiple-pymethods"] }
pyo3-async-runtimes = { version = "0.22", features = ["attributes", "tokio-runtime"] }
rand = "0.8.5"
rand_chacha = "0.3.1"
rand_core = { version = "0.6.4", features = ["std"] }
Expand All @@ -242,7 +242,7 @@ seqlock = "0.2.0"
serde = { version = "1.0.190", features = ["derive", "rc"] }
serde_bytes = "0.11.12"
serde_json = "1.0.107"
serde-pyobject = "0.3.0"
serde-pyobject = "0.4.0"
serde_repr = "0.1.18"
serde-value = "0.7.0"
serde-wasm-bindgen = "0.6.1"
Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ cfg_if::cfg_if! {
pub use pyo3::{
exceptions::PyException,
prelude::*,
types::{IntoPyDict, PyDict},
types::PyDict,
};
pub use serde_pyobject;
pub use std::str::FromStr;
Expand Down
1 change: 1 addition & 0 deletions consensus/client/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ impl TransactionInput {
#[pymethods]
impl TransactionInput {
#[new]
#[pyo3(signature = (previous_outpoint, signature_script, sequence, sig_op_count, utxo=None))]
pub fn constructor_py(
previous_outpoint: TransactionOutpoint,
signature_script: PyBinary,
Expand Down
10 changes: 4 additions & 6 deletions consensus/client/src/outpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,13 +176,11 @@ impl TryFrom<&JsValue> for TransactionOutpoint {
}

#[cfg(feature = "py-sdk")]
impl TryFrom<&PyDict> for TransactionOutpoint {
impl TryFrom<&Bound<'_, PyDict>> for TransactionOutpoint {
type Error = PyErr;
fn try_from(dict: &PyDict) -> PyResult<Self> {
Python::with_gil(|py| {
let inner: TransactionOutpointInner = serde_pyobject::from_pyobject(dict.into_py_dict_bound(py))?;
Ok(TransactionOutpoint { inner: Arc::new(inner) })
})
fn try_from(dict: &Bound<PyDict>) -> PyResult<Self> {
let inner: TransactionOutpointInner = serde_pyobject::from_pyobject(dict.clone())?;
Ok(TransactionOutpoint { inner: Arc::new(inner) })
}
}

Expand Down
14 changes: 7 additions & 7 deletions consensus/client/src/utxo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,19 +559,19 @@ impl TryCastFromJs for UtxoEntryReference {
}

#[cfg(feature = "py-sdk")]
impl TryFrom<&PyDict> for UtxoEntryReference {
impl TryFrom<&Bound<'_, PyDict>> for UtxoEntryReference {
type Error = PyErr;
fn try_from(dict: &PyDict) -> PyResult<Self> {
fn try_from(dict: &Bound<PyDict>) -> PyResult<Self> {
let address = Address::try_from(
dict.get_item("address")?.ok_or_else(|| PyException::new_err("Key `address` not present"))?.extract::<String>()?,
)?;

let outpoint: &PyDict =
dict.get_item("outpoint")?.ok_or_else(|| PyException::new_err("Key `outpoint` not present"))?.downcast()?;
let outpoint = TransactionOutpoint::try_from(outpoint)?;
let outpoint = TransactionOutpoint::try_from(
dict.get_item("outpoint")?.ok_or_else(|| PyException::new_err("Key `outpoint` not present"))?.downcast::<PyDict>()?,
)?;

let utxo_entry: &PyDict =
dict.get_item("utxoEntry")?.ok_or_else(|| PyException::new_err("Key `utxoEntry` not present"))?.extract()?;
let utxo_entry_value = dict.get_item("utxoEntry")?.ok_or_else(|| PyException::new_err("Key `utxoEntry` not present"))?;
let utxo_entry = utxo_entry_value.downcast::<PyDict>()?;

let amount: u64 = utxo_entry.get_item("amount")?.ok_or_else(|| PyException::new_err("Key `amount` not present"))?.extract()?;

Expand Down
3 changes: 2 additions & 1 deletion consensus/core/src/hashing/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use wasm_bindgen::prelude::*;

/// Kaspa Sighash types allowed by consensus
/// @category Consensus
#[cfg_attr(feature = "py-sdk", pyclass)]
#[derive(PartialEq)]
#[cfg_attr(feature = "py-sdk", pyclass(eq, eq_int))]
#[wasm_bindgen]
#[derive(Clone, Copy)]
pub enum SighashType {
Expand Down
6 changes: 3 additions & 3 deletions crypto/txscript/src/python/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ impl ScriptBuilder {
Ok(builder)
}

pub fn add_op(&self, op: Bound<PyAny>) -> PyResult<ScriptBuilder> {
pub fn add_op(&self, op: &Bound<PyAny>) -> PyResult<ScriptBuilder> {
let op = extract_ops(op)?;
let mut inner = self.inner();
inner.add_op(op[0]).map_err(|err| pyo3::exceptions::PyException::new_err(format!("{}", err)))?;

Ok(self.clone())
}

pub fn add_ops(&self, opcodes: Bound<PyAny>) -> PyResult<ScriptBuilder> {
pub fn add_ops(&self, opcodes: &Bound<PyAny>) -> PyResult<ScriptBuilder> {
let ops = extract_ops(opcodes)?;
self.inner().add_ops(&ops.as_slice()).map_err(|err| pyo3::exceptions::PyException::new_err(format!("{}", err)))?;

Expand Down Expand Up @@ -134,7 +134,7 @@ impl ScriptBuilder {
}

// PY-TODO change to PyOpcode struct and handle similar to PyBinary
fn extract_ops(input: Bound<PyAny>) -> PyResult<Vec<u8>> {
fn extract_ops(input: &Bound<PyAny>) -> PyResult<Vec<u8>> {
if let Ok(opcode) = extract_op(&input) {
// Single u8 or Opcodes variant
Ok(vec![opcode])
Expand Down
4 changes: 2 additions & 2 deletions crypto/txscript/src/wasm/opcodes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ pub use wasm_bindgen::prelude::*;
/// Kaspa Transaction Script Opcodes
/// @see {@link ScriptBuilder}
/// @category Consensus
#[derive(Clone)]
#[cfg_attr(feature = "py-sdk", pyclass)]
#[derive(Clone, PartialEq)]
#[cfg_attr(feature = "py-sdk", pyclass(eq, eq_int))]
#[wasm_bindgen]
pub enum Opcodes {
OpFalse = 0x00,
Expand Down
6 changes: 3 additions & 3 deletions python/core/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub struct PyBinary {
}

impl<'a> FromPyObject<'a> for PyBinary {
fn extract(value: &'a PyAny) -> PyResult<Self> {
fn extract_bound(value: &Bound<PyAny>) -> PyResult<Self> {
if let Ok(str) = value.extract::<String>() {
// Python `str` (of valid hex)
let mut data = vec![0u8; str.len() / 2];
Expand All @@ -28,9 +28,9 @@ impl<'a> FromPyObject<'a> for PyBinary {
}
}

impl TryFrom<Bound<'_, PyAny>> for PyBinary {
impl TryFrom<&Bound<'_, PyAny>> for PyBinary {
type Error = PyErr;
fn try_from(value: Bound<PyAny>) -> Result<Self, Self::Error> {
fn try_from(value: &Bound<PyAny>) -> Result<Self, Self::Error> {
if let Ok(str) = value.extract::<String>() {
// Python `str` (of valid hex)
let mut data = vec![0u8; str.len() / 2];
Expand Down
File renamed without changes.
6 changes: 4 additions & 2 deletions python/examples/rpc/all_calls.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@


async def main():
client = RpcClient(resolver=Resolver(), network_id="testnet-11")
client = RpcClient(resolver=Resolver())
await client.connect()

###
Expand Down Expand Up @@ -129,7 +129,7 @@ async def main():
"includeOrphanPool": False,
"filterTransactionPool": False,
})

await client.get_mempool_entries_by_addresses(request={
"addresses": addresses,
"includeOrphanPool": False,
Expand Down Expand Up @@ -169,6 +169,8 @@ async def main():

# await client.unban(request)

await client.disconnect()

if __name__ == "__main__":
asyncio.run(main())

2 changes: 1 addition & 1 deletion python/examples/transactions/krc20_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@


async def main():
client = RpcClient(resolver=Resolver(), network='testnet', network_suffix=10)
client = RpcClient(resolver=Resolver(), network_id='testnet-10')
await client.connect()

private_key = PrivateKey('389840d7696e89c38856a066175e8e92697f0cf182b854c883237a50acaf1f69')
Expand Down
6 changes: 3 additions & 3 deletions python/examples/transactions/single_transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@
async def main():
private_key = PrivateKey("389840d7696e89c38856a066175e8e92697f0cf182b854c883237a50acaf1f69")
keypair = private_key.to_keypair()
address = keypair.to_address(network="kaspatest")
address = keypair.to_address(network="testnet")
print(address.to_string())

client = RpcClient(resolver=Resolver(), network="testnet", network_suffix=10)
client = RpcClient(resolver=Resolver(), network_id="testnet-10")
await client.connect()
print(f"Client is connected: {client.is_connected}")

Expand All @@ -28,7 +28,7 @@ async def main():
fee_rates = await client.get_fee_estimate()
fee = int(fee_rates["estimate"]["priorityBucket"]["feerate"])

fee = max(fee, 2000)
fee = max(fee, 5000)
output_amount = int(total - fee)

change_address = address
Expand Down
2 changes: 1 addition & 1 deletion python/macros/src/py_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl ToTokens for PyAsync {

quote! {
let __fut__ = #block;
let __py_fut__ = pyo3_asyncio_0_21::tokio::future_into_py(#py, __fut__)?;
let __py_fut__ = pyo3_async_runtimes::tokio::future_into_py(#py, __fut__)?;
pyo3::prelude::Python::with_gil(|py| Ok(__py_fut__.into_py(#py)))
}
.to_tokens(tokens);
Expand Down
Loading

0 comments on commit b2cbfae

Please sign in to comment.