Skip to content

Commit

Permalink
Clean up Python interface for NetworkId, NetworkType (#115)
Browse files Browse the repository at this point in the history
* NetworkId, NetworkType interface cleanup

* .pyi upate
  • Loading branch information
smartgoo authored Oct 27, 2024
1 parent 676fd9d commit 7979002
Show file tree
Hide file tree
Showing 15 changed files with 40 additions and 48 deletions.
6 changes: 3 additions & 3 deletions consensus/client/src/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,13 +299,13 @@ impl Transaction {
inputs: Vec<TransactionInput>,
outputs: Vec<TransactionOutput>,
lock_time: u64,
subnetwork_id: String,
subnetwork_id: PyBinary,
gas: u64,
payload: PyBinary,
mass: u64,
) -> PyResult<Self> {
let subnetwork_id = Vec::from_hex(&subnetwork_id)
.map_err(|err| PyException::new_err(format!("subnetwork_id decode error: {}", err)))?
let subnetwork_id: SubnetworkId = subnetwork_id
.data
.as_slice()
.try_into()
.map_err(|err| PyException::new_err(format!("subnetwork_id conversion error: {}", err)))?;
Expand Down
2 changes: 1 addition & 1 deletion consensus/client/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ pub fn address_from_script_public_key(script_public_key: &ScriptPublicKeyT, netw
#[pyfunction]
#[pyo3(name = "address_from_script_public_key")]
pub fn address_from_script_public_key_py(script_public_key: &ScriptPublicKey, network: &str) -> PyResult<Address> {
match standard::extract_script_pub_key_address(script_public_key, network.try_into()?) {
match standard::extract_script_pub_key_address(script_public_key, NetworkType::from_str(network)?.try_into()?) {
Ok(address) => Ok(address),
Err(err) => Err(pyo3::exceptions::PyException::new_err(format!("{}", err))),
}
Expand Down
7 changes: 7 additions & 0 deletions consensus/core/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,13 @@ impl From<NetworkIdError> for JsValue {
}
}

#[cfg(feature = "py-sdk")]
impl From<NetworkIdError> for PyErr {
fn from(value: NetworkIdError) -> PyErr {
PyException::new_err(value.to_string())
}
}

///
/// NetworkId is a unique identifier for a kaspa network instance.
/// It is composed of a network type and an optional suffix.
Expand Down
4 changes: 2 additions & 2 deletions python/examples/addresses.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ def demo_generate_address_from_public_key_hex_string():
def demo_generate_address_from_private_key_hex_string():
private_key = PrivateKey("b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef")
print("\nGiven private key b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef")
print(private_key.to_keypair().to_address("kaspa").to_string())
print(private_key.to_keypair().to_address("mainnet").to_string())

def demo_generate_random():
keypair = Keypair.random()
print("\nRandom Generation")
print(keypair.private_key)
print(keypair.public_key)
print(keypair.to_address("kaspa").to_string())
print(keypair.to_address("mainnet").to_string())

if __name__ == "__main__":
demo_generate_address_from_public_key_hex_string()
Expand Down
2 changes: 1 addition & 1 deletion python/examples/rpc_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="testnet", network_suffix=11)
client = RpcClient(resolver=Resolver(), network_id="testnet-11")
await client.connect()

###
Expand Down
2 changes: 1 addition & 1 deletion python/examples/rpc_subscriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def rpc_subscriptions(client: RpcClient):
await client.unsubscribe_new_block_template()

async def main():
client = RpcClient(resolver=Resolver(), network="testnet", network_suffix=10)
client = RpcClient(resolver=Resolver(), network_id="testnet-11")

await client.connect()
print(f"Client is connected: {client.is_connected}")
Expand Down
2 changes: 1 addition & 1 deletion python/examples/transactions/krc20_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async def main():
script.add_op(Opcodes.OpEndIf)
print(f'Script: {script.to_string()}')

p2sh_address = address_from_script_public_key(script.create_pay_to_script_hash_script(), 'kaspatest')
p2sh_address = address_from_script_public_key(script.create_pay_to_script_hash_script(), 'testnet')
print(f'P2SH Address: {p2sh_address.to_string()}')

utxos = await client.get_utxos_by_addresses(request={'addresses': [address]})
Expand Down
10 changes: 5 additions & 5 deletions python/kaspa.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -918,16 +918,16 @@ class Resolver:

def urls(self) -> list[str]: ...

def get_node(self, encoding: str, network: str, network_suffix: Optional[int]) -> dict: ...
def get_node(self, encoding: str, network_id: Optional[str]) -> dict: ...

def get_url(self, encoding: str, network: str, network_suffix: Optional[int]) -> str: ...
def get_url(self, encoding: str, network_id: Optional[str]) -> str: ...

def connect(self, encoding: str, network: str, network_suffix: Optional[int]) -> RpcClient: ...
def connect(self, encoding: str, network_id: Optional[str]) -> RpcClient: ...


class RpcClient:

def __init__(self, resolver: Optional[Resolver], url: Optional[str], encoding: Optional[str], network: Optional[str], network_suffix: Optional[str]) -> None: ...
def __init__(self, resolver: Optional[Resolver], url: Optional[str], encoding: Optional[str], network_id: Optional[str]) -> None: ...

@property
def url(self) -> str: ...
Expand All @@ -937,7 +937,7 @@ class RpcClient:

def set_resolver(self, Resolver) -> None: ...

def set_network_id(self, network: str, network_suffix: Optional[int]) -> None: ...
def set_network_id(self, network_id: Optional[str]) -> None: ...

@property
def is_connected(self) -> bool: ...
Expand Down
12 changes: 5 additions & 7 deletions rpc/wrpc/python/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::resolver::{into_network_id, Resolver};
use crate::resolver::Resolver;
use ahash::AHashMap;
use futures::*;
use kaspa_addresses::Address;
Expand Down Expand Up @@ -157,12 +157,10 @@ impl RpcClient {
resolver: Option<Resolver>,
url: Option<String>,
encoding: Option<String>,
network: Option<String>,
network_suffix: Option<u32>,
network_id: Option<String>,
) -> PyResult<RpcClient> {
let encoding = WrpcEncoding::from_str(&encoding.unwrap_or("borsh".to_string())).unwrap();
let network = network.unwrap_or(String::from("mainnet"));
let network_id = into_network_id(&network, network_suffix)?;
let network_id = NetworkId::from_str(&network_id.unwrap_or(String::from("mainnet")))?;

Ok(Self::new(resolver, url, Some(encoding), Some(network_id))?)
}
Expand All @@ -182,8 +180,8 @@ impl RpcClient {
Ok(())
}

fn set_network_id(&self, network: String, network_suffix: Option<u32>) -> PyResult<()> {
let network_id = into_network_id(&network, network_suffix)?;
fn set_network_id(&self, network_id: String) -> PyResult<()> {
let network_id = NetworkId::from_str(&network_id)?;
self.inner.client.set_network_id(&network_id)?;
Ok(())
}
Expand Down
25 changes: 5 additions & 20 deletions rpc/wrpc/python/src/resolver.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use kaspa_consensus_core::network::{NetworkId, NetworkType};
use kaspa_consensus_core::network::NetworkId;
use kaspa_python_macros::py_async;
use kaspa_wrpc_client::{Resolver as NativeResolver, WrpcEncoding};
use pyo3::exceptions::PyException;
use pyo3::prelude::*;
use std::{str::FromStr, sync::Arc};

Expand Down Expand Up @@ -36,11 +35,9 @@ impl Resolver {
self.resolver.urls().unwrap_or_default().into_iter().map(|url| (*url).clone()).collect::<Vec<_>>()
}

fn get_node(&self, py: Python, encoding: String, network: String, network_suffix: Option<u32>) -> PyResult<Py<PyAny>> {
fn get_node(&self, py: Python, encoding: String, network_id: &str) -> PyResult<Py<PyAny>> {
let encoding = WrpcEncoding::from_str(encoding.as_str()).unwrap();

// TODO find better way of accepting NetworkId type from Python
let network_id = into_network_id(&network, network_suffix)?;
let network_id = NetworkId::from_str(network_id)?;

let resolver = self.resolver.clone();
py_async! {py, async move {
Expand All @@ -51,11 +48,9 @@ impl Resolver {
}}
}

fn get_url(&self, py: Python, encoding: String, network: String, network_suffix: Option<u32>) -> PyResult<Py<PyAny>> {
fn get_url(&self, py: Python, encoding: String, network_id: &str) -> PyResult<Py<PyAny>> {
let encoding = WrpcEncoding::from_str(encoding.as_str()).unwrap();

// TODO find better way of accepting NetworkId type from Python
let network_id = into_network_id(&network, network_suffix)?;
let network_id = NetworkId::from_str(network_id)?;

let resolver = self.resolver.clone();
py_async! {py, async move {
Expand All @@ -72,13 +67,3 @@ impl From<Resolver> for NativeResolver {
resolver.resolver
}
}

pub fn into_network_id(network: &str, network_suffix: Option<u32>) -> Result<NetworkId, PyErr> {
let network_type = NetworkType::from_str(network).map_err(|_| PyErr::new::<PyException, _>("Invalid network type"))?;
NetworkId::try_from(network_type).or_else(|_| {
network_suffix.map_or_else(
|| Err(PyErr::new::<PyException, _>("Network suffix required for this network")),
|suffix| Ok(NetworkId::with_suffix(network_type, suffix)),
)
})
}
2 changes: 1 addition & 1 deletion wallet/core/src/python/tx/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn create_transaction_py(
#[pyo3(name = "create_transactions")]
pub fn create_transactions_py<'a>(
py: Python<'a>,
network_id: String, // TODO this is wrong
network_id: String,
entries: Vec<&PyDict>,
outputs: Vec<&PyDict>,
change_address: Address,
Expand Down
2 changes: 2 additions & 0 deletions wallet/keys/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pub use borsh::{BorshDeserialize, BorshSerialize};
pub use js_sys::Array;
pub use kaspa_addresses::{Address, Version as AddressVersion};
pub use kaspa_bip32::{ChildNumber, ExtendedPrivateKey, ExtendedPublicKey, SecretKey};
#[cfg(feature = "py-sdk")]
pub use kaspa_consensus_core::network::NetworkType;
pub use kaspa_consensus_core::network::{NetworkId, NetworkTypeT};
pub use kaspa_utils::hex::*;
pub use kaspa_wasm_core::types::*;
Expand Down
4 changes: 2 additions & 2 deletions wallet/keys/src/keypair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,14 @@ impl Keypair {
#[pyo3(name = "to_address")]
pub fn to_address_py(&self, network: &str) -> PyResult<Address> {
let payload = &self.xonly_public_key.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKey, payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKey, payload);
Ok(address)
}

#[pyo3(name = "to_address_ecdsa")]
pub fn to_address_ecdsa_py(&self, network: &str) -> PyResult<Address> {
let payload = &self.public_key.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKeyECDSA, payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKeyECDSA, payload);
Ok(address)
}

Expand Down
4 changes: 2 additions & 2 deletions wallet/keys/src/privatekey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,15 +118,15 @@ impl PrivateKey {
let public_key = secp256k1::PublicKey::from_secret_key_global(&self.inner);
let (x_only_public_key, _) = public_key.x_only_public_key();
let payload = x_only_public_key.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKey, &payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKey, &payload);
Ok(address)
}

#[pyo3(name = "to_address_ecdsa")]
pub fn to_address_ecdsa_py(&self, network: &str) -> PyResult<Address> {
let public_key = secp256k1::PublicKey::from_secret_key_global(&self.inner);
let payload = public_key.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKeyECDSA, &payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKeyECDSA, &payload);
Ok(address)
}

Expand Down
4 changes: 2 additions & 2 deletions wallet/keys/src/publickey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,14 +305,14 @@ impl XOnlyPublicKey {
#[pyo3(name = "to_address")]
pub fn to_address_py(&self, network: &str) -> PyResult<Address> {
let payload = &self.inner.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKey, payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKey, payload);
Ok(address)
}

#[pyo3(name = "to_address_ecdsa")]
pub fn to_address_ecdsa_py(&self, network: &str) -> PyResult<Address> {
let payload = &self.inner.serialize();
let address = Address::new(network.try_into()?, AddressVersion::PubKeyECDSA, payload);
let address = Address::new(NetworkType::from_str(network)?.try_into()?, AddressVersion::PubKeyECDSA, payload);
Ok(address)
}

Expand Down

0 comments on commit 7979002

Please sign in to comment.