Skip to content

Commit

Permalink
rustdoc: api docs 90% covered
Browse files Browse the repository at this point in the history
  • Loading branch information
wthrajat committed Dec 12, 2023
1 parent e936099 commit 72a8b1d
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 27 deletions.
11 changes: 6 additions & 5 deletions src/maker/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ pub enum MakerBehavior {
}

/// Expected messages for the taker in the context of [ConnectionState] structure.
///
///
/// If the received message doesn't match expected message,
/// a protocol error will be returned.
#[derive(Debug, Default, PartialEq, Clone)]
Expand Down Expand Up @@ -187,6 +187,7 @@ impl Maker {
Ok(())
}

/// Returns a reference to the Maker's wallet.
pub fn get_wallet(&self) -> &RwLock<Wallet> {
&self.wallet
}
Expand Down Expand Up @@ -340,7 +341,7 @@ impl Maker {

/// Constantly checks for contract transactions in the bitcoin network for all
/// unsettled swap.
///
///
/// If any one of the is ever observed, run the recovery routine.
pub fn check_for_broadcasted_contracts(maker: Arc<Maker>) -> Result<(), MakerError> {
let mut failed_swap_ip = Vec::new();
Expand Down Expand Up @@ -454,7 +455,7 @@ pub fn check_for_broadcasted_contracts(maker: Arc<Maker>) -> Result<(), MakerErr
}

/// Check that if any Taker connection went idle.
///
///
/// If a connection remains idle for more than idle timeout time, thats a potential DOS attack.
/// Broadcast the contract transactions and claim funds via timelock.
pub fn check_for_idle_states(maker: Arc<Maker>) -> Result<(), MakerError> {
Expand Down Expand Up @@ -537,8 +538,8 @@ pub fn check_for_idle_states(maker: Arc<Maker>) -> Result<(), MakerError> {
Ok(())
}

/// Broadcast Incoming and Outgoing Contract transactions. Broadcast timelock transactions after maturity.
/// remove contract transactions from the wallet.
/// Broadcast Incoming and Outgoing Contract transactions & timelock transactions after maturity.
/// Remove contract transactions from the wallet.
pub fn recover_from_swap(
maker: Arc<Maker>,
// Tuple of ((Multisig_reedemscript, Contract Tx), (Timelock, Timelock Tx))
Expand Down
2 changes: 1 addition & 1 deletion src/maker/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ mod tests {
fn remove_temp_config(path: &PathBuf) {
fs::remove_file(path).unwrap();
}

#[test]
fn test_valid_config() {
let contents = r#"
Expand Down
1 change: 1 addition & 0 deletions src/maker/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use bitcoin::secp256k1;

use crate::{protocol::error::ContractError, wallet::WalletError};

/// Enum to handle Maker related errors.
#[derive(Debug)]
pub enum MakerError {
IO(std::io::Error),
Expand Down
8 changes: 6 additions & 2 deletions src/market/directory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
//! maker addresses from directory servers, post maker addresses to directory servers,
//! and defines constants such as Tor addresses and directory server addresses.
// configure this with your own TOR port
/// Represents the Tor address and port configuration.
// It should be set to your specific Tor address and port.
pub const TOR_ADDR: &str = "127.0.0.1:9050";

use bitcoin::Network;
Expand All @@ -15,6 +16,7 @@ use crate::taker::offers::MakerAddress;
const DIRECTORY_SERVER_ADDR: &str =
"zfwo4t5yfuf6epu7rhjbmkr6kiysi6v7kibta4i55zlp4y6xirpcr7qd.onion:8080";

/// Represents errors that can occur during directory server operations.
#[derive(Debug)]
pub enum DirectoryServerError {
Reqwest(reqwest::Error),
Expand All @@ -27,6 +29,7 @@ impl From<reqwest::Error> for DirectoryServerError {
}
}

/// Converts a `Network` enum variant to its corresponding string representation.
fn network_enum_to_string(network: Network) -> &'static str {
match network {
Network::Bitcoin => "mainnet",
Expand All @@ -36,7 +39,7 @@ fn network_enum_to_string(network: Network) -> &'static str {
_ => todo!(),
}
}

/// Asynchronously Synchronize Maker Addresses from Directory Servers.
pub async fn sync_maker_addresses_from_directory_servers(
network: Network,
) -> Result<Vec<MakerAddress>, DirectoryServerError> {
Expand Down Expand Up @@ -73,6 +76,7 @@ pub async fn sync_maker_addresses_from_directory_servers(
Ok(maker_addresses)
}

/// Posts a maker's address to directory servers based on the specified network.
pub async fn post_maker_address_to_directory_servers(
network: Network,
address: &str,
Expand Down
9 changes: 5 additions & 4 deletions src/protocol/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,20 @@ use super::{
messages::{FundingTxInfo, ProofOfFunding},
};

//relatively simple handling of miner fees for now, each funding transaction is considered
// relatively simple handling of miner fees for now, each funding transaction is considered
// to have the same size, and taker will pay all the maker's miner fees based on that
//taker will choose what fee rate they will use, and how many funding transactions they want
// taker will choose what fee rate they will use, and how many funding transactions they want
// the makers to create
//this doesnt take into account the different sizes of single-sig, 2of2 multisig or htlc contracts
// this doesnt take into account the different sizes of single-sig, 2of2 multisig or htlc contracts
// but all those complications will go away when we move to ecdsa2p and scriptless scripts
// so theres no point adding complications for something that we'll hopefully get rid of soon
//this size here is for a tx with 2 p2wpkh outputs, 3 singlesig inputs and 1 2of2 multisig input
// this size here is for a tx with 2 p2wpkh outputs, 3 singlesig inputs and 1 2of2 multisig input
// if the maker can get stuff confirmed cheaper than this then they can keep that money
// if the maker ends up paying more then thats their problem
// we could avoid this guessing by adding one more round trip to the protocol where the maker
// calculates exactly how big the transactions will be and then taker knows exactly the miner fee
// to pay for

pub const FUNDING_TX_VBYTE_SIZE: u64 = 372;

pub fn calculate_coinswap_fee(
Expand Down
1 change: 1 addition & 0 deletions src/protocol/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
use bitcoin::secp256k1;

/// Enum for handling contract-related errors.
#[derive(Debug)]
pub enum ContractError {
Secp(secp256k1::Error),
Expand Down
3 changes: 3 additions & 0 deletions src/protocol/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,10 @@ use serde::{Deserialize, Serialize};

use bitcoin::hashes::hash160::Hash as Hash160;

/// Defines the length of the Preimage.
pub const PREIMAGE_LEN: usize = 32;

/// Type for Preimage.
pub type Preimage = [u8; PREIMAGE_LEN];

/// Represents the initial handshake message sent from Taker to Maker.
Expand Down
2 changes: 1 addition & 1 deletion src/protocol/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Defines the Contract Transaction and Protocol Messages
//! Defines the Contract Transaction and Protocol Messages.
pub mod contract;
pub mod error;
Expand Down
2 changes: 1 addition & 1 deletion src/scripts/market.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::taker::{
};

#[tokio::main]
/// App function to download offers
/// App function to download offers.
pub async fn download_and_display_offers(
_network_str: Option<String>,
maker_address: Option<String>,
Expand Down
1 change: 1 addition & 0 deletions src/scripts/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,7 @@ pub fn display_wallet_addresses(
Ok(())
}

/// Prints the receive invoice for the wallet.
pub fn print_receive_invoice(wallet_file_name: &PathBuf) -> Result<(), WalletError> {
let mut wallet = Wallet::load(&RPCConfig::default(), wallet_file_name)?;
wallet.sync()?;
Expand Down
6 changes: 4 additions & 2 deletions src/taker/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,15 @@ struct NextPeerInfo {
contract_reedemscripts: Vec<ScriptBuf>,
}

/// Enum representing different behaviors of the Taker in a coinswap protocol.
#[derive(Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum TakerBehavior {
// No special behavior
/// No special behavior.
#[default]
Normal,
// This depicts the behavior when the taker drops connections after the full coinswap setup
/// This depicts the behavior when the taker drops connections after the full coinswap setup.
DropConnectionAfterFullSetup,
/// Behavior to broadcast the contract after the full coinswap setup.
BroadcastContractAfterFullSetup,
}

Expand Down
6 changes: 5 additions & 1 deletion src/taker/config.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
//! Taker configuration. Controlling various behavior.
//!
//! Represents the configuration options for the Taker module, controlling behaviors
//! such as refund locktime, connection attempts, sleep delays, and timeouts.
use std::{collections::HashMap, io, path::PathBuf};

use crate::utill::{parse_field, parse_toml};
/// TODO: Optionally read this from a config file.
// TODO: Optionally read this from a config file.
/// Taker configuration with refund, connection, and sleep settings.
#[derive(Debug, Clone, PartialEq)]
pub struct TakerConfig {
pub refund_locktime: u16,
Expand Down
1 change: 1 addition & 0 deletions src/taker/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::{
wallet::WalletError,
};

/// Enum for handling taker-related errors.
#[derive(Debug)]
pub enum TakerError {
IO(std::io::Error),
Expand Down
1 change: 0 additions & 1 deletion src/taker/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! Defines a Coinswap Taker Client.
//!
//!
//! This also contains the entire swap workflow as major decision makings are involved for the Taker. Makers are
//! simple request-response servers. The Taker handles all the necessary communications between one or many makers to route the swap across various makers. Description of
//! protocol workflow is described in the [protocol between takers and makers](https://github.com/utxo-teleport/teleport-transactions#protocol-between-takers-and-makers)
Expand Down
11 changes: 11 additions & 0 deletions src/taker/offers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use crate::market::directory::{

use super::{config::TakerConfig, error::TakerError, routines::download_maker_offer};

/// Represents an offer along with the corresponding maker address.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OfferAndAddress {
pub offer: Offer,
Expand All @@ -33,13 +34,15 @@ const REGTEST_MAKER_ADDRESSES: &[&str] = &[
"localhost:46102",
];

/// Enum representing maker addresses (clearnet and TOR).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MakerAddress {
Clearnet { address: String },
Tor { address: String },
}

impl MakerAddress {
/// Returns the TCP stream address as a string.
pub fn get_tcpstream_address(&self) -> String {
match &self {
MakerAddress::Clearnet { address } => address.to_string(),
Expand Down Expand Up @@ -68,13 +71,15 @@ pub struct OfferBook {
}

impl OfferBook {
/// Gets all untried offers.
pub fn get_all_untried(&self) -> Vec<&OfferAndAddress> {
self.all_makers
.iter()
.filter(|offer| !self.good_makers.contains(offer) && !self.bad_makers.contains(offer))
.collect()
}

/// Adds a new offer to the offer book.
pub fn add_new_offer(&mut self, offer: &OfferAndAddress) -> bool {
if !self.all_makers.contains(offer) {
self.all_makers.push(offer.clone());
Expand All @@ -84,6 +89,7 @@ impl OfferBook {
}
}

/// Adds a good maker to the offer book.
pub fn add_good_maker(&mut self, good_maker: &OfferAndAddress) -> bool {
if !self.good_makers.contains(good_maker) {
self.good_makers.push(good_maker.clone());
Expand All @@ -93,6 +99,7 @@ impl OfferBook {
}
}

/// Adds a bad maker to the offer book.
pub fn add_bad_maker(&mut self, bad_maker: &OfferAndAddress) -> bool {
if !self.bad_makers.contains(bad_maker) {
self.bad_makers.push(bad_maker.clone());
Expand All @@ -102,6 +109,7 @@ impl OfferBook {
}
}

/// Synchronizes the offer book with addresses obtained from directory servers and local configurations.
pub async fn sync_offerbook(
&mut self,
network: Network,
Expand All @@ -123,6 +131,7 @@ impl OfferBook {
Ok(new_offers)
}

/// Gets the list of bad makers.
pub fn get_bad_makers(&self) -> Vec<&OfferAndAddress> {
self.bad_makers.iter().collect()
}
Expand All @@ -137,6 +146,7 @@ fn get_regtest_maker_addresses() -> Vec<MakerAddress> {
.collect::<Vec<MakerAddress>>()
}

/// Synchronizes the offer book with specific maker addresses.
pub async fn sync_offerbook_with_addresses(
maker_addresses: Vec<MakerAddress>,
config: &TakerConfig,
Expand Down Expand Up @@ -167,6 +177,7 @@ pub async fn sync_offerbook_with_addresses(
result
}

/// Retrieves advertised maker addresses from directory servers based on the specified network.
pub async fn get_advertised_maker_addresses(
network: Network,
) -> Result<Vec<MakerAddress>, DirectoryServerError> {
Expand Down
20 changes: 14 additions & 6 deletions src/utill.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ use crate::{
wallet::{SwapCoin, WalletError},
};

/// Converts a string representation of a network to a `Network` enum variant.
pub fn str_to_bitcoin_network(net_str: &str) -> Network {
match net_str {
"main" => Network::Bitcoin,
Expand Down Expand Up @@ -84,7 +85,7 @@ pub fn setup_logger() {
});
}

/// Can send both Taker and Maker messages
/// Can send both Taker and Maker messages.
pub async fn send_message(
socket_writer: &mut WriteHalf<'_>,
message: &impl serde::Serialize,
Expand All @@ -95,7 +96,7 @@ pub async fn send_message(
Ok(())
}

/// Read a Maker Message
/// Read a Maker Message.
pub async fn read_message(
reader: &mut BufReader<ReadHalf<'_>>,
) -> Result<MakerToTakerMessage, NetError> {
Expand All @@ -122,7 +123,7 @@ pub fn check_and_apply_maker_private_keys<S: SwapCoin>(

/// Generate The Maker's Multisig and HashLock keys and respective nonce values.
/// Nonce values are random integers and resulting Pubkeys are derived by tweaking the
/// Make's advertised Pubkey with these two nonces.
/// Maker's advertised Pubkey with these two nonces.
pub fn generate_maker_keys(
tweakable_point: &PublicKey,
count: u32,
Expand All @@ -146,6 +147,7 @@ pub fn generate_maker_keys(
)
}

/// Converts a Bitcoin amount from JSON-RPC representation to satoshis.
pub fn convert_json_rpc_bitcoin_to_satoshis(amount: &Value) -> u64 {
//to avoid floating point arithmetic, convert the bitcoin amount to
//string with 8 decimal places, then remove the decimal point to
Expand All @@ -157,7 +159,11 @@ pub fn convert_json_rpc_bitcoin_to_satoshis(amount: &Value) -> u64 {
.parse::<u64>()
.unwrap()
}
// returns None if not a hd descriptor (but possibly a swapcoin (multisig) descriptor instead)

/// Extracts hierarchical deterministic (HD) path components from a descriptor.
///
/// Parses an input descriptor string and returns `Some` with a tuple containing the HD path
/// components if it's an HD descriptor. If it's not an HD descriptor, it returns `None`.
pub fn get_hd_path_from_descriptor(descriptor: &str) -> Option<(&str, u32, i32)> {
//e.g
//"desc": "wpkh([a945b5ca/1/1]029b77637989868dcd502dbc07d6304dc2150301693ae84a60b379c3b696b289ad)#aq759em9",
Expand Down Expand Up @@ -186,6 +192,7 @@ pub fn get_hd_path_from_descriptor(descriptor: &str) -> Option<(&str, u32, i32)>
Some((path_chunks[0], addr_type.unwrap(), index.unwrap()))
}

/// Generates a keypair using the secp256k1 elliptic curve.
pub fn generate_keypair() -> (PublicKey, SecretKey) {
let mut privkey = [0u8; 32];
OsRng.fill_bytes(&mut privkey);
Expand All @@ -209,6 +216,7 @@ pub fn redeemscript_to_scriptpubkey(redeemscript: &ScriptBuf) -> ScriptBuf {
ScriptBuf::new_witness_program(&witness_program)
}

/// Converts a byte vector to a hexadecimal string representation.
pub fn to_hex(bytes: &Vec<u8>) -> String {
let hex_chars: Vec<char> = "0123456789abcdef".chars().collect();
let mut hex_string = String::new();
Expand All @@ -223,7 +231,7 @@ pub fn to_hex(bytes: &Vec<u8>) -> String {
hex_string
}

/// Function to parse toml file into key-value pair
/// Parse TOML file into key-value pair.
pub fn parse_toml(file_path: &PathBuf) -> io::Result<HashMap<String, HashMap<String, String>>> {
let file = File::open(file_path)?;
let reader = io::BufReader::new(file);
Expand Down Expand Up @@ -253,7 +261,7 @@ pub fn parse_toml(file_path: &PathBuf) -> io::Result<HashMap<String, HashMap<Str
Ok(sections)
}

/// Function to parse and log errors for each field
/// Parse and log errors for each field.
pub fn parse_field<T: std::str::FromStr>(value: Option<&String>, default: T) -> io::Result<T> {
match value {
Some(value) => value
Expand Down
Loading

0 comments on commit 72a8b1d

Please sign in to comment.