Skip to content
Open
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
105 changes: 105 additions & 0 deletions code/src/Birdmannn_week_2/LEARNING_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -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.

50 changes: 50 additions & 0 deletions code/src/Birdmannn_week_2/task_1.rs
Original file line number Diff line number Diff line change
@@ -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);
}

61 changes: 61 additions & 0 deletions code/src/Birdmannn_week_2/task_2.rs
Original file line number Diff line number Diff line change
@@ -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)");
}

101 changes: 101 additions & 0 deletions code/src/Birdmannn_week_2/task_3.rs
Original file line number Diff line number Diff line change
@@ -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));
}

Loading