Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
58 changes: 58 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,16 @@ export interface ServerCoin {
p2PuzzleHash: Buffer
memoUrls: Array<string>
}
/** Object returned by simulator_new_puzzle, containing both the puzzle hash and the puzzle reveal. */
export interface SimulatorPuzzle {
puzzleHash: Buffer
puzzleReveal: Buffer
}
export interface BlsPair {
sk: Buffer
pk: Buffer
puzzleHash: Buffer
}
/**
* Creates a new lineage proof.
*
Expand Down Expand Up @@ -432,6 +442,26 @@ export declare function getMainnetGenesisChallenge(): Buffer
* @returns {Buffer} The testnet11 genesis challenge.
*/
export declare function getTestnet11GenesisChallenge(): Buffer
/**
* Creates a new puzzle and its hash using the simulator.
*
* @param {BigInt} value - The value to use for the puzzle.
* @returns {Promise<js::SimulatorPuzzle>} The puzzle hash and reveal.
*/
export declare function simulatorNewPuzzle(value: bigint): Promise<SimulatorPuzzle>
/**
* Creates a new BlsPair.
*
* @param {BigInt} value - The value to use to initialize the pair.
* @returns {Promise<js::BlsPair>} The BlsPair.
*/
export declare function simulatorNewBlspair(value: bigint): BlsPair
/**
* Creates a new simulator program.
*
* @returns {Promise<Buffer>} The program.
*/
export declare function simulatorNewProgram(pk: Buffer): Buffer
export declare class Tls {
/**
* Creates a new TLS connector.
Expand Down Expand Up @@ -460,6 +490,34 @@ export declare class Peer {
* @returns {Promise<UnspentCoinsResponse>} The unspent coins response.
*/
getAllUnspentCoins(puzzleHash: Buffer, previousHeight: number | undefined | null, previousHeaderHash: Buffer): Promise<UnspentCoinsResponse>
/**
* Creates a new coin with the specified puzzle hash and amount using the simulator.
*
* @param {Buffer} puzzleHash - The puzzle hash for the new coin.
* @param {BigInt} amount - The amount for the new coin.
* @returns {Promise<Coin>} The newly created coin.
*/
simulatorNewCoin(puzzleHash: Buffer, amount: bigint): Promise<Coin>
/**
* Gets the current height of the simulator.
*
* @returns {Promise<u32>} The current height.
*/
simulatorHeight(): Promise<number>
/**
* Gets the coin state for a given coin ID.
*
* @param {Buffer} coinId - The coin ID to look up.
* @returns {Promise<CoinState | null>} The coin state if found.
*/
simulatorCoinState(coinId: Buffer): Promise<CoinState | null>
/**
* Gets the header hash at the specified height.
*
* @param {u32} height - The height to get the header hash for.
* @returns {Promise<Buffer>} The header hash.
*/
headerHash(height: number): Promise<Buffer>
/**
* Retrieves all hinted coin states that are unspent on the chain. Note that coins part of spend bundles that are pending in the mempool will also be included.
*
Expand Down
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ if (!nativeBinding) {
throw new Error(`Failed to load native binding`)
}

const { newLineageProof, newEveProof, Tls, Peer, PeerType, selectCoins, sendXch, morphLauncherId, createServerCoin, mintStore, oracleSpend, addFee, masterPublicKeyToWalletSyntheticKey, masterPublicKeyToFirstPuzzleHash, masterSecretKeyToWalletSyntheticSecretKey, secretKeyToPublicKey, puzzleHashToAddress, addressToPuzzleHash, adminDelegatedPuzzleFromKey, writerDelegatedPuzzleFromKey, oracleDelegatedPuzzle, signCoinSpends, getCoinId, updateStoreMetadata, updateStoreOwnership, meltStore, signMessage, verifySignedMessage, syntheticKeyToPuzzleHash, getCost, getMainnetGenesisChallenge, getTestnet11GenesisChallenge } = nativeBinding
const { newLineageProof, newEveProof, Tls, Peer, PeerType, selectCoins, sendXch, morphLauncherId, createServerCoin, mintStore, oracleSpend, addFee, masterPublicKeyToWalletSyntheticKey, masterPublicKeyToFirstPuzzleHash, masterSecretKeyToWalletSyntheticSecretKey, secretKeyToPublicKey, puzzleHashToAddress, addressToPuzzleHash, adminDelegatedPuzzleFromKey, writerDelegatedPuzzleFromKey, oracleDelegatedPuzzle, signCoinSpends, getCoinId, updateStoreMetadata, updateStoreOwnership, meltStore, signMessage, verifySignedMessage, syntheticKeyToPuzzleHash, getCost, getMainnetGenesisChallenge, getTestnet11GenesisChallenge, simulatorNewPuzzle, simulatorNewBlspair, simulatorNewProgram } = nativeBinding

module.exports.newLineageProof = newLineageProof
module.exports.newEveProof = newEveProof
Expand Down Expand Up @@ -344,3 +344,6 @@ module.exports.syntheticKeyToPuzzleHash = syntheticKeyToPuzzleHash
module.exports.getCost = getCost
module.exports.getMainnetGenesisChallenge = getMainnetGenesisChallenge
module.exports.getTestnet11GenesisChallenge = getTestnet11GenesisChallenge
module.exports.simulatorNewPuzzle = simulatorNewPuzzle
module.exports.simulatorNewBlspair = simulatorNewBlspair
module.exports.simulatorNewProgram = simulatorNewProgram
2 changes: 1 addition & 1 deletion npm/darwin-arm64/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver-darwin-arm64",
"version": "0.1.30",
"version": "0.1.31",
"repository": {
"type": "git",
"url": "https://github.com/DIG-Network/DataLayer-Driver"
Expand Down
2 changes: 1 addition & 1 deletion npm/darwin-x64/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver-darwin-x64",
"version": "0.1.30",
"version": "0.1.31",
"repository": {
"type": "git",
"url": "https://github.com/DIG-Network/DataLayer-Driver"
Expand Down
2 changes: 1 addition & 1 deletion npm/linux-arm64-gnu/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver-linux-arm64-gnu",
"version": "0.1.30",
"version": "0.1.31",
"repository": {
"type": "git",
"url": "https://github.com/DIG-Network/DataLayer-Driver"
Expand Down
2 changes: 1 addition & 1 deletion npm/linux-x64-gnu/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver-linux-x64-gnu",
"version": "0.1.30",
"version": "0.1.31",
"repository": {
"type": "git",
"url": "https://github.com/DIG-Network/DataLayer-Driver"
Expand Down
2 changes: 1 addition & 1 deletion npm/win32-x64-msvc/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver-win32-x64-msvc",
"version": "0.1.30",
"version": "0.1.31",
"repository": {
"type": "git",
"url": "https://github.com/DIG-Network/DataLayer-Driver"
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/datalayer-driver",
"version": "0.1.30",
"version": "0.1.31",
"main": "index.js",
"types": "index.d.ts",
"repository": {
Expand Down
38 changes: 38 additions & 0 deletions src/conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,44 @@ impl ToJs<js::Coin> for rust::Coin {
}
}

impl FromJs<js::SimulatorPuzzle> for rust::SimulatorPuzzle {
fn from_js(value: js::SimulatorPuzzle) -> Result<Self> {
Ok(Self {
puzzle_hash: Bytes32::from_js(value.puzzle_hash)?,
puzzle_reveal: Program::from_js(value.puzzle_reveal)?,
})
}
}

impl ToJs<js::SimulatorPuzzle> for rust::SimulatorPuzzle {
fn to_js(&self) -> Result<js::SimulatorPuzzle> {
Ok(js::SimulatorPuzzle {
puzzle_reveal: self.puzzle_reveal.to_js()?,
puzzle_hash: self.puzzle_hash.to_js()?,
})
}
}

impl FromJs<js::BlsPair> for rust::BlsPair {
fn from_js(value: js::BlsPair) -> Result<Self> {
Ok(Self {
puzzle_hash: Bytes32::from_js(value.puzzle_hash)?,
pk: PublicKey::from_js(value.pk)?,
sk: SecretKey::from_js(value.sk)?,
})
}
}

impl ToJs<js::BlsPair> for rust::BlsPair {
fn to_js(&self) -> Result<js::BlsPair> {
Ok(js::BlsPair {
puzzle_hash: self.puzzle_hash.to_js()?,
pk: self.pk.to_js()?,
sk: self.sk.to_js()?,
})
}
}

impl FromJs<js::CoinState> for rust::CoinState {
fn from_js(value: js::CoinState) -> Result<Self> {
Ok(Self {
Expand Down
14 changes: 14 additions & 0 deletions src/js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ pub struct ServerCoin {
pub memo_urls: Vec<String>,
}

#[napi(object)]
/// Object returned by simulator_new_puzzle, containing both the puzzle hash and the puzzle reveal.
pub struct SimulatorPuzzle {
pub puzzle_hash: Buffer,
pub puzzle_reveal: Buffer,
}

#[napi(object)]
pub struct BlsPair {
pub sk: Buffer,
pub pk: Buffer,
pub puzzle_hash: Buffer,
}

pub fn err<T>(error: T) -> napi::Error
where
T: ToString,
Expand Down
114 changes: 111 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ use chia::traits::Streamable;
use chia_wallet_sdk::client::{
connect_peer, create_native_tls_connector, load_ssl_cert, Connector, PeerOptions,
};
use chia_wallet_sdk::test::PeerSimulator;
use chia_wallet_sdk::prelude::AggSigMe;
use chia_wallet_sdk::test::{to_program, to_puzzle, PeerSimulator};
use chia_wallet_sdk::types::{MAINNET_CONSTANTS, TESTNET11_CONSTANTS};
use chia_wallet_sdk::utils::Address;
use chia_wallet_sdk::{
Expand Down Expand Up @@ -460,6 +461,7 @@ pub struct Peer {
inner: Arc<RustPeer>,
peak: Arc<Mutex<Option<NewPeakWallet>>>,
coin_listeners: Arc<Mutex<HashMap<RustBytes32, UnboundedSender<()>>>>,
sim: Option<Arc<Mutex<PeerSimulator>>>,
}

#[napi]
Expand Down Expand Up @@ -491,11 +493,13 @@ impl Peer {
/// @returns {Promise<Peer>} A new Peer instance.
pub async fn new(node_uri: String, peer_type: PeerType, tls: &Tls) -> napi::Result<Self> {
let (peer, mut receiver);
let sim: Option<Arc<Mutex<PeerSimulator>>>;
if peer_type == PeerType::Simulator {
let sim = PeerSimulator::new().await.map_err(js::err)?;
let (p, r) = sim.connect_raw().await.map_err(js::err)?;
let simulator = PeerSimulator::new().await.map_err(js::err)?;
let (p, r) = simulator.connect_raw().await.map_err(js::err)?;
peer = p;
receiver = r;
sim = Some(Arc::new(Mutex::new(simulator)));
} else {
let (p, r) = connect_peer(
peer_type.as_str().to_string(),
Expand All @@ -511,6 +515,7 @@ impl Peer {
.map_err(js::err)?;
peer = p;
receiver = r;
sim = None;
}

let inner = Arc::new(peer);
Expand Down Expand Up @@ -555,6 +560,7 @@ impl Peer {
inner,
peak,
coin_listeners,
sim,
})
}

Expand Down Expand Up @@ -585,6 +591,68 @@ impl Peer {
resp.to_js()
}

#[napi]
/// Creates a new coin with the specified puzzle hash and amount using the simulator.
///
/// @param {Buffer} puzzleHash - The puzzle hash for the new coin.
/// @param {BigInt} amount - The amount for the new coin.
/// @returns {Promise<Coin>} The newly created coin.
pub async fn simulator_new_coin(
&self,
puzzle_hash: Buffer,
amount: BigInt,
) -> napi::Result<Coin> {
let puzzle_hash = RustBytes32::from_js(puzzle_hash)?;
let amount = u64::from_js(amount)?;
match &self.sim {
Some(sim) => {
let coin = sim.lock().await.mint_coin(puzzle_hash, amount).await;
coin.to_js()
}
None => Err(js::err("Simulator is not available for this peer type")),
}
}

#[napi]
/// Gets the current height of the simulator.
///
/// @returns {Promise<u32>} The current height.
pub async fn simulator_height(&self) -> napi::Result<u32> {
match &self.sim {
Some(sim) => Ok(sim.lock().await.height().await),
None => Err(js::err("Simulator is not available for this peer type")),
}
}

#[napi]
/// Gets the coin state for a given coin ID.
///
/// @param {Buffer} coinId - The coin ID to look up.
/// @returns {Promise<CoinState | null>} The coin state if found.
pub async fn simulator_coin_state(&self, coin_id: Buffer) -> napi::Result<Option<CoinState>> {
let coin_id = RustBytes32::from_js(coin_id)?;

match &self.sim {
Some(sim) => match sim.lock().await.coin_state(coin_id).await {
Some(state) => Ok(Some(state.to_js()?)),
None => Ok(None),
},
None => Err(js::err("Simulator is not available for this peer type")),
}
}

#[napi]
/// Gets the header hash at the specified height.
///
/// @param {u32} height - The height to get the header hash for.
/// @returns {Promise<Buffer>} The header hash.
pub async fn header_hash(&self, height: u32) -> napi::Result<Buffer> {
match &self.sim {
Some(sim) => sim.lock().await.header_hash(height).await.to_js(),
None => Err(js::err("Simulator is not available for this peer type")),
}
}

#[napi]
/// Retrieves all hinted coin states that are unspent on the chain. Note that coins part of spend bundles that are pending in the mempool will also be included.
///
Expand Down Expand Up @@ -1509,3 +1577,43 @@ pub fn get_mainnet_genesis_challenge() -> napi::Result<Buffer> {
pub fn get_testnet11_genesis_challenge() -> napi::Result<Buffer> {
TESTNET11_CONSTANTS.genesis_challenge.to_js()
}

#[napi]
/// Creates a new puzzle and its hash using the simulator.
///
/// @param {BigInt} value - The value to use for the puzzle.
/// @returns {Promise<js::SimulatorPuzzle>} The puzzle hash and reveal.
pub async fn simulator_new_puzzle(value: BigInt) -> napi::Result<js::SimulatorPuzzle> {
let value = u64::from_js(value)?;
let (puzzle_hash, puzzle_reveal) = to_puzzle(value).map_err(js::err)?;
Ok(js::SimulatorPuzzle {
puzzle_hash: puzzle_hash.to_js()?,
puzzle_reveal: puzzle_reveal.to_js()?,
})
}

#[napi]
/// Creates a new BlsPair.
///
/// @param {BigInt} value - The value to use to initialize the pair.
/// @returns {Promise<js::BlsPair>} The BlsPair.
pub fn simulator_new_blspair(value: BigInt) -> napi::Result<js::BlsPair> {
let value = u64::from_js(value)?;
let pair = chia_wallet_sdk::test::BlsPair::new(value);
Ok(js::BlsPair {
puzzle_hash: pair.puzzle_hash.to_js()?,
sk: pair.sk.to_js()?,
pk: pair.pk.to_js()?,
})
}

#[napi]
/// Creates a new simulator program.
///
/// @returns {Promise<Buffer>} The program.
pub fn simulator_new_program(pk: Buffer) -> napi::Result<Buffer> {
let pk = RustPublicKey::from_js(pk)?;
let program =
to_program([AggSigMe::new(pk, b"Hello, world!".to_vec().into())]).map_err(js::err)?;
Ok(program.to_js()?)
}
12 changes: 12 additions & 0 deletions src/rust.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub use crate::server_coin::ServerCoin;
use crate::UnspentCoinStates;
use chia::bls::{PublicKey, SecretKey};
pub use chia::protocol::*;
pub use chia::puzzles::{EveProof, LineageProof, Proof};

Expand All @@ -22,3 +23,14 @@ impl From<UnspentCoinStates> for UnspentCoinsResponse {
}
}
}

pub struct SimulatorPuzzle {
pub puzzle_hash: Bytes32,
pub puzzle_reveal: Program,
}

pub struct BlsPair {
pub sk: SecretKey,
pub pk: PublicKey,
pub puzzle_hash: Bytes32,
}