Skip to content

Commit

Permalink
Merge pull request #66 from wthrajat/module-docs
Browse files Browse the repository at this point in the history
Completes Module level documentation across the crate.
  • Loading branch information
rajarshimaitra authored Dec 2, 2023
2 parents 18c5daa + 4b4d2af commit 2cbb7d0
Show file tree
Hide file tree
Showing 34 changed files with 171 additions and 29 deletions.
10 changes: 9 additions & 1 deletion src/bin/teleport.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
//! CLI for the Teleport Wallet, handling various commands.
//!
//! Commands are related to wallet management, coin swapping, and market interactions.
//! Subcommands for tasks like generating a new wallet, recovering an existing wallet,
//! displaying wallet information, running the yield generator,
//! and performing coin swaps. It also supports direct sending of transactions and downloading
//! offers from makers in the market.
use clap::{Parser, Subcommand};
use std::{path::PathBuf, sync::Arc};

Expand Down Expand Up @@ -124,7 +132,7 @@ enum WalletArgsSubcommand {
#[arg(long, short, value_enum, default_value = "wallet")]
destination: Destination,

/// Coins to spend as inputs, either in long form "<txid>:vout" or short
/// Coins to spend as inputs, either in long form `<txid>:vout` or short
/// form "txid-prefix..txid-suffix:vout"
#[arg(long, short, value_enum)]
coins_to_spend: Vec<CoinToSpend>,
Expand Down
6 changes: 4 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
//! High-level network and protocol errors.
use crate::protocol::error::ContractError;

/// Includes all network related errors.
/// Includes all network-related errors.
#[derive(Debug)]
pub enum NetError {
IO(std::io::Error),
Expand All @@ -21,7 +23,7 @@ impl From<serde_json::Error> for NetError {
}
}

/// Includes all Protocol level errors.
/// Includes all Protocol-level errors.
#[derive(Debug)]
pub enum ProtocolError {
WrongMessage { expected: String, received: String },
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ pub mod taker;
pub mod test_framework;
pub mod utill;
pub mod wallet;
// Diasable watchtower for now. Handle contract watching
// Disable watchtower for now. Handle contract watching
// individually for maker and Taker.
//pub mod watchtower;
17 changes: 13 additions & 4 deletions src/maker/api.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
//! The Maker API.
//!
//! This module defines the core functionality of the Maker in a swap protocol implementation.
//! It includes structures for managing maker behavior, connection states, and recovery from swap events.
//! The module provides methods for initializing a Maker, verifying swap messages, and monitoring
//! contract broadcasts and handle idle Taker connections. Additionally, it handles recovery by broadcasting
//! contract transactions and claiming funds after an unsuccessful swap event.
use std::{
collections::HashMap,
net::IpAddr,
Expand Down Expand Up @@ -33,7 +41,7 @@ use crate::{

use super::{config::MakerConfig, error::MakerError};

//used to configure the maker do weird things for testing
// MakerBehavior enum is used to configure the maker for testing purposes.
#[derive(Debug, Clone, Copy)]
pub enum MakerBehavior {
Normal,
Expand Down Expand Up @@ -62,7 +70,8 @@ pub enum ExpectedMessage {
PrivateKeyHandover,
}

/// Per connection state maintaining list of swapcoins and next [ExpectedMessage]
/// ConnectionState structure maintains the state of a connection,
/// including the list of swapcoins and the next expected message.
#[derive(Debug, Default, Clone)]
pub struct ConnectionState {
pub allowed_message: ExpectedMessage,
Expand All @@ -71,7 +80,7 @@ pub struct ConnectionState {
pub pending_funding_txes: Vec<Transaction>,
}

/// The Maker Structure
/// The Maker structure represents the maker in the swap protocol.
pub struct Maker {
/// Defines special maker behavior, only applicable for testing
pub behavior: MakerBehavior,
Expand Down Expand Up @@ -122,7 +131,7 @@ impl Maker {
})
}

/// Trigger shutdown
/// Triggers a shutdown event for the Maker.
pub fn shutdown(&self) -> Result<(), MakerError> {
let mut flag = self.shutdown.write()?;
*flag = true;
Expand Down
2 changes: 2 additions & 0 deletions src/maker/config.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Maker Configuration. Controlling various behaviors.
use std::{collections::HashMap, io, path::PathBuf};

use crate::utill::{parse_field, parse_toml};
Expand Down
2 changes: 2 additions & 0 deletions src/maker/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! All Maker related errors.
use std::sync::{MutexGuard, PoisonError, RwLockReadGuard, RwLockWriteGuard};

use bitcoin::secp256k1;
Expand Down
13 changes: 11 additions & 2 deletions src/maker/handlers.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
//! Collection of all message handlers for a Maker.
//!
//! Implements the logic for message handling based on the current connection state.
//! Exposes the main function [handle_message] to process incoming messages and generate outgoing messages.
//! Also includes handlers for specific messages such as contract signatures, proof of funding, hash preimage, and private key handover.
//! Manages wallet state, incoming and outgoing swap coins, and special behaviors defined for the Maker.
//! The file includes functions to validate and sign contract transactions, verify proof of funding, and handle unexpected recovery scenarios.
//! Implements the core functionality for a Maker in a Bitcoin coinswap protocol.
use std::{net::IpAddr, sync::Arc, time::Instant};

use bitcoin::{
Expand Down Expand Up @@ -37,7 +46,7 @@ use crate::{
wallet::{IncomingSwapCoin, SwapCoin},
};

/// The Global Handle Message function. Takes in a [Arc<Maker>] and handle messages
/// The Global Handle Message function. Takes in a [`Arc<Maker>`] and handle messages
/// according to a [ConnectionState].
pub async fn handle_message(
maker: &Arc<Maker>,
Expand Down Expand Up @@ -235,7 +244,7 @@ impl Maker {
}

/// Validates the [ProofOfFunding] message, initiate the next hop,
/// and create the [ReqContractSigsAsRecvrAndSender] message.
/// and create the `[ReqContractSigsAsRecvrAndSender`\] message.
pub fn handle_proof_of_funding(
&self,
connection_state: &mut ConnectionState,
Expand Down
7 changes: 6 additions & 1 deletion src/maker/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
/// Main server runtime for the Maker module.
//! Defines a Coinswap Maker Server.
//!
//! Handles connections, communication with takers, various aspects of the
//! Maker's behavior, includes functionalities such as checking for new connections, handling messages from takers,
//! refreshing offer caches, and interacting with the Bitcoin node.
pub mod api;
pub mod config;
pub mod error;
Expand Down
8 changes: 7 additions & 1 deletion src/market/directory.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
//configure this with your own tor port
//! A simple directory-server
//!
//! Handles market-related logic where Makers post their offers. Also provides functions to synchronize
//! 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
pub const TOR_ADDR: &str = "127.0.0.1:9050";

use bitcoin::Network;
Expand Down
2 changes: 2 additions & 0 deletions src/market/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
//! (dummy) Current toy implementation of a directory-server.
pub mod directory;
4 changes: 4 additions & 0 deletions src/protocol/contract.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
//! Definition of the Coinswap Contract Transaction.
//!
//! This module includes most of the fundamental functions defining the coinswap protocol.
use std::convert::TryInto;

use bitcoin::{
Expand Down
2 changes: 2 additions & 0 deletions src/protocol/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! All Contract related errors.
use bitcoin::secp256k1;

#[derive(Debug)]
Expand Down
4 changes: 3 additions & 1 deletion src/protocol/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

//! Coinswap Protocol Messages.
//!
//! Messages are Communicated between Taker and one or many Makers.
//! Messages are communicated between one Taker and one or many Makers.
//! Makers don't communicate with each other. One Maker will only know the Identity of the Maker, in previous and next hop.
//!
//! Messages are named in terms of `Sender` and `Receiver` as identification of their context. They refer to sender and receiver sides of each hop.
Expand All @@ -22,6 +22,7 @@
//!
//! Taker -----> Maker1 -----> Maker2 ------> Taker
//!
//! ```shell
//! ********* Initiate First Hop *********
//! (Sender: Taker, Receiver: Maker1)
//! Taker -> Maker1: [TakerToMakerMessage::ReqContractSigsForSender]
Expand Down Expand Up @@ -58,6 +59,7 @@
//! Taker -> Maker2: [TakerToMakerMessage::RespPrivKeyHandover] (For Maker1-Maker2 funding multisig, received from Maker1 in Step 16)
//! Taker -> Maker2: [`TakerToMakerMessage::RespHashPreimage`] (for Maker2-Taker HTLC).
//! Maker2 -> Taker: [`MakerToTakerMessage::RespPrivKeyHandover`] (For Maker2-Taker funding multisig).
//! ```
use std::fmt::Display;

Expand Down
2 changes: 2 additions & 0 deletions src/protocol/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Defines the Contract Transaction and Protocol Messages
pub mod contract;
pub mod error;
pub mod messages;
Expand Down
6 changes: 6 additions & 0 deletions src/scripts/market.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
//! Download stuffs from the toy directory-server.
//!
//! The function takes optional parameters for specifying the network and a specific maker address.
//! It retrieves advertised maker addresses, synchronizes the offer book with these addresses,
//! and displays relevant offer details like size limits, fees, and locktime information.
use std::collections::HashMap;

use bitcoin::Network;
Expand Down
2 changes: 2 additions & 0 deletions src/scripts/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
//! (dummy) Various market and wallet related old scripts.
pub mod market;
pub mod wallet;
7 changes: 7 additions & 0 deletions src/scripts/wallet.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! Some Wallet application scripts made with the Wallet API.
//!
//! These include generating or recovering a wallet, displaying wallet balances and addresses,
//! printing receive invoices, and performing direct send operations. The functions handle
//! wallet initialization, synchronization with a backend node, and various display and transaction operations.
//! The module provides a convenient interface for users interacting with the teleport wallet.
use crate::wallet::{
fidelity::get_locktime_from_index, SwapCoin, UTXOSpendInfo, Wallet, WalletStore,
};
Expand Down
5 changes: 1 addition & 4 deletions src/taker/api.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
//! CoinSwap Taker Protocol
//!
//! Implementation of coinswap Taker protocol described in https://github.com/utxo-teleport/teleport-transactions#protocol-between-takers-and-makers
//! The Taker handles all the necessary communications between one or many makers to route the swap across various makers.
//! The Taker API.
//!
//! This module describes the main [Taker] structure and all other associated data sets related to a coinswap round.
//!
Expand Down
3 changes: 2 additions & 1 deletion src/taker/config.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
//! Taker configuration. Controlling various behavior.
use std::{collections::HashMap, io, path::PathBuf};

use crate::utill::{parse_field, parse_toml};
/// Various global configurations defining the Taker behavior.
/// TODO: Optionally read this from a config file.
#[derive(Debug, Clone, PartialEq)]
pub struct TakerConfig {
Expand Down
2 changes: 2 additions & 0 deletions src/taker/error.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! All Taker-related errors.
use bitcoin::Txid;

use bitcoind::bitcoincore_rpc::Error as RpcError;
Expand Down
7 changes: 7 additions & 0 deletions src/taker/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! 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)
mod api;
mod config;
pub mod error;
Expand Down
7 changes: 7 additions & 0 deletions src/taker/offers.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
//! Download, process and store Maker offers from the directory-server.
//!
//! It defines structures like [OfferAndAddress] and [MakerAddress] for representing maker offers and addresses.
//! The [OfferBook] struct keeps track of good and bad makers, and it provides methods for managing offers.
//! The module handles the syncing of the offer book with addresses obtained from directory servers and local configurations.
//! It uses asynchronous channels for concurrent processing of maker offers.
use std::fmt;

use tokio::sync::mpsc;
Expand Down
8 changes: 8 additions & 0 deletions src/taker/routines.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
//! Various operational routines/functions.
//!
//! It includes functions for handshaking, requesting contract signatures, sending proofs of funding, and downloading maker offers.
//! It also defines structs for contract transactions and contract information.
//! Notable types include [ContractTransaction], [ContractsInfo], [ThisMakerInfo], and [NextPeerInfoArgs].
//! It also handles downloading maker offers with retry mechanisms and implements the necessary message structures
//! for communication between taker and maker.
use serde::{Deserialize, Serialize};
use std::time::Duration;

Expand Down
24 changes: 22 additions & 2 deletions src/test_framework.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,17 @@
//! A Framework to write functional tests for the Coinswap Protocol.
//!
//! This framework uses [bitcoind] to automatically spawn regtest node in the background.
//!
//! Spawns one Taker and multiple Makers, with/without special behavior, connect them to bitcoind regtest node,
//! and initializes the database.
//!
//! The tests data are stored in the `tests/temp-files` directory, which is auto-removed after each successful test.
//! Do not invoke [TestFramework::stop] function at the end of the test, to persis this data for debugging.
//!
//! The test data also includes the backend bitcoind data-directory, which is useful for observing the blockchain states after a swap.
//!
//! Checkout `tests/standard_swap.rs` for example of simple coinswap simulation test between 1 Taker and 2 Makers.
use bitcoin::secp256k1::rand::{distributions::Alphanumeric, thread_rng, Rng}; // 0.8

use std::{
Expand Down Expand Up @@ -32,6 +46,9 @@ fn get_random_tmp_dir() -> PathBuf {
PathBuf::from(path)
}

/// The Test Framework.
///
/// Handles initializing, operating and cleaning up of all backend processes. Bitcoind, Taker and Makers.
pub struct TestFramework {
bitcoind: BitcoinD,
temp_dir: PathBuf,
Expand All @@ -45,7 +62,7 @@ impl TestFramework {
/// - a map of [port, [MakerBehavior]]
/// - optional taker behavior.
///
/// Returns ([TestFramework], [Taker], [Vec<Maker>]).
/// Returns ([TestFramework], [Taker], [`Vec<Maker>`]).
/// Maker's config will follow the pattern given the input HashMap.
/// If no bitcoind conf is provide a default value will be used.
pub async fn init(
Expand Down Expand Up @@ -137,6 +154,7 @@ impl TestFramework {
(test_framework, taker, makers)
}

/// Generate 1 block in the backend bitcoind.
pub fn generate_1_block(&self) {
let mining_address = self
.bitcoind
Expand All @@ -151,14 +169,15 @@ impl TestFramework {
.unwrap();
}

/// Send coins to a bitcoin address.
pub fn send_to_address(&self, addrs: &Address, amount: Amount) {
self.bitcoind
.client
.send_to_address(addrs, amount, None, None, None, None, None, None)
.unwrap();
}

// Clean up all test artifacts everything.
/// Stop bitcoind and clean up all test data.
pub fn stop(&self) {
log::info!("Stopping Test Framework");
// stop all framework threads.
Expand All @@ -176,6 +195,7 @@ impl TestFramework {
}
}

/// Initializes a [TestFramework] given a [RPCConfig].
impl From<&TestFramework> for RPCConfig {
fn from(value: &TestFramework) -> Self {
let url = value.bitcoind.rpc_url().split_at(7).1.to_string();
Expand Down
2 changes: 1 addition & 1 deletion src/utill.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Various Utility and Helper functions used in both Taker and Maker protocols.
//! Various utility and helper functions for both Taker and Maker.
use std::{io::ErrorKind, path::PathBuf, sync::Once};

Expand Down
8 changes: 4 additions & 4 deletions src/wallet/api.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// this file contains code handling the wallet and sync'ing the wallet
// for now the wallet is only sync'd via bitcoin core's RPC
// makers will only ever sync this way, but one day takers may sync in other
// ways too such as a lightweight wallet method
//! The Wallet API.
//!
//! Currently, wallet synchronization is exclusively performed through RPC for makers.
//! In the future, takers might adopt alternative synchronization methods, such as lightweight wallet solutions.
use std::{convert::TryFrom, fs, path::PathBuf, str::FromStr};

Expand Down
6 changes: 6 additions & 0 deletions src/wallet/direct_send.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
//! Send regular Bitcoin payments.
//!
//! This module provides functionality for managing wallet transactions, including the creation of
//! direct sends. It leverages Bitcoin Core's RPC for wallet synchronization and implements various
//! parsing mechanisms for transaction inputs and outputs.
use std::{num::ParseIntError, str::FromStr};

use bitcoin::{
Expand Down
Loading

0 comments on commit 2cbb7d0

Please sign in to comment.