Skip to content

Commit

Permalink
update proto, create deposit rpc
Browse files Browse the repository at this point in the history
  • Loading branch information
Ash-L2L committed Nov 4, 2024
1 parent fc94e41 commit 01c8744
Show file tree
Hide file tree
Showing 11 changed files with 89 additions and 50 deletions.
11 changes: 0 additions & 11 deletions Cargo.lock

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

15 changes: 6 additions & 9 deletions app/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use futures::{StreamExt, TryFutureExt, TryStreamExt as _};
use parking_lot::RwLock;
use rustreexo::accumulator::proof::Proof;
use thunder::{
format_deposit_address,
miner::{self, Miner},
node::{self, Node},
types::{
Expand All @@ -14,7 +13,7 @@ use thunder::{
self,
generated::{validator_service_server, wallet_service_server},
},
OutPoint, Output, Transaction, THIS_SIDECHAIN,
Address, OutPoint, Output, Transaction,
},
wallet::{self, Wallet},
};
Expand Down Expand Up @@ -354,24 +353,22 @@ impl App {
}

pub fn deposit(
&mut self,
&self,
address: Address,
amount: bitcoin::Amount,
fee: bitcoin::Amount,
) -> Result<(), Error> {
) -> Result<bitcoin::Txid, Error> {
let Some(miner) = self.miner.as_ref() else {
return Err(Error::NoCusfMainchainWalletClient);
};
self.runtime.block_on(async {
let address = self.wallet.get_new_address()?;
let address =
format_deposit_address(THIS_SIDECHAIN, &format!("{address}"));
let mut miner_write = miner.write().await;
let _txid = miner_write
let txid = miner_write
.cusf_mainchain_wallet
.create_deposit_tx(address, amount.to_sat(), fee.to_sat())
.await?;
drop(miner_write);
Ok(())
Ok(txid)
})
}
}
Expand Down
1 change: 1 addition & 0 deletions app/gui/parent_chain/transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ impl Deposit {
.clicked()
{
if let Err(err) = app.deposit(
app.wallet.get_new_address().expect("should not happen"),
amount.expect("should not happen"),
fee.expect("should not happen"),
) {
Expand Down
22 changes: 17 additions & 5 deletions app/rpc_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use jsonrpsee::{
};
use thunder::{
node,
types::{Address, PointedOutput, Txid, THIS_SIDECHAIN},
types::{Address, PointedOutput, Txid},
wallet,
};
use thunder_app_rpc_api::RpcServer;
Expand Down Expand Up @@ -50,6 +50,21 @@ impl RpcServer for RpcServerImpl {
self.app.wallet.get_balance().map_err(convert_wallet_err)
}

async fn create_deposit(
&self,
address: Address,
value_sats: u64,
fee_sats: u64,
) -> RpcResult<bitcoin::Txid> {
self.app
.deposit(
address,
bitcoin::Amount::from_sat(value_sats),
bitcoin::Amount::from_sat(fee_sats),
)
.map_err(convert_app_err)
}

async fn connect_peer(&self, addr: SocketAddr) -> RpcResult<()> {
self.app.node.connect_peer(addr).map_err(convert_node_err)
}
Expand All @@ -58,10 +73,7 @@ impl RpcServer for RpcServerImpl {
&self,
address: Address,
) -> RpcResult<String> {
let deposit_address = thunder::format_deposit_address(
THIS_SIDECHAIN,
&address.to_string(),
);
let deposit_address = thunder::format_deposit_address(address);
Ok(deposit_address)
}

Expand Down
18 changes: 18 additions & 0 deletions cli/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ pub enum Command {
Balance,
/// Connect to a peer
ConnectPeer { addr: SocketAddr },
/// Deposit to address
CreateDeposit {
address: Address,
#[arg(long)]
value_sats: u64,
#[arg(long)]
fee_sats: u64,
},
/// Format a deposit address
FormatDepositAddress { address: Address },
/// Generate a mnemonic seed phrase
Expand Down Expand Up @@ -91,6 +99,16 @@ impl Cli {
let () = rpc_client.connect_peer(addr).await?;
String::default()
}
Command::CreateDeposit {
address,
value_sats,
fee_sats,
} => {
let txid = rpc_client
.create_deposit(address, value_sats, fee_sats)
.await?;
format!("{txid}")
}
Command::FormatDepositAddress { address } => {
rpc_client.format_deposit_address(address).await?
}
Expand Down
1 change: 0 additions & 1 deletion lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ bincode = "1.3.3"
bitcoin = { version = "0.32.2", features = ["serde"] }
blake3 = "1.4.1"
borsh = { version = "1.3.1", features = ["derive"] }
bs58 = { version = "0.5.0", features = ["check"] }
byteorder = "1.4.3"
bytes = "1.4.0"
ed25519-dalek = { version = "2.1.1", features = ["batch", "serde"] }
Expand Down
9 changes: 3 additions & 6 deletions lib/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,10 @@ pub mod wallet;

pub use heed;

/// Format `str_dest` with the proper `s{sidechain_number}_` prefix and a
/// Format `b58_dest` with the proper `s{sidechain_number}_` prefix and a
/// checksum postfix for calling createsidechaindeposit on mainchain.
pub fn format_deposit_address(this_sidechain: u8, str_dest: &str) -> String {
let deposit_address: String = format!("s{}_{}_", this_sidechain, str_dest);
let hash = sha256::digest(deposit_address.as_bytes()).to_string();
let hash: String = hash[..6].into();
format!("{}{}", deposit_address, hash)
pub fn format_deposit_address(dest: types::Address) -> String {
format!("s{}_{}", types::THIS_SIDECHAIN, dest.to_base58ck())
}

// TODO: Add error log.
18 changes: 8 additions & 10 deletions lib/types/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use serde_with::{DeserializeAs, DisplayFromStr};
#[derive(Debug, thiserror::Error)]
pub enum AddressParseError {
#[error("bs58 error")]
Bs58(#[from] bs58::decode::Error),
Bs58(#[from] bitcoin::base58::InvalidCharacterError),
#[error("wrong address length {0} != 20")]
WrongLength(usize),
}
Expand All @@ -17,10 +17,11 @@ pub struct Address(pub [u8; 20]);

impl Address {
pub fn to_base58(self) -> String {
bs58::encode(self.0)
.with_alphabet(bs58::Alphabet::BITCOIN)
.with_check()
.into_string()
bitcoin::base58::encode(&self.0)
}

pub fn to_base58ck(self) -> String {
bitcoin::base58::encode_check(&self.0)
}
}

Expand All @@ -45,10 +46,7 @@ impl From<[u8; 20]> for Address {
impl std::str::FromStr for Address {
type Err = AddressParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let address = bs58::decode(s)
.with_alphabet(bs58::Alphabet::BITCOIN)
.with_check(None)
.into_vec()?;
let address = bitcoin::base58::decode(s)?;
Ok(Address(address.try_into().map_err(
|address: Vec<u8>| AddressParseError::WrongLength(address.len()),
)?))
Expand All @@ -74,7 +72,7 @@ impl Serialize for Address {
S: serde::Serializer,
{
if serializer.is_human_readable() {
Serialize::serialize(&self.to_base58(), serializer)
Serialize::serialize(&self.to_base58ck(), serializer)
} else {
Serialize::serialize(&self.0, serializer)
}
Expand Down
13 changes: 8 additions & 5 deletions lib/types/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -921,15 +921,17 @@ pub mod mainchain {

pub async fn create_deposit_tx(
&mut self,
address: String,
address: crate::types::Address,
value_sats: u64,
fee_sats: u64,
) -> Result<Txid, super::Error> {
let request = generated::CreateDepositTransactionRequest {
sidechain_id: THIS_SIDECHAIN as u32,
address,
value_sats,
fee_sats,
sidechain_id: Some(THIS_SIDECHAIN as u32),
address: Some(ConsensusHex::consensus_encode(
&address.0.to_vec(),
)),
value_sats: Some(value_sats),
fee_sats: Some(fee_sats),
};
let generated::CreateDepositTransactionResponse { txid } = self
.0
Expand Down Expand Up @@ -971,6 +973,7 @@ pub mod mainchain {
) -> Result<(), super::Error> {
let request = generated::GenerateBlocksRequest {
blocks: Some(blocks),
ack_all_proposals: true,
};
let generated::GenerateBlocksResponse {} =
self.0.generate_blocks(request).await?.into_inner();
Expand Down
2 changes: 1 addition & 1 deletion proto
29 changes: 27 additions & 2 deletions rpc-api/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ impl ToSchema<'static> for BitcoinOutPointSchema {
}
}

struct BitcoinTxidSchema;

impl PartialSchema for BitcoinTxidSchema {
fn schema() -> RefOr<Schema> {
let obj = utoipa::openapi::Object::with_type(SchemaType::String);
RefOr::T(Schema::Object(obj))
}
}

impl ToSchema<'static> for BitcoinTxidSchema {
fn schema() -> (&'static str, RefOr<Schema>) {
("bitcoin.Txid", <Self as PartialSchema>::schema())
}
}

struct OpenApiSchema;

impl PartialSchema for OpenApiSchema {
Expand All @@ -70,8 +85,8 @@ impl PartialSchema for SocketAddrSchema {
}

#[open_api(ref_schemas[
Address, BitcoinAddrSchema, BitcoinOutPointSchema, MerkleRoot, OutPoint, Output,
OutputContent, Txid
Address, BitcoinAddrSchema, BitcoinOutPointSchema, BitcoinTxidSchema,
MerkleRoot, OutPoint, Output, OutputContent, Txid
])]
#[rpc(client, server)]
pub trait Rpc {
Expand All @@ -88,6 +103,16 @@ pub trait Rpc {
addr: SocketAddr,
) -> RpcResult<()>;

/// Deposit to address
#[open_api_method(output_schema(PartialSchema = "BitcoinTxidSchema"))]
#[method(name = "create_deposit")]
async fn create_deposit(
&self,
address: Address,
value_sats: u64,
fee_sats: u64,
) -> RpcResult<bitcoin::Txid>;

/// Format a deposit address
#[method(name = "format_deposit_address")]
async fn format_deposit_address(
Expand Down

0 comments on commit 01c8744

Please sign in to comment.