diff --git a/code/src/Birdmannn_week_2/LEARNING_SUMMARY.md b/code/src/Birdmannn_week_2/LEARNING_SUMMARY.md new file mode 100644 index 0000000..0562018 --- /dev/null +++ b/code/src/Birdmannn_week_2/LEARNING_SUMMARY.md @@ -0,0 +1,105 @@ +# Week 2 Learning Summary: Rust Fundamentals + +## Overview +This week focused on building strong Rust fundamentals through three hands-on exercises. These exercises prepare for Bitcoin-focused development by covering essential Rust concepts. + +--- + +## Task 1: Functions and Expressions + +### What I Learned +- **Function Return Types**: Rust functions explicitly declare return types using `-> Type` syntax +- **Expression Blocks**: In Rust, the last expression in a function (without a semicolon) is automatically returned +- **Type Safety**: Rust's type system ensures functions work with specific data types + +### Key Concepts +- Functions are defined with `fn` keyword +- Return type comes after the parameter list: `fn name(param: Type) -> ReturnType` +- Expressions (without semicolons) return values; statements (with semicolons) don't +- Floating-point arithmetic for financial calculations + +### Practical Application +Created `btc_value_in_usd()` function that converts Bitcoin amounts to USD using exchange rates. This demonstrates: +- Simple mathematical operations +- Function composition +- Real-world Bitcoin use case + +--- + +## Task 2: Control Flow & Loops + +### What I Learned +- **For Loops**: Iterate over ranges using `for x in 1..=limit` syntax +- **While Loops**: Conditional iteration with mutable state management +- **If-Else Blocks**: Pattern matching for conditional logic +- **Loop Control**: Using modulo operator (`%`) for periodic actions + +### Key Concepts +- `for` loops are ideal for known iteration counts +- `while` loops handle conditional iterations +- Range syntax: `1..limit` (exclusive) vs `1..=limit` (inclusive) +- Mutable variables with `mut` keyword for state tracking +- Checkpoint logic using modulo arithmetic + +### Practical Application +Simulated Bitcoin block mining with: +- Basic mining loop showing block heights +- Checkpoints every 5 blocks +- Difficulty adjustment every 10 blocks +- Real-world blockchain simulation + +--- + +## Task 3: Enums & Pattern Matching + +### What I Learned +- **Enums**: Define types with multiple variants (Mainnet, Testnet, Regtest) +- **Pattern Matching**: Use `match` expressions to handle all enum variants +- **Exhaustiveness**: Rust requires handling all possible enum values +- **String References**: Return `&str` for efficient string handling + +### Key Concepts +- Enum definition with `enum Name { Variant1, Variant2, ... }` +- `#[derive(Debug, Clone, Copy)]` attributes for enum functionality +- `match` expressions for comprehensive pattern matching +- Functions that accept enum references: `fn func(network: &Network)` +- Returning string slices for different network configurations + +### Practical Application +Created Bitcoin network configuration system: +- Three network types: Mainnet, Testnet, Regtest +- RPC URL mapping for each network +- Network details (ports, descriptions, chain IDs) +- Demonstrates real Bitcoin development patterns + +--- + +## Key Takeaways + +### Rust Fundamentals Mastered +1. **Functions**: Clear return types and expression-based returns +2. **Control Flow**: Flexible looping with for/while and conditional logic +3. **Type System**: Enums provide type-safe alternatives to magic strings +4. **Pattern Matching**: Exhaustive matching prevents runtime errors + +### Bitcoin Development Readiness +- Understanding network configurations (Mainnet/Testnet/Regtest) +- Block mining simulation concepts +- Value conversion and financial calculations +- RPC endpoint management + +### Best Practices Applied +- Clear function documentation with doc comments (`///`) +- Meaningful variable names +- Proper use of Rust's type system +- Efficient string handling with references + +--- + +## Files Created +- `task_1.rs` - Functions and Expressions (BTC to USD conversion) +- `task_2.rs` - Control Flow & Loops (Block mining simulation) +- `task_3.rs` - Enums & Pattern Matching (Network configuration) + +All tasks compile successfully and demonstrate proper Rust patterns for Bitcoin development. + diff --git a/code/src/Birdmannn_week_2/task_1.rs b/code/src/Birdmannn_week_2/task_1.rs new file mode 100644 index 0000000..d5d31d1 --- /dev/null +++ b/code/src/Birdmannn_week_2/task_1.rs @@ -0,0 +1,50 @@ +/// Task 1: Functions and Expressions +/// +/// This task demonstrates: +/// - Function return types +/// - Expression blocks (no semicolons for return) +/// - Converting BTC to USD using a given exchange rate + +/// Converts Bitcoin value to USD +/// +/// # Arguments +/// * `btc` - The amount of Bitcoin +/// * `rate` - The exchange rate (BTC to USD) +/// +/// # Returns +/// The equivalent value in USD +fn btc_value_in_usd(btc: f64, rate: f64) -> f64 { + btc * rate +} + +fn main() { + println!("=== Task 1: Functions and Expressions ===\n"); + + // Example 1: Convert 1 BTC to USD at $45,000 per BTC + let btc_amount = 1.0; + let exchange_rate = 45000.0; + let usd_value = btc_value_in_usd(btc_amount, exchange_rate); + + println!("Bitcoin Amount: {} BTC", btc_amount); + println!("Exchange Rate: ${} per BTC", exchange_rate); + println!("USD Value: ${}\n", usd_value); + + // Example 2: Convert 0.5 BTC to USD at $50,000 per BTC + let btc_amount_2 = 0.5; + let exchange_rate_2 = 50000.0; + let usd_value_2 = btc_value_in_usd(btc_amount_2, exchange_rate_2); + + println!("Bitcoin Amount: {} BTC", btc_amount_2); + println!("Exchange Rate: ${} per BTC", exchange_rate_2); + println!("USD Value: ${}\n", usd_value_2); + + // Example 3: Convert 2.5 BTC to USD at $48,500 per BTC + let btc_amount_3 = 2.5; + let exchange_rate_3 = 48500.0; + let usd_value_3 = btc_value_in_usd(btc_amount_3, exchange_rate_3); + + println!("Bitcoin Amount: {} BTC", btc_amount_3); + println!("Exchange Rate: ${} per BTC", exchange_rate_3); + println!("USD Value: ${}", usd_value_3); +} + diff --git a/code/src/Birdmannn_week_2/task_2.rs b/code/src/Birdmannn_week_2/task_2.rs new file mode 100644 index 0000000..ffb3668 --- /dev/null +++ b/code/src/Birdmannn_week_2/task_2.rs @@ -0,0 +1,61 @@ +/// Task 2: Control Flow & Loops +/// +/// This task demonstrates: +/// - For loops for block mining simulation +/// - While loops for difficulty simulation +/// - If-else blocks for checkpoints +/// - Pattern matching with ranges + +/// Simulates mining blocks with difficulty and checkpoints +/// +/// # Arguments +/// * `limit` - The maximum block height to mine +fn mine_blocks(limit: u8) { + println!("Starting block mining simulation...\n"); + + for height in 1..=limit { + println!("Mining block #{}", height); + + // Checkpoint every 5 blocks + if height % 5 == 0 { + println!("✓ Checkpoint reached at block #{}\n", height); + } + } +} + +/// Simulates mining with difficulty adjustment using a while loop +/// +/// # Arguments +/// * `target_blocks` - The number of blocks to mine +fn mine_blocks_with_difficulty(target_blocks: u8) { + println!("\n=== Mining with Difficulty Simulation ===\n"); + + let mut height = 1; + let mut difficulty = 1; + + while height <= target_blocks { + println!("Mining block #{} (Difficulty: {})", height, difficulty); + + // Increase difficulty every 10 blocks + if height % 10 == 0 { + difficulty += 1; + println!("⚡ Difficulty increased to {}\n", difficulty); + } + + height += 1; + } +} + +fn main() { + println!("=== Task 2: Control Flow & Loops ===\n"); + + // Basic mining simulation with checkpoints + mine_blocks(20); + + // Mining with difficulty adjustment + mine_blocks_with_difficulty(25); + + println!("\n=== Mining Summary ==="); + println!("Total blocks mined: 20 (basic) + 25 (with difficulty)"); +} + diff --git a/code/src/Birdmannn_week_2/task_3.rs b/code/src/Birdmannn_week_2/task_3.rs new file mode 100644 index 0000000..461c908 --- /dev/null +++ b/code/src/Birdmannn_week_2/task_3.rs @@ -0,0 +1,101 @@ +/// Task 3: Enums & Pattern Matching +/// +/// This task demonstrates: +/// - Enum definition for Bitcoin networks +/// - Pattern matching with match blocks +/// - Functions that work with enums +/// - Returning string references + +/// Represents different Bitcoin networks +#[derive(Debug, Clone, Copy)] +enum Network { + Mainnet, + Testnet, + Regtest, +} + +/// Returns the RPC URL for the given network +/// +/// # Arguments +/// * `network` - A reference to the Network enum +/// +/// # Returns +/// A string slice containing the RPC URL +fn get_rpc_url(network: &Network) -> &str { + match network { + Network::Mainnet => "http://localhost:8332", + Network::Testnet => "http://localhost:18332", + Network::Regtest => "http://localhost:18443", + } +} + +/// Prints detailed information about the selected network +/// +/// # Arguments +/// * `network` - A reference to the Network enum +fn print_network_details(network: &Network) { + match network { + Network::Mainnet => { + println!("Network: Mainnet"); + println!("Description: The main Bitcoin network (production)"); + println!("RPC Port: 8332"); + println!("P2P Port: 8333"); + println!("Chain ID: 0"); + } + Network::Testnet => { + println!("Network: Testnet"); + println!("Description: Bitcoin test network for development"); + println!("RPC Port: 18332"); + println!("P2P Port: 18333"); + println!("Chain ID: 1"); + } + Network::Regtest => { + println!("Network: Regtest"); + println!("Description: Local regression test network"); + println!("RPC Port: 18443"); + println!("P2P Port: 18444"); + println!("Chain ID: 1"); + } + } +} + +/// Returns the network name as a string +fn get_network_name(network: &Network) -> &str { + match network { + Network::Mainnet => "Mainnet", + Network::Testnet => "Testnet", + Network::Regtest => "Regtest", + } +} + +fn main() { + println!("=== Task 3: Enums & Pattern Matching ===\n"); + + // Create instances of each network + let networks = vec![ + Network::Mainnet, + Network::Testnet, + Network::Regtest, + ]; + + // Iterate through networks and display information + for network in networks { + println!("--- {} ---", get_network_name(&network)); + print_network_details(&network); + println!("RPC URL: {}\n", get_rpc_url(&network)); + } + + // Example: Using pattern matching directly + println!("=== Direct Pattern Matching Example ===\n"); + + let selected_network = Network::Regtest; + + match selected_network { + Network::Mainnet => println!("You selected the production network"), + Network::Testnet => println!("You selected the test network"), + Network::Regtest => println!("You selected the local regression test network"), + } + + println!("\nRPC URL for {:?}: {}", selected_network, get_rpc_url(&selected_network)); +} + diff --git a/submissions/Week-1/Note.md b/submissions/Week-1/Note.md deleted file mode 100644 index 00408f4..0000000 --- a/submissions/Week-1/Note.md +++ /dev/null @@ -1,187 +0,0 @@ -### -Submission_Week 1 -*Learning the fundamentals on Bitcoin -During week one our focus was on fundamentals of Bitcoin and how to setup the bitcoin core on my device. - -This week I was able to: - -- Run a Bitcoin node in regtest mode, -- Explore blocks, transactions, and the mempool, -- Simulate simple transactions between wallets, -- Understand how UTXOs power Bitcoin. - - -## Setting up bitcoin core - -Setting up bitcoin core on my machine through the following steps: - -- Download the gzip from the [official website](https://bitcoincore.org/en/download/). -- cd to Downloads then run - ```bash - > cd Downloads - ~./Downloads > tar -xzf (file_name) - ``` -- Then run: - ```bash - > sudo install -m 0755 -o root -g root -t /usr/local/bin bitcoin-30.1/bin/* - ``` - This command copies the extracted files from the g-zip to the local user binary folder so it can get globally executed. -- To confirm if everything is fine, run bitcoin-cli --version as in the image below: -- Next is to create a default bitcoin directory in our root folder and also create a default _bitcoin.conf_ inside the directory: - - ```bash - > mkdir ~./bitcoin - ``` - - The conf file would contain the configurations on which the bitcoin daemon would run - -- To create the configuration file, run the following command: - - ```bash - > vim ~./bitcoin/bitcoin.conf - ``` - - You can either use vim or any preferred text editor. - When the editor opened, I added the following config: - - ```text - regtest=1 - daemon=1 - ``` - - Setting our environment to regtest and to run the daemon in development mode - -- Next is to run the bitcoin daemon using the following command: - -```bash -> bitcoind -``` -- This confirms the whole setup. -### -Verifying the Node - -First, I verified that my Bitcoin node was running correctly in regtest mode: - -``` -bitcoin-cli getblockchaininfo -``` - -I checked that the `chain` parameter showed `regtest` and noted the current block height. - -![Blockchain Info](my-image-1.png) - -### Creating wallet - -A Bitcoin wallet is like your digital money bag that stores your keys, not your coins. Now u will be wondering where ur coin is been stored, it is stored in the blockchain
Source: ChatGPT - -To generate a bitcoin wallet on the bitcoin cli: - -```bash -> bitcoin-cli createwallet "sender" -``` - -The terminal should output something like: - -```json -{ - "name": "sender" -} -``` -![alt text](my-image-2.png) - -### Get a Wallet Address - ->To retrieve the wallet address that was created as seen above I used the getnewaddress and it brought out or displayed the wallet address of the wallet "sender" - -```bash ->bitcoin-cli getnewaddress -``` -The command returns the info about the wallet address -![alt text](my-image-3.png) - -### Generate Blocks - -> To generate blocks to a specific address we run the following code: -```bash -> bitcoin-cli generatetoaddress 101 "$(bitcoin-cli -regtest getnewaddress)"on the bitcoin cl -``` - -![alt text](my-image-3.png) - -> Running getbalance shows you the current cbalance of the address after it has generated new blocks and compiled -![alt text](my-image-4.png) - -### Exploring the blockchain -> To explore the blockchain, we run some commands like: - -> The getbestblockhash Returns the hash (ID) of the most recent block in the best (longest/most-work) blockchain. - -- getbestblockhash: - Returns the hash of the best (tip) block in the most-work fully-validated chain. - ![alt text](my-image-5.png) - ->The getblock Returns all details about a block, given its block hash. - -- getblock : -Returns information about the block specified -![alt text](my-image-5.png) - ->The getblockheader is a Bitcoin Core RPC command that gives you summary information about a block — but only its header, not the full list of transactions.Work with Wallets: Get cWork with Wallets: Get comfortable managing multiple wallets and addresses.omfortable managing multiple wallets and addresses. - -- getblockheader : -Returns a full summary of information of a block -![alt text](my-image-6.png) - -### Work with Wallets: Get comfortable managing multiple wallets and addresses. -- I crgenerated another bitcoin wallet on the bitcoin cli called "receiver": - -```bash -> bitcoin-cli createwallet "receiver" -``` - -The terminal should output something like: - -```json -{ - "name": "receiver" -} -``` -![alt text](my-image-7.png) - -```bash ->bitcoin-cli getnewaddress -``` -This command above returns the info about the wallet address -![alt text](my-image-7.png) - -### Sending and Tracking Transactions: - -To send coins between addresses, we use sendtoaddress - -```bash ->bitcoin-cli -rpcwallet=sender sendtoaddress "recipient_bitcoin_address" amount "optional_comment" -``` -Added this config to the bitcoin.conf file - -```text -fallbackfee=0.0002 -txindex=1 -``` -The command returns the transaction hash -![alt text](my-image-7.png) - -To check the transaction details, we run gettransaction -![alt text](my-image-7.png) - -### 6. Inspect UTXOs: Send and Track Transactions: -- To get all the information about all your spendable outputs of the mined blocks under the senders address we use the listunspent. -- Record details like txid, vout, and amount. - -```bash ->bitcoin-cli -rpcwallet=sender listunspent -``` - -To check the transaction details, we run listunspent -![alt text](my-image-8.png) - - - -