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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! PSBT workflow manager for multi-signer coordination
//!
//! Provides tools for managing complex PSBT signing workflows with multiple signers.

use crate::error::BitcoinError;
use bitcoin::psbt::Psbt;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// PSBT version
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PsbtVersion {
    /// PSBT version 0 (BIP 174)
    V0,
    /// PSBT version 2 (BIP 370)
    V2,
}

/// Signer role in the workflow
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SignerRole {
    /// Signer identifier
    pub id: String,
    /// Human-readable name
    pub name: String,
    /// Required to sign
    pub required: bool,
}

/// Signing status for a signer
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum SigningStatus {
    /// Awaiting signature
    Pending,
    /// Signature provided
    Signed,
    /// Signature rejected
    Rejected,
    /// Timeout
    Timeout,
}

/// Signature record for tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SignatureRecord {
    /// Signer role
    pub signer: SignerRole,
    /// Signing status
    pub status: SigningStatus,
    /// When the signature was requested
    pub requested_at: chrono::DateTime<chrono::Utc>,
    /// When the signature was provided (if signed)
    pub signed_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Additional notes
    pub notes: Option<String>,
}

/// PSBT workflow state
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorkflowState {
    /// Initial state - PSBT created
    Created,
    /// Collecting signatures
    Collecting,
    /// All required signatures collected
    Complete,
    /// Workflow cancelled
    Cancelled,
    /// Workflow expired
    Expired,
}

/// PSBT workflow for coordinating multi-signer transactions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PsbtWorkflow {
    /// Workflow ID
    pub id: String,
    /// PSBT data (base64)
    pub psbt_base64: String,
    /// PSBT version
    pub version: PsbtVersion,
    /// Current workflow state
    pub state: WorkflowState,
    /// Signature records
    pub signatures: Vec<SignatureRecord>,
    /// Required signers
    pub required_signers: HashSet<String>,
    /// Created timestamp
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// Expiration timestamp
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

impl PsbtWorkflow {
    /// Create a new PSBT workflow
    pub fn new(
        id: String,
        psbt_base64: String,
        signers: Vec<SignerRole>,
        expires_at: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Self {
        let now = chrono::Utc::now();
        let required_signers: HashSet<String> = signers
            .iter()
            .filter(|s| s.required)
            .map(|s| s.id.clone())
            .collect();

        let signatures = signers
            .into_iter()
            .map(|signer| SignatureRecord {
                signer,
                status: SigningStatus::Pending,
                requested_at: now,
                signed_at: None,
                notes: None,
            })
            .collect();

        Self {
            id,
            psbt_base64,
            version: PsbtVersion::V0,
            state: WorkflowState::Created,
            signatures,
            required_signers,
            created_at: now,
            expires_at,
            metadata: HashMap::new(),
        }
    }

    /// Record a signature from a signer
    pub fn record_signature(
        &mut self,
        signer_id: &str,
        psbt_base64: String,
    ) -> Result<(), BitcoinError> {
        if self.state == WorkflowState::Complete || self.state == WorkflowState::Cancelled {
            return Err(BitcoinError::InvalidTransaction(
                "Workflow is already completed or cancelled".to_string(),
            ));
        }

        // Check if expired
        if let Some(expires_at) = self.expires_at {
            if chrono::Utc::now() > expires_at {
                self.state = WorkflowState::Expired;
                return Err(BitcoinError::InvalidTransaction(
                    "Workflow has expired".to_string(),
                ));
            }
        }

        // Find the signer
        let signature = self
            .signatures
            .iter_mut()
            .find(|s| s.signer.id == signer_id)
            .ok_or_else(|| BitcoinError::InvalidTransaction("Signer not found".to_string()))?;

        if signature.status == SigningStatus::Signed {
            return Err(BitcoinError::InvalidTransaction(
                "Signer has already signed".to_string(),
            ));
        }

        // Update signature record
        signature.status = SigningStatus::Signed;
        signature.signed_at = Some(chrono::Utc::now());

        // Update PSBT
        self.psbt_base64 = psbt_base64;

        // Update state
        self.state = WorkflowState::Collecting;

        // Check if all required signatures are collected
        if self.is_complete() {
            self.state = WorkflowState::Complete;
        }

        Ok(())
    }

    /// Check if all required signatures are collected
    pub fn is_complete(&self) -> bool {
        self.required_signers.iter().all(|id| {
            self.signatures
                .iter()
                .any(|s| s.signer.id == *id && s.status == SigningStatus::Signed)
        })
    }

    /// Get pending signers
    pub fn pending_signers(&self) -> Vec<&SignerRole> {
        self.signatures
            .iter()
            .filter(|s| s.status == SigningStatus::Pending)
            .map(|s| &s.signer)
            .collect()
    }

    /// Cancel the workflow
    pub fn cancel(&mut self) {
        self.state = WorkflowState::Cancelled;
    }

    /// Check if workflow is expired
    pub fn is_expired(&self) -> bool {
        if let Some(expires_at) = self.expires_at {
            chrono::Utc::now() > expires_at
        } else {
            false
        }
    }

    /// Get the current PSBT
    pub fn get_psbt(&self) -> Result<Psbt, BitcoinError> {
        // Decode from base64
        use base64::Engine;
        let psbt_bytes = base64::engine::general_purpose::STANDARD
            .decode(&self.psbt_base64)
            .map_err(|e| BitcoinError::InvalidTransaction(format!("Invalid base64: {}", e)))?;

        Psbt::deserialize(&psbt_bytes)
            .map_err(|e| BitcoinError::InvalidTransaction(format!("Invalid PSBT: {}", e)))
    }
}

/// PSBT workflow manager
pub struct PsbtWorkflowManager {
    workflows: HashMap<String, PsbtWorkflow>,
}

impl PsbtWorkflowManager {
    /// Create a new workflow manager
    pub fn new() -> Self {
        Self {
            workflows: HashMap::new(),
        }
    }

    /// Create a new workflow
    pub fn create_workflow(
        &mut self,
        psbt_base64: String,
        signers: Vec<SignerRole>,
        expires_in_hours: Option<i64>,
    ) -> String {
        let id = uuid::Uuid::new_v4().to_string();
        let expires_at =
            expires_in_hours.map(|hours| chrono::Utc::now() + chrono::Duration::hours(hours));

        let workflow = PsbtWorkflow::new(id.clone(), psbt_base64, signers, expires_at);
        self.workflows.insert(id.clone(), workflow);

        id
    }

    /// Get a workflow by ID
    pub fn get_workflow(&self, id: &str) -> Option<&PsbtWorkflow> {
        self.workflows.get(id)
    }

    /// Get a mutable workflow by ID
    pub fn get_workflow_mut(&mut self, id: &str) -> Option<&mut PsbtWorkflow> {
        self.workflows.get_mut(id)
    }

    /// Record a signature
    pub fn record_signature(
        &mut self,
        workflow_id: &str,
        signer_id: &str,
        psbt_base64: String,
    ) -> Result<(), BitcoinError> {
        let workflow = self
            .get_workflow_mut(workflow_id)
            .ok_or_else(|| BitcoinError::InvalidTransaction("Workflow not found".to_string()))?;

        workflow.record_signature(signer_id, psbt_base64)
    }

    /// Cancel a workflow
    pub fn cancel_workflow(&mut self, id: &str) -> Result<(), BitcoinError> {
        let workflow = self
            .get_workflow_mut(id)
            .ok_or_else(|| BitcoinError::InvalidTransaction("Workflow not found".to_string()))?;

        workflow.cancel();
        Ok(())
    }

    /// List all workflows
    pub fn list_workflows(&self) -> Vec<&PsbtWorkflow> {
        self.workflows.values().collect()
    }

    /// List workflows by state
    pub fn list_workflows_by_state(&self, state: WorkflowState) -> Vec<&PsbtWorkflow> {
        self.workflows
            .values()
            .filter(|w| w.state == state)
            .collect()
    }

    /// Clean up expired workflows
    pub fn cleanup_expired(&mut self) -> usize {
        let expired_ids: Vec<String> = self
            .workflows
            .iter()
            .filter(|(_, w)| w.is_expired())
            .map(|(id, _)| id.clone())
            .collect();

        let count = expired_ids.len();

        for id in expired_ids {
            if let Some(workflow) = self.workflows.get_mut(&id) {
                workflow.state = WorkflowState::Expired;
            }
        }

        count
    }
}

impl Default for PsbtWorkflowManager {
    fn default() -> Self {
        Self::new()
    }
}

/// PSBT template for common transaction patterns
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PsbtTemplate {
    /// Template name
    pub name: String,
    /// Template description
    pub description: String,
    /// Number of inputs
    pub num_inputs: usize,
    /// Number of outputs
    pub num_outputs: usize,
    /// Required signers configuration
    pub signers: Vec<SignerRole>,
}

impl PsbtTemplate {
    /// Create a 2-of-3 multisig template
    pub fn multisig_2_of_3() -> Self {
        Self {
            name: "2-of-3 Multisig".to_string(),
            description: "Standard 2-of-3 multisig transaction".to_string(),
            num_inputs: 1,
            num_outputs: 2,
            signers: vec![
                SignerRole {
                    id: "signer_1".to_string(),
                    name: "Primary Signer".to_string(),
                    required: true,
                },
                SignerRole {
                    id: "signer_2".to_string(),
                    name: "Secondary Signer".to_string(),
                    required: true,
                },
                SignerRole {
                    id: "signer_3".to_string(),
                    name: "Backup Signer".to_string(),
                    required: false,
                },
            ],
        }
    }

    /// Create a single-sig with co-signer template
    pub fn single_with_cosigner() -> Self {
        Self {
            name: "Single + Co-signer".to_string(),
            description: "Primary signer with optional co-signer approval".to_string(),
            num_inputs: 1,
            num_outputs: 2,
            signers: vec![
                SignerRole {
                    id: "primary".to_string(),
                    name: "Primary Signer".to_string(),
                    required: true,
                },
                SignerRole {
                    id: "cosigner".to_string(),
                    name: "Co-signer".to_string(),
                    required: false,
                },
            ],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_psbt_workflow_creation() {
        let signers = vec![
            SignerRole {
                id: "signer1".to_string(),
                name: "Signer 1".to_string(),
                required: true,
            },
            SignerRole {
                id: "signer2".to_string(),
                name: "Signer 2".to_string(),
                required: true,
            },
        ];

        let workflow = PsbtWorkflow::new(
            "test_workflow".to_string(),
            "test_psbt".to_string(),
            signers,
            None,
        );

        assert_eq!(workflow.state, WorkflowState::Created);
        assert_eq!(workflow.signatures.len(), 2);
        assert!(!workflow.is_complete());
    }

    #[test]
    fn test_workflow_signature_recording() {
        let signers = vec![SignerRole {
            id: "signer1".to_string(),
            name: "Signer 1".to_string(),
            required: true,
        }];

        let mut workflow = PsbtWorkflow::new(
            "test_workflow".to_string(),
            "test_psbt".to_string(),
            signers,
            None,
        );

        let result = workflow.record_signature("signer1", "signed_psbt".to_string());
        assert!(result.is_ok());
        assert_eq!(workflow.state, WorkflowState::Complete);
        assert!(workflow.is_complete());
    }

    #[test]
    fn test_workflow_manager() {
        let mut manager = PsbtWorkflowManager::new();

        let signers = vec![SignerRole {
            id: "signer1".to_string(),
            name: "Signer 1".to_string(),
            required: true,
        }];

        let workflow_id = manager.create_workflow("test_psbt".to_string(), signers, Some(24));

        assert!(manager.get_workflow(&workflow_id).is_some());

        let result = manager.record_signature(&workflow_id, "signer1", "signed_psbt".to_string());
        assert!(result.is_ok());

        let workflow = manager.get_workflow(&workflow_id).unwrap();
        assert!(workflow.is_complete());
    }

    #[test]
    fn test_psbt_template_multisig() {
        let template = PsbtTemplate::multisig_2_of_3();
        assert_eq!(template.signers.len(), 3);
        assert_eq!(template.signers.iter().filter(|s| s.required).count(), 2);
    }

    #[test]
    fn test_psbt_template_single_cosigner() {
        let template = PsbtTemplate::single_with_cosigner();
        assert_eq!(template.signers.len(), 2);
        assert_eq!(template.signers.iter().filter(|s| s.required).count(), 1);
    }

    #[test]
    fn test_workflow_expiration() {
        let signers = vec![SignerRole {
            id: "signer1".to_string(),
            name: "Signer 1".to_string(),
            required: true,
        }];

        let expired_time = chrono::Utc::now() - chrono::Duration::hours(1);
        let workflow = PsbtWorkflow::new(
            "test_workflow".to_string(),
            "test_psbt".to_string(),
            signers,
            Some(expired_time),
        );

        assert!(workflow.is_expired());
    }

    #[test]
    fn test_pending_signers() {
        let signers = vec![
            SignerRole {
                id: "signer1".to_string(),
                name: "Signer 1".to_string(),
                required: true,
            },
            SignerRole {
                id: "signer2".to_string(),
                name: "Signer 2".to_string(),
                required: true,
            },
        ];

        let mut workflow = PsbtWorkflow::new(
            "test_workflow".to_string(),
            "test_psbt".to_string(),
            signers,
            None,
        );

        let pending = workflow.pending_signers();
        assert_eq!(pending.len(), 2);

        workflow
            .record_signature("signer1", "signed_psbt".to_string())
            .ok();

        let pending = workflow.pending_signers();
        assert_eq!(pending.len(), 1);
        assert_eq!(pending[0].id, "signer2");
    }
}