blvm-node 0.1.2

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Payment RPC commands
//!
//! Provides JSON-RPC methods for payment operations including:
//! - Creating payment requests
//! - Creating CTV covenant proofs
//! - Querying payment state
//! - Settlement monitoring

use crate::payment::processor::PaymentError;
use crate::payment::state_machine::{PaymentState, PaymentStateMachine};
use crate::rpc::params::{param_bool_default, param_str};
use crate::utils::current_timestamp;
use blvm_protocol::payment::PaymentOutput;
use serde_json::{json, Value};
use std::sync::Arc;
use tracing::{debug, error};

/// Default number of confirmations before considering a payment "safe for release" (RPC and REST).
pub const DEFAULT_SAFE_DEPTH: u32 = 6;

/// Payment RPC handler
#[derive(Clone)]
pub struct PaymentRpc {
    state_machine: Option<Arc<PaymentStateMachine>>,
}

impl PaymentRpc {
    /// Create a new payment RPC handler
    pub fn new() -> Self {
        Self {
            state_machine: None,
        }
    }

    /// Create with payment state machine
    pub fn with_state_machine(state_machine: Arc<PaymentStateMachine>) -> Self {
        Self {
            state_machine: Some(state_machine),
        }
    }

    /// Get payment state machine (returns error if not available)
    fn get_state_machine(&self) -> Result<Arc<PaymentStateMachine>, PaymentError> {
        self.state_machine
            .as_ref()
            .ok_or_else(|| {
                PaymentError::ProcessingError("Payment state machine not available".to_string())
            })
            .map(|sm| Arc::clone(sm))
    }

    /// Create a payment request
    ///
    /// Params: ["outputs", "merchant_data", "create_covenant"]
    /// - outputs: Array of payment outputs [{amount, script_pubkey}, ...]
    /// - merchant_data: Optional merchant data (hex string)
    /// - create_covenant: Whether to create CTV proof immediately (default: false)
    ///
    /// Returns: {payment_id, covenant_proof (optional)}
    pub async fn create_payment_request(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: createpaymentrequest");

        let state_machine = self.get_state_machine()?;

        // Parse outputs
        let outputs_value = params.get(0).ok_or_else(|| {
            PaymentError::ProcessingError("Missing 'outputs' parameter".to_string())
        })?;

        let outputs: Vec<PaymentOutput> = serde_json::from_value(outputs_value.clone())
            .map_err(|e| PaymentError::ProcessingError(format!("Invalid outputs format: {}", e)))?;

        // Parse merchant_data (optional)
        let merchant_data = params
            .get(1)
            .and_then(|v| v.as_str())
            .and_then(|s| hex::decode(s).ok());

        // Parse create_covenant (optional, default: false)
        let create_covenant = param_bool_default(params, 2, false);

        // Create payment request
        let (payment_id, covenant_proof) = state_machine
            .create_payment_request(outputs, merchant_data, create_covenant)
            .await?;

        // Build response
        let mut response = json!({
            "payment_id": payment_id,
        });

        #[cfg(feature = "ctv")]
        {
            if let Some(proof) = covenant_proof {
                response["covenant_proof"] = serde_json::to_value(&proof).map_err(|e| {
                    PaymentError::ProcessingError(format!(
                        "Failed to serialize covenant proof: {}",
                        e
                    ))
                })?;
            }
        }

        Ok(response)
    }

    /// Create CTV covenant proof for existing payment request
    ///
    /// Params: ["payment_request_id"]
    /// - payment_request_id: ID of the payment request
    ///
    /// Returns: {covenant_proof}
    #[cfg(feature = "ctv")]
    pub async fn create_covenant_proof(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: createcovenantproof");

        let state_machine = self.get_state_machine()?;

        let payment_request_id = params.get(0).and_then(|v| v.as_str()).ok_or_else(|| {
            PaymentError::ProcessingError("Missing 'payment_request_id' parameter".to_string())
        })?;

        let covenant_proof = state_machine
            .create_covenant_proof(payment_request_id)
            .await?;

        Ok(serde_json::to_value(&covenant_proof).map_err(|e| {
            PaymentError::ProcessingError(format!("Failed to serialize covenant proof: {}", e))
        })?)
    }

    /// Get payment state
    ///
    /// Params: ["payment_request_id"]
    /// - payment_request_id: ID of the payment request
    ///
    /// Returns: {state, details}
    pub async fn get_payment_state(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: getpaymentstate");

        let state_machine = self.get_state_machine()?;

        let payment_request_id = param_str(params, 0).map(String::from).ok_or_else(|| {
            PaymentError::ProcessingError("Missing 'payment_request_id' parameter".to_string())
        })?;

        let state = state_machine.get_payment_state(&payment_request_id).await?;

        // Convert state to JSON
        let state_json = match &state {
            PaymentState::RequestCreated { request_id } => {
                json!({
                    "state": "request_created",
                    "request_id": request_id,
                })
            }
            #[cfg(feature = "ctv")]
            PaymentState::ProofCreated {
                request_id,
                covenant_proof,
            } => {
                json!({
                    "state": "proof_created",
                    "request_id": request_id,
                    "covenant_proof": serde_json::to_value(covenant_proof)
                        .map_err(|e| PaymentError::ProcessingError(
                            format!("Failed to serialize covenant proof: {}", e)
                        ))?,
                })
            }
            #[cfg(feature = "ctv")]
            PaymentState::ProofBroadcast {
                request_id,
                covenant_proof,
                broadcast_peers,
            } => {
                json!({
                    "state": "proof_broadcast",
                    "request_id": request_id,
                    "covenant_proof": serde_json::to_value(covenant_proof)
                        .map_err(|e| PaymentError::ProcessingError(
                            format!("Failed to serialize covenant proof: {}", e)
                        ))?,
                    "broadcast_peers": broadcast_peers.len(),
                })
            }
            PaymentState::InMempool {
                request_id,
                tx_hash,
            } => {
                json!({
                    "state": "in_mempool",
                    "request_id": request_id,
                    "tx_hash": hex::encode(tx_hash),
                })
            }
            PaymentState::Settled {
                request_id,
                tx_hash,
                block_hash,
                confirmation_count,
                ..
            } => {
                json!({
                    "state": "settled",
                    "request_id": request_id,
                    "tx_hash": hex::encode(tx_hash),
                    "block_hash": hex::encode(block_hash),
                    "confirmation_count": confirmation_count,
                    "safe_for_release": *confirmation_count >= DEFAULT_SAFE_DEPTH,
                })
            }
            PaymentState::ReorgPending {
                request_id,
                tx_hash,
                reason,
                ..
            } => {
                json!({
                    "state": "reorg_pending",
                    "request_id": request_id,
                    "tx_hash": hex::encode(tx_hash),
                    "reason": reason,
                })
            }
            PaymentState::Failed { request_id, reason } => {
                json!({
                    "state": "failed",
                    "request_id": request_id,
                    "reason": reason,
                })
            }
            #[cfg(not(feature = "ctv"))]
            #[allow(unreachable_patterns)]
            PaymentState::ProofCreated { .. } | PaymentState::ProofBroadcast { .. } => {
                unreachable!("CTV variants should not exist when CTV feature is disabled")
            }
        };

        Ok(state_json)
    }

    /// List all payment states
    ///
    /// Params: [] (no parameters)
    ///
    /// Returns: {payments: [{payment_id, state, ...}, ...]}
    pub async fn list_payments(&self, _params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: listpayments");

        let state_machine = self.get_state_machine()?;

        let states = state_machine.list_payment_states();

        let payments: Vec<Value> = states
            .iter()
            .map(|(payment_id, state)| {
                let state_str = match state {
                    PaymentState::RequestCreated { .. } => "request_created",
                    #[cfg(feature = "ctv")]
                    PaymentState::ProofCreated { .. } => "proof_created",
                    #[cfg(feature = "ctv")]
                    PaymentState::ProofBroadcast { .. } => "proof_broadcast",
                    #[cfg(not(feature = "ctv"))]
                    PaymentState::ProofCreated { .. } | PaymentState::ProofBroadcast { .. } => {
                        unreachable!("CTV variants should not exist when CTV feature is disabled")
                    }
                    PaymentState::InMempool { .. } => "in_mempool",
                    PaymentState::Settled { .. } => "settled",
                    PaymentState::ReorgPending { .. } => "reorg_pending",
                    PaymentState::Failed { .. } => "failed",
                };

                json!({
                    "payment_id": payment_id,
                    "state": state_str,
                })
            })
            .collect();

        Ok(json!({
            "payments": payments,
            "count": payments.len(),
        }))
    }

    // ========== VAULT RPC METHODS ==========

    /// Create a vault
    ///
    /// Params: ["vault_id", "deposit_amount", "withdrawal_script", "config"]
    /// - vault_id: Unique identifier for the vault
    /// - deposit_amount: Amount to deposit (satoshis)
    /// - withdrawal_script: Script pubkey for withdrawal (hex)
    /// - config: Vault configuration (optional)
    ///
    /// Returns: {vault_id, vault_state}
    #[cfg(feature = "ctv")]
    pub async fn create_vault(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: createvault");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let vault_engine = state_machine.vault_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Vault engine not available".to_string())
        })?;

        let vault_id = params["vault_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("vault_id required".to_string()))?
            .to_string();

        let deposit_amount = params["deposit_amount"]
            .as_u64()
            .ok_or_else(|| PaymentError::ProcessingError("deposit_amount required".to_string()))?;

        let withdrawal_script_hex = params["withdrawal_script"].as_str().ok_or_else(|| {
            PaymentError::ProcessingError("withdrawal_script required".to_string())
        })?;
        let withdrawal_script = hex::decode(withdrawal_script_hex).map_err(|e| {
            PaymentError::ProcessingError(format!("Invalid withdrawal_script: {}", e))
        })?;

        let config = if params["config"].is_object() {
            serde_json::from_value(params["config"].clone())
                .unwrap_or_else(|_| crate::payment::vault::VaultConfig::default())
        } else {
            crate::payment::vault::VaultConfig::default()
        };

        let vault_state =
            vault_engine.create_vault(&vault_id, deposit_amount, withdrawal_script, config)?;

        Ok(json!({
            "vault_id": vault_state.vault_id,
            "vault_state": serde_json::to_value(&vault_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Unvault funds (first step of withdrawal)
    ///
    /// Params: ["vault_id", "unvault_script"]
    /// - vault_id: Vault identifier
    /// - unvault_script: Script pubkey for unvault output (hex)
    ///
    /// Returns: {vault_id, vault_state}
    #[cfg(feature = "ctv")]
    pub async fn unvault(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: unvault");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let vault_engine = state_machine.vault_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Vault engine not available".to_string())
        })?;

        let vault_id = params["vault_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("vault_id required".to_string()))?
            .to_string();

        let unvault_script_hex = params["unvault_script"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("unvault_script required".to_string()))?;
        let unvault_script = hex::decode(unvault_script_hex)
            .map_err(|e| PaymentError::ProcessingError(format!("Invalid unvault_script: {}", e)))?;

        let vault_state = vault_engine
            .get_vault(&vault_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Vault not found".to_string()))?;

        let updated_vault_state = vault_engine.unvault(&vault_state, unvault_script)?;

        Ok(json!({
            "vault_id": updated_vault_state.vault_id,
            "vault_state": serde_json::to_value(&updated_vault_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Withdraw from vault
    ///
    /// Params: ["vault_id", "withdrawal_script", "current_block_height"]
    /// - vault_id: Vault identifier
    /// - withdrawal_script: Final destination script (hex)
    /// - current_block_height: Current blockchain height
    ///
    /// Returns: {vault_id, vault_state}
    #[cfg(feature = "ctv")]
    pub async fn withdraw_from_vault(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: withdrawfromvault");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let vault_engine = state_machine.vault_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Vault engine not available".to_string())
        })?;

        let vault_id = params["vault_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("vault_id required".to_string()))?
            .to_string();

        let vault_state = vault_engine
            .get_vault(&vault_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Vault not found".to_string()))?;

        let withdrawal_script_hex = params["withdrawal_script"].as_str().ok_or_else(|| {
            PaymentError::ProcessingError("withdrawal_script required".to_string())
        })?;
        let withdrawal_script = hex::decode(withdrawal_script_hex).map_err(|e| {
            PaymentError::ProcessingError(format!("Invalid withdrawal_script: {}", e))
        })?;

        let current_block_height = params["current_block_height"].as_u64().ok_or_else(|| {
            PaymentError::ProcessingError("current_block_height required".to_string())
        })?;

        let updated_vault_state =
            vault_engine.withdraw(&vault_state, withdrawal_script, current_block_height)?;

        Ok(json!({
            "vault_id": updated_vault_state.vault_id,
            "vault_state": serde_json::to_value(&updated_vault_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Get vault state
    ///
    /// Params: ["vault_id"]
    /// - vault_id: Vault identifier
    ///
    /// Returns: {vault_id, vault_state}
    #[cfg(feature = "ctv")]
    pub async fn get_vault_state(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: getvaultstate");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let vault_engine = state_machine.vault_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Vault engine not available".to_string())
        })?;

        let vault_id = params["vault_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("vault_id required".to_string()))?
            .to_string();

        let vault_state = vault_engine
            .get_vault(&vault_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Vault not found".to_string()))?;

        Ok(json!({
            "vault_id": vault_state.vault_id,
            "vault_state": serde_json::to_value(&vault_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    // ========== POOL RPC METHODS ==========

    /// Create a payment pool
    ///
    /// Params: ["pool_id", "initial_participants", "config"]
    /// - pool_id: Unique identifier for the pool
    /// - initial_participants: Array of [participant_id, contribution, script_pubkey_hex]
    /// - config: Pool configuration (optional)
    ///
    /// Returns: {pool_id, pool_state}
    #[cfg(feature = "ctv")]
    pub async fn create_pool(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: createpool");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let pool_engine = state_machine.pool_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Pool engine not available".to_string())
        })?;

        let pool_id = params["pool_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("pool_id required".to_string()))?
            .to_string();

        let participants_array = params["initial_participants"].as_array().ok_or_else(|| {
            PaymentError::ProcessingError("initial_participants required".to_string())
        })?;

        let mut initial_participants = Vec::new();
        for p in participants_array {
            let p_arr = p.as_array().ok_or_else(|| {
                PaymentError::ProcessingError("Each participant must be an array".to_string())
            })?;
            if p_arr.len() < 3 {
                return Err(PaymentError::ProcessingError(
                    "Each participant must have [participant_id, contribution, script_pubkey]"
                        .to_string(),
                ));
            }
            let participant_id = p_arr[0]
                .as_str()
                .ok_or_else(|| {
                    PaymentError::ProcessingError("participant_id required".to_string())
                })?
                .to_string();
            let contribution = p_arr[1].as_u64().ok_or_else(|| {
                PaymentError::ProcessingError("contribution required".to_string())
            })?;
            let script_hex = p_arr[2].as_str().ok_or_else(|| {
                PaymentError::ProcessingError("script_pubkey required".to_string())
            })?;
            let script = hex::decode(script_hex).map_err(|e| {
                PaymentError::ProcessingError(format!("Invalid script_pubkey: {}", e))
            })?;

            initial_participants.push((participant_id, contribution, script));
        }

        let config = if params["config"].is_object() {
            serde_json::from_value(params["config"].clone())
                .unwrap_or_else(|_| crate::payment::pool::PoolConfig::default())
        } else {
            crate::payment::pool::PoolConfig::default()
        };

        let pool_state = pool_engine.create_pool(&pool_id, initial_participants, config)?;

        Ok(json!({
            "pool_id": pool_state.pool_id,
            "pool_state": serde_json::to_value(&pool_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Join a payment pool
    ///
    /// Params: ["pool_id", "participant_id", "contribution", "script_pubkey"]
    /// - pool_id: Pool identifier
    /// - participant_id: ID of new participant
    /// - contribution: Contribution amount (satoshis)
    /// - script_pubkey: Participant's script pubkey (hex)
    ///
    /// Returns: {pool_id, pool_state}
    #[cfg(feature = "ctv")]
    pub async fn join_pool(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: joinpool");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let pool_engine = state_machine.pool_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Pool engine not available".to_string())
        })?;

        let pool_id = params["pool_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("pool_id required".to_string()))?
            .to_string();

        let participant_id = params["participant_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("participant_id required".to_string()))?
            .to_string();

        let contribution = params["contribution"]
            .as_u64()
            .ok_or_else(|| PaymentError::ProcessingError("contribution required".to_string()))?;

        let script_hex = params["script_pubkey"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("script_pubkey required".to_string()))?;
        let script_pubkey = hex::decode(script_hex)
            .map_err(|e| PaymentError::ProcessingError(format!("Invalid script_pubkey: {}", e)))?;

        let pool_state = pool_engine
            .get_pool(&pool_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Pool not found".to_string()))?;

        let updated_pool_state =
            pool_engine.join_pool(&pool_state, &participant_id, contribution, script_pubkey)?;

        Ok(json!({
            "pool_id": updated_pool_state.pool_id,
            "pool_state": serde_json::to_value(&updated_pool_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Distribute funds from pool
    ///
    /// Params: ["pool_id", "distribution"]
    /// - pool_id: Pool identifier
    /// - distribution: Array of [participant_id, amount]
    ///
    /// Returns: {pool_id, pool_state, covenant_proof}
    #[cfg(feature = "ctv")]
    pub async fn distribute_pool(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: distributepool");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let pool_engine = state_machine.pool_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Pool engine not available".to_string())
        })?;

        let pool_id = params["pool_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("pool_id required".to_string()))?
            .to_string();

        let distribution_array = params["distribution"].as_array().ok_or_else(|| {
            PaymentError::ProcessingError("distribution array required".to_string())
        })?;

        let mut distribution = Vec::new();
        for d in distribution_array {
            let d_arr = d.as_array().ok_or_else(|| {
                PaymentError::ProcessingError(
                    "Each distribution entry must be an array".to_string(),
                )
            })?;
            if d_arr.len() < 2 {
                return Err(PaymentError::ProcessingError(
                    "Each distribution entry must have [participant_id, amount]".to_string(),
                ));
            }
            let participant_id = d_arr[0]
                .as_str()
                .ok_or_else(|| {
                    PaymentError::ProcessingError("participant_id required".to_string())
                })?
                .to_string();
            let amount = d_arr[1]
                .as_u64()
                .ok_or_else(|| PaymentError::ProcessingError("amount required".to_string()))?;
            distribution.push((participant_id, amount));
        }

        let pool_state = pool_engine
            .get_pool(&pool_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Pool not found".to_string()))?;

        let (updated_pool_state, covenant_proof) =
            pool_engine.distribute(&pool_state, distribution)?;

        Ok(json!({
            "pool_id": updated_pool_state.pool_id,
            "pool_state": serde_json::to_value(&updated_pool_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
            "covenant_proof": serde_json::to_value(&covenant_proof)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    /// Get payment pool state
    ///
    /// Params: ["pool_id"]
    /// - pool_id: Pool identifier
    ///
    /// Returns: {pool_id, pool_state}
    #[cfg(feature = "ctv")]
    pub async fn get_pool_state(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: getpoolstate");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let pool_engine = state_machine.pool_engine().ok_or_else(|| {
            PaymentError::ProcessingError("Pool engine not available".to_string())
        })?;

        let pool_id = params["pool_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("pool_id required".to_string()))?
            .to_string();

        let pool_state = pool_engine
            .get_pool(&pool_id)?
            .ok_or_else(|| PaymentError::ProcessingError("Pool not found".to_string()))?;

        Ok(json!({
            "pool_id": pool_state.pool_id,
            "pool_state": serde_json::to_value(&pool_state)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
        }))
    }

    // ========== CONGESTION RPC METHODS ==========

    /// Create a transaction batch
    ///
    /// Params: ["batch_id", "target_fee_rate"]
    /// - batch_id: Unique identifier for the batch
    /// - target_fee_rate: Target fee rate (sat/vbyte, optional)
    ///
    /// Returns: {batch_id}
    #[cfg(feature = "ctv")]
    pub async fn create_batch(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: createbatch");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let congestion_manager = state_machine.congestion_manager().ok_or_else(|| {
            PaymentError::ProcessingError("Congestion manager not available".to_string())
        })?;

        let batch_id = params["batch_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("batch_id required".to_string()))?
            .to_string();

        let target_fee_rate = params["target_fee_rate"].as_u64();

        let mut manager = congestion_manager.lock().await;
        let created_id = manager.create_batch(&batch_id, target_fee_rate);

        Ok(json!({
            "batch_id": created_id,
        }))
    }

    /// Add transaction to batch
    ///
    /// Params: ["batch_id", "tx_id", "outputs", "priority", "deadline"]
    /// - batch_id: Batch identifier
    /// - tx_id: Transaction ID
    /// - outputs: Array of payment outputs
    /// - priority: Transaction priority (low, normal, high, urgent)
    /// - deadline: Optional deadline (Unix timestamp)
    ///
    /// Returns: {batch_id, batch_size}
    #[cfg(feature = "ctv")]
    pub async fn add_to_batch(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: addtobatch");

        if !params.is_object() {
            return Err(PaymentError::ProcessingError(
                "Params must be a JSON object".to_string(),
            ));
        }

        let state_machine = self.get_state_machine()?;
        let congestion_manager = state_machine.congestion_manager().ok_or_else(|| {
            PaymentError::ProcessingError("Congestion manager not available".to_string())
        })?;

        let batch_id = params["batch_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("batch_id required".to_string()))?
            .to_string();

        let tx_id = params["tx_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("tx_id required".to_string()))?
            .to_string();

        // Parse outputs
        let outputs_array = params["outputs"]
            .as_array()
            .ok_or_else(|| PaymentError::ProcessingError("outputs required".to_string()))?;

        let mut outputs = Vec::new();
        for o in outputs_array {
            let amount = o["amount"].as_u64();
            let script_hex = o["script_pubkey"].as_str().ok_or_else(|| {
                PaymentError::ProcessingError("script_pubkey required".to_string())
            })?;
            let script = hex::decode(script_hex).map_err(|e| {
                PaymentError::ProcessingError(format!("Invalid script_pubkey: {}", e))
            })?;

            outputs.push(PaymentOutput { script, amount });
        }

        let priority_str = params["priority"]
            .as_str()
            .unwrap_or("normal")
            .to_lowercase();
        let priority = match priority_str.as_str() {
            "low" => crate::payment::congestion::TransactionPriority::Low,
            "normal" => crate::payment::congestion::TransactionPriority::Normal,
            "high" => crate::payment::congestion::TransactionPriority::High,
            "urgent" => crate::payment::congestion::TransactionPriority::Urgent,
            _ => crate::payment::congestion::TransactionPriority::Normal,
        };

        let deadline = params["deadline"].as_u64();

        let pending_tx = crate::payment::congestion::PendingTransaction {
            tx_id,
            outputs,
            priority,
            created_at: current_timestamp(),
            deadline,
        };

        let mut manager = congestion_manager.lock().await;
        manager.add_to_batch(&batch_id, pending_tx)?;

        let batch = manager
            .get_batch(&batch_id)
            .ok_or_else(|| PaymentError::ProcessingError("Batch not found".to_string()))?;

        Ok(json!({
            "batch_id": batch_id,
            "batch_size": batch.transactions.len(),
        }))
    }

    /// Get congestion metrics
    ///
    /// Params: []
    ///
    /// Returns: {mempool_size, avg_fee_rate, median_fee_rate, estimated_blocks}
    #[cfg(feature = "ctv")]
    pub async fn get_congestion(&self, _params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: getcongestion");

        let state_machine = self.get_state_machine()?;
        let congestion_manager = state_machine.congestion_manager().ok_or_else(|| {
            PaymentError::ProcessingError("Congestion manager not available".to_string())
        })?;

        let manager = congestion_manager.lock().await;
        let metrics = manager.check_congestion()?;

        Ok(json!({
            "mempool_size": metrics.mempool_size,
            "avg_fee_rate": metrics.avg_fee_rate,
            "median_fee_rate": metrics.median_fee_rate,
            "estimated_blocks": metrics.estimated_blocks,
            "collected_at": metrics.collected_at,
        }))
    }

    /// Get congestion metrics (alias for get_congestion)
    #[cfg(feature = "ctv")]
    pub async fn get_congestion_metrics(&self, params: &Value) -> Result<Value, PaymentError> {
        self.get_congestion(params).await
    }

    /// Broadcast batch when conditions are optimal
    ///
    /// Params: ["batch_id"]
    /// - batch_id: Batch identifier
    ///
    /// Returns: {batch_id, covenant_proof, ready_to_broadcast}
    #[cfg(feature = "ctv")]
    pub async fn broadcast_batch(&self, params: &Value) -> Result<Value, PaymentError> {
        debug!("RPC: broadcastbatch");

        let state_machine = self.get_state_machine()?;
        let congestion_manager = state_machine.congestion_manager().ok_or_else(|| {
            PaymentError::ProcessingError("Congestion manager not available".to_string())
        })?;

        let batch_id = params["batch_id"]
            .as_str()
            .ok_or_else(|| PaymentError::ProcessingError("batch_id required".to_string()))?
            .to_string();

        let mut manager = congestion_manager.lock().await;
        let covenant_proof = manager.broadcast_batch(&batch_id)?;

        Ok(json!({
            "batch_id": batch_id,
            "covenant_proof": serde_json::to_value(&covenant_proof)
                .map_err(|e| PaymentError::ProcessingError(format!("Serialization error: {}", e)))?,
            "ready_to_broadcast": true,
        }))
    }
}