Skip to content

Commit

Permalink
Merge pull request #109 from xch-dev/peer-close
Browse files Browse the repository at this point in the history
Add JS Peer and close function
  • Loading branch information
Rigidity authored Nov 3, 2024
2 parents 46db028 + 968736d commit 5d023f7
Show file tree
Hide file tree
Showing 8 changed files with 161 additions and 3 deletions.
14 changes: 14 additions & 0 deletions Cargo.lock

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

5 changes: 5 additions & 0 deletions crates/chia-sdk-client/src/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,11 @@ impl Peer {
self.0.sink.lock().await.send(message).await?;
Ok(receiver.await?)
}

pub async fn close(&self) -> Result<(), ClientError> {
self.0.sink.lock().await.close().await?;
Ok(())
}
}

impl Drop for PeerInner {
Expand Down
21 changes: 19 additions & 2 deletions napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,31 @@ workspace = true
crate-type = ["cdylib"]

[dependencies]
napi = { workspace = true, features = ["napi6"] }
napi = { workspace = true, features = ["napi6", "async"] }
napi-derive = { workspace = true }
chia-wallet-sdk = { workspace = true }
chia-wallet-sdk = { workspace = true, features = ["native-tls"] }
chia = { workspace = true }
clvmr = { workspace = true }
num-bigint = { workspace = true }
hex = { workspace = true }
paste = { workspace = true }
tokio = { workspace = true, features = ["sync"] }

[build-dependencies]
napi-build = "2.0.1"

[target.aarch64-unknown-linux-gnu.dependencies]
openssl = { version = "0.10.64", features = ["vendored"] }
openssl-sys = { version = "0.9.102", features = ["vendored"] }

[target.aarch64-unknown-linux-musl.dependencies]
openssl = { version = "0.10.64", features = ["vendored"] }
openssl-sys = { version = "0.9.102", features = ["vendored"] }

[target.x86_64-unknown-linux-gnu.dependencies]
openssl = { version = "0.10.64", features = ["vendored"] }
openssl-sys = { version = "0.9.102", features = ["vendored"] }

[target.x86_64-unknown-linux-musl.dependencies]
openssl = { version = "0.10.64", features = ["vendored"] }
openssl-sys = { version = "0.9.102", features = ["vendored"] }
13 changes: 13 additions & 0 deletions napi/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ export interface Spend {
puzzle: Program
solution: Program
}
export interface CoinState {
coin: Coin
spentHeight?: number
createdHeight?: number
}
export interface LineageProof {
parentParentCoinInfo: Uint8Array
parentInnerPuzzleHash?: Uint8Array
Expand Down Expand Up @@ -294,6 +299,14 @@ export declare class ClvmAllocator {
softfork(cost: bigint, rest: Program): Program
parseSoftfork(program: Program): Softfork | null
}
export declare class Tls {
constructor(certPath: string, keyPath: string)
}
export declare class Peer {
static connect(uri: string, tls: Tls, networkId: string): Promise<Peer>
requestChildren(coinId: Uint8Array): Promise<Array<CoinState>>
close(): Promise<void>
}
export declare class Program {
isAtom(): boolean
isPair(): boolean
Expand Down
4 changes: 3 additions & 1 deletion napi/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,13 +310,15 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}

const { ClvmAllocator, curryTreeHash, intToSignedBytes, signedBytesToInt, toCoinId, Program, Simulator, compareBytes, sha256, fromHexRaw, fromHex, toHex } = nativeBinding
const { ClvmAllocator, curryTreeHash, intToSignedBytes, signedBytesToInt, toCoinId, Tls, Peer, Program, Simulator, compareBytes, sha256, fromHexRaw, fromHex, toHex } = nativeBinding

module.exports.ClvmAllocator = ClvmAllocator
module.exports.curryTreeHash = curryTreeHash
module.exports.intToSignedBytes = intToSignedBytes
module.exports.signedBytesToInt = signedBytesToInt
module.exports.toCoinId = toCoinId
module.exports.Tls = Tls
module.exports.Peer = Peer
module.exports.Program = Program
module.exports.Simulator = Simulator
module.exports.compareBytes = compareBytes
Expand Down
34 changes: 34 additions & 0 deletions napi/src/coin_state.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use chia::protocol;
use napi::bindgen_prelude::*;

use crate::{
traits::{FromJs, IntoJs, IntoRust},
Coin,
};

#[napi(object)]
pub struct CoinState {
pub coin: Coin,
pub spent_height: Option<u32>,
pub created_height: Option<u32>,
}

impl IntoJs<CoinState> for protocol::CoinState {
fn into_js(self) -> Result<CoinState> {
Ok(CoinState {
coin: self.coin.into_js()?,
spent_height: self.spent_height,
created_height: self.created_height,
})
}
}

impl FromJs<CoinState> for protocol::CoinState {
fn from_js(value: CoinState) -> Result<Self> {
Ok(Self {
coin: value.coin.into_rust()?,
spent_height: value.spent_height,
created_height: value.created_height,
})
}
}
4 changes: 4 additions & 0 deletions napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ mod clvm;
mod clvm_value;
mod coin;
mod coin_spend;
mod coin_state;
mod lineage_proof;
mod nft;
mod peer;
mod program;
mod simulator;
mod traits;
Expand All @@ -22,7 +24,9 @@ mod utils;
pub use clvm::*;
pub use coin::*;
pub use coin_spend::*;
pub use coin_state::*;
pub use lineage_proof::*;
pub use nft::*;
pub use peer::*;
pub use program::*;
pub use utils::*;
69 changes: 69 additions & 0 deletions napi/src/peer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::net::SocketAddr;

use chia_wallet_sdk::{
self as sdk, connect_peer, create_native_tls_connector, load_ssl_cert, Connector,
};
use napi::bindgen_prelude::*;

use crate::{
traits::{IntoJs, IntoRust},
CoinState,
};

#[napi]
pub struct Tls(Connector);

#[napi]
impl Tls {
#[napi(constructor)]
pub fn new(cert_path: String, key_path: String) -> Result<Self> {
let cert = load_ssl_cert(&cert_path, &key_path)
.map_err(|error| Error::from_reason(error.to_string()))?;
let tls = create_native_tls_connector(&cert)
.map_err(|error| Error::from_reason(error.to_string()))?;
Ok(Self(tls))
}
}

#[napi]
pub struct Peer(sdk::Peer);

#[napi]
impl Peer {
#[napi(ts_args_type = "uri: string, tls: Tls, networkId: string")]
pub async fn connect(uri: String, tls: Reference<Tls>, network_id: String) -> Result<Self> {
let (peer, mut receiver) = connect_peer(
network_id,
tls.0.clone(),
uri.parse::<SocketAddr>()
.map_err(|error| Error::from_reason(error.to_string()))?,
)
.await
.map_err(|error| Error::from_reason(error.to_string()))?;

tokio::spawn(async move { while let Some(_message) = receiver.recv().await {} });

Ok(Self(peer))
}

#[napi]
pub async fn request_children(&self, coin_id: Uint8Array) -> Result<Vec<CoinState>> {
self.0
.request_children(coin_id.into_rust()?)
.await
.map_err(|error| Error::from_reason(error.to_string()))?
.coin_states
.into_iter()
.map(IntoJs::into_js)
.collect()
}

#[napi]
pub async fn close(&self) -> Result<()> {
self.0
.close()
.await
.map_err(|error| Error::from_reason(error.to_string()))?;
Ok(())
}
}

0 comments on commit 5d023f7

Please sign in to comment.