kaccy-bitcoin 0.2.0

Bitcoin integration for Kaccy Protocol - HD wallets, UTXO management, and transaction building
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Transaction monitoring

use bitcoin::Amount;
use serde::Serialize;
use std::sync::Arc;

use crate::client::BitcoinClient;
use crate::error::{BitcoinError, Result};

/// Payment status with details
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum PaymentStatus {
    /// No payment received yet
    NotReceived,
    /// Payment received but waiting for confirmations
    Pending {
        /// Amount received so far (may include mempool balance).
        received_amount: Amount,
        /// Number of confirmations the payment currently has.
        confirmations: u32,
    },
    /// Payment received but amount is incorrect
    Underpaid {
        /// The amount that was expected.
        expected: Amount,
        /// The amount that was actually received.
        received: Amount,
    },
    /// Payment received but amount is more than expected
    Overpaid {
        /// The amount that was expected.
        expected: Amount,
        /// The amount that was actually received.
        received: Amount,
    },
    /// Payment confirmed with required confirmations
    Confirmed {
        /// Total amount received and confirmed.
        received_amount: Amount,
        /// Number of confirmations at the time of confirmation.
        confirmations: u32,
    },
}

impl PaymentStatus {
    /// Check if payment can proceed (confirmed or overpaid with enough confirmations)
    pub fn is_actionable(&self) -> bool {
        matches!(
            self,
            PaymentStatus::Confirmed { .. } | PaymentStatus::Overpaid { .. }
        )
    }
}

/// Monitors payments for pending orders
pub struct PaymentMonitor {
    client: Arc<BitcoinClient>,
    required_confirmations: u32,
}

impl PaymentMonitor {
    /// Create a new `PaymentMonitor` with the given client and confirmation threshold.
    pub fn new(client: Arc<BitcoinClient>, required_confirmations: u32) -> Self {
        Self {
            client,
            required_confirmations,
        }
    }

    /// Check payment status for an address
    pub fn check_payment(&self, address: &str, expected_amount: Amount) -> Result<PaymentStatus> {
        let addr: bitcoin::Address<bitcoin::address::NetworkUnchecked> = address
            .parse()
            .map_err(|e| BitcoinError::InvalidAddress(format!("{:?}", e)))?;

        let checked_addr = addr.assume_checked();

        // Check with 0 confirmations first (mempool)
        let unconfirmed = self
            .client
            .get_received_by_address(&checked_addr, Some(0))?;

        if unconfirmed == Amount::ZERO {
            return Ok(PaymentStatus::NotReceived);
        }

        // Check with required confirmations
        let confirmed = self
            .client
            .get_received_by_address(&checked_addr, Some(self.required_confirmations))?;

        // Estimate confirmations based on difference
        let estimated_confirmations = if confirmed >= unconfirmed {
            self.required_confirmations
        } else if confirmed > Amount::ZERO {
            // Some confirmations but not enough
            self.required_confirmations / 2 // Rough estimate
        } else {
            0
        };

        // Determine status based on amount and confirmations
        if confirmed >= expected_amount {
            if confirmed > expected_amount {
                Ok(PaymentStatus::Overpaid {
                    expected: expected_amount,
                    received: confirmed,
                })
            } else {
                Ok(PaymentStatus::Confirmed {
                    received_amount: confirmed,
                    confirmations: self.required_confirmations,
                })
            }
        } else if unconfirmed >= expected_amount {
            // Received full amount but waiting for confirmations
            Ok(PaymentStatus::Pending {
                received_amount: unconfirmed,
                confirmations: estimated_confirmations,
            })
        } else if unconfirmed > Amount::ZERO {
            // Received some but not enough
            Ok(PaymentStatus::Underpaid {
                expected: expected_amount,
                received: unconfirmed,
            })
        } else {
            Ok(PaymentStatus::NotReceived)
        }
    }

    /// Check payment and get detailed info including transaction ID
    pub fn check_payment_detailed(
        &self,
        address: &str,
        expected_amount: Amount,
    ) -> Result<PaymentDetails> {
        let status = self.check_payment(address, expected_amount)?;

        Ok(PaymentDetails {
            address: address.to_string(),
            expected_amount,
            status,
            txid: None, // Would need additional lookup for txid
        })
    }

    /// Get required confirmations setting
    pub fn required_confirmations(&self) -> u32 {
        self.required_confirmations
    }
}

/// Detailed payment information
#[derive(Debug, Clone, Serialize)]
pub struct PaymentDetails {
    /// Bitcoin address being monitored for the payment.
    pub address: String,
    /// Amount expected for this payment.
    pub expected_amount: Amount,
    /// Current status of the payment.
    pub status: PaymentStatus,
    /// Transaction ID of the payment, if known.
    pub txid: Option<String>,
}

/// Pending order for monitoring
#[derive(Debug, Clone)]
pub struct PendingOrder {
    /// Unique identifier for this order.
    pub order_id: uuid::Uuid,
    /// Bitcoin address assigned for this order's payment.
    pub address: String,
    /// Payment amount expected for this order.
    pub expected_amount: Amount,
    /// UTC timestamp when this order was created.
    pub created_at: chrono::DateTime<chrono::Utc>,
}

/// Payment event emitted by the monitor
#[derive(Debug, Clone)]
pub enum PaymentEvent {
    /// Payment received and confirmed
    Confirmed {
        /// Unique identifier of the order whose payment was confirmed.
        order_id: uuid::Uuid,
        /// Confirmed amount received.
        amount: Amount,
        /// Number of block confirmations at the time of this event.
        confirmations: u32,
    },
    /// Payment pending (in mempool or insufficient confirmations)
    Pending {
        /// Unique identifier of the order awaiting payment.
        order_id: uuid::Uuid,
        /// Amount detected so far (may be unconfirmed).
        amount: Amount,
        /// Current number of confirmations.
        confirmations: u32,
    },
    /// Underpayment detected
    Underpaid {
        /// Unique identifier of the underpaid order.
        order_id: uuid::Uuid,
        /// Amount that was expected.
        expected: Amount,
        /// Amount that was actually received.
        received: Amount,
    },
    /// Overpayment detected
    Overpaid {
        /// Unique identifier of the overpaid order.
        order_id: uuid::Uuid,
        /// Amount that was expected.
        expected: Amount,
        /// Amount that was actually received.
        received: Amount,
    },
    /// Order expired without payment
    Expired {
        /// Unique identifier of the expired order.
        order_id: uuid::Uuid,
    },
}

/// Configuration for payment monitor background task
#[derive(Debug, Clone)]
pub struct MonitorConfig {
    /// Polling interval in seconds
    pub poll_interval_secs: u64,
    /// Order expiry time in hours
    pub order_expiry_hours: u32,
    /// Required confirmations for payment to be confirmed
    pub required_confirmations: u32,
}

impl Default for MonitorConfig {
    fn default() -> Self {
        Self {
            poll_interval_secs: 30,
            order_expiry_hours: 24,
            required_confirmations: 3,
        }
    }
}

/// Background payment monitoring task
pub struct PaymentMonitorTask {
    client: Arc<BitcoinClient>,
    config: MonitorConfig,
    /// Channel to send payment events
    event_sender: Option<tokio::sync::mpsc::Sender<PaymentEvent>>,
    /// Shutdown signal
    shutdown: tokio::sync::watch::Receiver<bool>,
}

impl PaymentMonitorTask {
    /// Create a new payment monitor task
    pub fn new(
        client: Arc<BitcoinClient>,
        config: MonitorConfig,
        shutdown: tokio::sync::watch::Receiver<bool>,
    ) -> Self {
        Self {
            client,
            config,
            event_sender: None,
            shutdown,
        }
    }

    /// Set the event sender channel
    pub fn with_event_sender(mut self, sender: tokio::sync::mpsc::Sender<PaymentEvent>) -> Self {
        self.event_sender = Some(sender);
        self
    }

    /// Start the monitoring loop (call in a spawned task)
    pub async fn run<F, Fut>(&mut self, get_pending_orders: F)
    where
        F: Fn() -> Fut,
        Fut: std::future::Future<Output = Vec<PendingOrder>>,
    {
        let poll_interval = std::time::Duration::from_secs(self.config.poll_interval_secs);

        tracing::info!(
            poll_interval_secs = self.config.poll_interval_secs,
            required_confirmations = self.config.required_confirmations,
            "Payment monitor started"
        );

        loop {
            // Check shutdown signal
            if *self.shutdown.borrow() {
                tracing::info!("Payment monitor shutting down");
                break;
            }

            // Get pending orders
            let orders = get_pending_orders().await;

            if !orders.is_empty() {
                tracing::debug!(count = orders.len(), "Checking pending orders");
            }

            // Check each order
            for order in orders {
                if let Err(e) = self.check_order(&order).await {
                    tracing::warn!(
                        order_id = %order.order_id,
                        error = %e,
                        "Error checking payment"
                    );
                }
            }

            // Wait for next poll interval or shutdown
            tokio::select! {
                _ = tokio::time::sleep(poll_interval) => {}
                _ = self.shutdown.changed() => {
                    if *self.shutdown.borrow() {
                        tracing::info!("Payment monitor received shutdown signal");
                        break;
                    }
                }
            }
        }
    }

    /// Check payment status for a single order
    async fn check_order(&self, order: &PendingOrder) -> Result<()> {
        let monitor = PaymentMonitor::new(self.client.clone(), self.config.required_confirmations);

        // Check for expiry first
        let age = chrono::Utc::now() - order.created_at;
        if age.num_hours() >= self.config.order_expiry_hours as i64 {
            self.emit_event(PaymentEvent::Expired {
                order_id: order.order_id,
            })
            .await;
            return Ok(());
        }

        let status = monitor.check_payment(&order.address, order.expected_amount)?;

        let event = match status {
            PaymentStatus::Confirmed {
                received_amount,
                confirmations,
            } => Some(PaymentEvent::Confirmed {
                order_id: order.order_id,
                amount: received_amount,
                confirmations,
            }),
            PaymentStatus::Pending {
                received_amount,
                confirmations,
            } => Some(PaymentEvent::Pending {
                order_id: order.order_id,
                amount: received_amount,
                confirmations,
            }),
            PaymentStatus::Underpaid { expected, received } => Some(PaymentEvent::Underpaid {
                order_id: order.order_id,
                expected,
                received,
            }),
            PaymentStatus::Overpaid { expected, received } => Some(PaymentEvent::Overpaid {
                order_id: order.order_id,
                expected,
                received,
            }),
            PaymentStatus::NotReceived => None,
        };

        if let Some(event) = event {
            self.emit_event(event).await;
        }

        Ok(())
    }

    /// Emit a payment event
    async fn emit_event(&self, event: PaymentEvent) {
        tracing::info!(
            event = ?event,
            "Payment event"
        );

        if let Some(ref sender) = self.event_sender {
            if let Err(e) = sender.send(event.clone()).await {
                tracing::error!(error = %e, "Failed to send payment event");
            }
        }
    }
}

/// Create a shutdown signal pair for the monitor
pub fn create_shutdown_signal() -> (
    tokio::sync::watch::Sender<bool>,
    tokio::sync::watch::Receiver<bool>,
) {
    tokio::sync::watch::channel(false)
}