clementine_core/
operator.rs

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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
use ark_ff::PrimeField;
use circuits_lib::common::constants::{FIRST_FIVE_OUTPUTS, NUMBER_OF_ASSERT_TXS};
use risc0_zkvm::is_dev_mode;
use std::collections::HashMap;
use std::time::Duration;

use crate::actor::{Actor, TweakCache, WinternitzDerivationPath};
use crate::bitvm_client::{ClementineBitVMPublicKeys, SECP};
use crate::builder::script::extract_winternitz_commits;
use crate::builder::sighash::{create_operator_sighash_stream, PartialSignatureInfo};
use crate::builder::transaction::deposit_signature_owner::EntityType;
use crate::builder::transaction::sign::{create_and_sign_txs, TransactionRequestData};
use crate::builder::transaction::{
    create_burn_unused_kickoff_connectors_txhandler, create_round_nth_txhandler,
    create_round_txhandlers, create_txhandlers, ContractContext, KickoffWinternitzKeys,
    ReimburseDbCache, TransactionType, TxHandler, TxHandlerCache,
};
use crate::citrea::CitreaClientT;
use crate::config::BridgeConfig;
use crate::database::Database;
use crate::database::DatabaseTransaction;
use crate::deposit::{DepositData, KickoffData, OperatorData};
use crate::errors::BridgeError;
use crate::extended_rpc::ExtendedRpc;
use crate::header_chain_prover::HeaderChainProver;
use crate::task::manager::BackgroundTaskManager;
use crate::task::payout_checker::{PayoutCheckerTask, PAYOUT_CHECKER_POLL_DELAY};
use crate::task::TaskExt;
use crate::utils::Last20Bytes;
use crate::utils::{NamedEntity, TxMetadata};
use crate::{builder, constants, UTXO};
use bitcoin::consensus::deserialize;
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::schnorr::Signature;
use bitcoin::secp256k1::{schnorr, Message};
use bitcoin::{
    Address, Amount, BlockHash, OutPoint, ScriptBuf, Transaction, TxOut, Txid, XOnlyPublicKey,
};
use bitcoincore_rpc::json::AddressType;
use bitcoincore_rpc::RpcApi;
use bitvm::chunk::api::generate_assertions;
use bitvm::signatures::winternitz;
use bridge_circuit_host::bridge_circuit_host::{
    create_spv, prove_bridge_circuit, MAINNET_BRIDGE_CIRCUIT_ELF, REGTEST_BRIDGE_CIRCUIT_ELF,
    SIGNET_BRIDGE_CIRCUIT_ELF, TESTNET4_BRIDGE_CIRCUIT_ELF,
};
use bridge_circuit_host::structs::{BridgeCircuitHostParams, WatchtowerContext};
use bridge_circuit_host::utils::{get_ark_verifying_key, get_ark_verifying_key_dev_mode_bridge};
use eyre::{Context, OptionExt};
use tokio::sync::mpsc;
use tokio_stream::StreamExt;

#[cfg(feature = "automation")]
use crate::{
    states::StateManager,
    task::IntoTask,
    tx_sender::{ActivatedWithOutpoint, ActivatedWithTxid, TxSenderClient},
    utils::FeePayingType,
};
#[cfg(feature = "automation")]
use bitcoin::Witness;

pub type SecretPreimage = [u8; 20];
pub type PublicHash = [u8; 20];

/// Round index is used to represent the round index safely.
/// Collateral represents the collateral utxo.
/// Round(index) represents the rounds of the bridge operators, index is 0-indexed.
/// As a single u32, collateral is represented as 0 and rounds are represented starting from 1.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, Ord, PartialOrd,
)]
pub enum RoundIndex {
    Collateral,
    Round(usize), // 0-indexed
}

impl RoundIndex {
    /// Converts the round to a 0-indexed index.
    pub fn to_index(&self) -> usize {
        match self {
            RoundIndex::Collateral => 0,
            RoundIndex::Round(index) => *index + 1,
        }
    }

    /// Converts a 0-indexed index to a RoundIndex.
    /// Use this only when dealing with 0-indexed data. Currently these are data coming from the database and rpc.
    pub fn from_index(index: usize) -> Self {
        if index == 0 {
            RoundIndex::Collateral
        } else {
            RoundIndex::Round(index - 1)
        }
    }

    /// Returns the next RoundIndex.
    pub fn next_round(&self) -> Self {
        match self {
            RoundIndex::Collateral => RoundIndex::Round(0),
            RoundIndex::Round(index) => RoundIndex::Round(*index + 1),
        }
    }

    /// Creates an iterator over rounds from 0 to num_rounds (exclusive)
    /// Only iterates actual rounds, collateral is not included.
    pub fn iter_rounds(num_rounds: usize) -> impl Iterator<Item = RoundIndex> {
        Self::iter_rounds_range(0, num_rounds)
    }

    /// Creates an iterator over rounds from start to end (exclusive)
    /// Only iterates actual rounds, collateral is not included.
    pub fn iter_rounds_range(start: usize, end: usize) -> impl Iterator<Item = RoundIndex> {
        (start..end).map(RoundIndex::Round)
    }
}

pub struct OperatorServer<C: CitreaClientT> {
    pub operator: Operator<C>,
    background_tasks: BackgroundTaskManager<Operator<C>>,
}

#[derive(Debug, Clone)]
pub struct Operator<C: CitreaClientT> {
    pub rpc: ExtendedRpc,
    pub db: Database,
    pub signer: Actor,
    pub config: BridgeConfig,
    pub collateral_funding_outpoint: OutPoint,
    pub(crate) reimburse_addr: Address,
    #[cfg(feature = "automation")]
    pub tx_sender: TxSenderClient,
    pub header_chain_prover: HeaderChainProver,
    pub citrea_client: C,
}

impl<C> OperatorServer<C>
where
    C: CitreaClientT,
{
    pub async fn new(config: BridgeConfig) -> Result<Self, BridgeError> {
        let operator = Operator::new(config.clone()).await?;
        let mut background_tasks = BackgroundTaskManager::default();

        // initialize and run state manager
        #[cfg(feature = "automation")]
        {
            let paramset = config.protocol_paramset();
            let state_manager =
                StateManager::new(operator.db.clone(), operator.clone(), paramset).await?;

            let should_run_state_mgr = {
                #[cfg(test)]
                {
                    config.test_params.should_run_state_manager
                }
                #[cfg(not(test))]
                {
                    true
                }
            };

            if should_run_state_mgr {
                background_tasks.loop_and_monitor(state_manager.block_fetcher_task().await?);
                background_tasks.loop_and_monitor(state_manager.into_task());
            }
        }

        // run payout checker task
        background_tasks.loop_and_monitor(
            PayoutCheckerTask::new(operator.db.clone(), operator.clone())
                .with_delay(PAYOUT_CHECKER_POLL_DELAY),
        );

        tracing::info!("Payout checker task started");

        // track the operator's round state
        #[cfg(feature = "automation")]
        {
            operator.track_rounds().await?;
            tracing::info!("Operator round state tracked");
        }

        Ok(Self {
            operator,
            background_tasks,
        })
    }

    pub async fn shutdown(&mut self) {
        self.background_tasks
            .graceful_shutdown_with_timeout(Duration::from_secs(10))
            .await;
    }
}

impl<C> Operator<C>
where
    C: CitreaClientT,
{
    /// Creates a new `Operator`.
    pub async fn new(config: BridgeConfig) -> Result<Self, BridgeError> {
        let signer = Actor::new(
            config.secret_key,
            config.winternitz_secret_key,
            config.protocol_paramset().network,
        );

        let db = Database::new(&config).await?;
        let rpc = ExtendedRpc::connect(
            config.bitcoin_rpc_url.clone(),
            config.bitcoin_rpc_user.clone(),
            config.bitcoin_rpc_password.clone(),
        )
        .await?;

        #[cfg(feature = "automation")]
        let tx_sender = TxSenderClient::new(
            db.clone(),
            format!("operator_{:?}", signer.xonly_public_key).to_string(),
        );

        if config.operator_withdrawal_fee_sats.is_none() {
            return Err(eyre::eyre!("Operator withdrawal fee is not set").into());
        }

        // check if we store our collateral outpoint already in db
        let mut dbtx = db.begin_transaction().await?;
        let op_data = db
            .get_operator(Some(&mut dbtx), signer.xonly_public_key)
            .await?;
        let (collateral_funding_outpoint, reimburse_addr) = match op_data {
            Some(operator_data) => {
                // Operator data is already set in db, we don't actually need to do anything.
                // set_operator_checked will give error if the values set in config and db doesn't match.
                (
                    operator_data.collateral_funding_outpoint,
                    operator_data.reimburse_addr,
                )
            }
            None => {
                // Operator data is not set in db, then we check if any collateral outpoint and reimbursement address is set in config.
                // If so we create a new operator using those data, otherwise we generate new collateral outpoint and reimbursement address.
                let reimburse_addr = match &config.operator_reimbursement_address {
                    Some(reimburse_addr) => {
                        reimburse_addr
                            .to_owned()
                            .require_network(config.protocol_paramset().network)
                            .wrap_err(format!("Invalid operator reimbursement address provided in config: {:?} for network: {:?}", reimburse_addr, config.protocol_paramset().network))?
                    }
                    None => {
                        rpc
                        .client
                        .get_new_address(Some("OperatorReimbursement"), Some(AddressType::Bech32m))
                        .await
                        .wrap_err("Failed to get new address")?
                        .require_network(config.protocol_paramset().network)
                        .wrap_err(format!("Invalid operator reimbursement address generated for the network in config: {:?}
                                Possibly the provided rpc's network and network given in config doesn't match", config.protocol_paramset().network))?
                    }
                };
                let outpoint = match &config.operator_collateral_funding_outpoint {
                    Some(outpoint) => {
                        // check if outpoint exists on chain and has exactly collateral funding amount
                        let collateral_tx = rpc
                            .get_tx_of_txid(&outpoint.txid)
                            .await
                            .wrap_err("Failed to get collateral funding tx")?;
                        let collateral_value = collateral_tx
                            .output
                            .get(outpoint.vout as usize)
                            .ok_or_eyre("Invalid vout index for collateral funding tx")?
                            .value;
                        if collateral_value != config.protocol_paramset().collateral_funding_amount
                        {
                            return Err(eyre::eyre!("Operator collateral funding outpoint given in config has a different amount than the one specified in config..
                                Bridge collateral funnding amount: {:?}, Amount in given outpoint: {:?}", config.protocol_paramset().collateral_funding_amount, collateral_value).into());
                        }
                        *outpoint
                    }
                    None => {
                        // create a new outpoint that has collateral funding amount
                        rpc.send_to_address(
                            &signer.address,
                            config.protocol_paramset().collateral_funding_amount,
                        )
                        .await?
                    }
                };
                (outpoint, reimburse_addr)
            }
        };

        db.set_operator(
            Some(&mut dbtx),
            signer.xonly_public_key,
            &reimburse_addr,
            collateral_funding_outpoint,
        )
        .await?;
        dbtx.commit().await?;
        let citrea_client = C::new(
            config.citrea_rpc_url.clone(),
            config.citrea_light_client_prover_url.clone(),
            config.citrea_chain_id,
            None,
        )
        .await?;

        tracing::info!(
            "Operator xonly pk: {:?}, db created with name: {:?}",
            signer.xonly_public_key,
            config.db_name
        );

        let header_chain_prover = HeaderChainProver::new(&config, rpc.clone()).await?;

        Ok(Operator {
            rpc,
            db: db.clone(),
            signer,
            config,
            collateral_funding_outpoint,
            #[cfg(feature = "automation")]
            tx_sender,
            citrea_client,
            header_chain_prover,
            reimburse_addr,
        })
    }

    #[cfg(feature = "automation")]
    pub async fn send_initial_round_tx(&self, round_tx: &Transaction) -> Result<(), BridgeError> {
        let mut dbtx = self.db.begin_transaction().await?;
        self.tx_sender
            .insert_try_to_send(
                &mut dbtx,
                Some(TxMetadata {
                    tx_type: TransactionType::Round,
                    operator_xonly_pk: None,
                    round_idx: Some(RoundIndex::Round(0)),
                    kickoff_idx: None,
                    deposit_outpoint: None,
                }),
                round_tx,
                FeePayingType::CPFP,
                None,
                &[],
                &[],
                &[],
                &[],
            )
            .await?;
        dbtx.commit().await?;
        Ok(())
    }

    /// Returns an operator's winternitz public keys and challenge ackpreimages
    /// & hashes.
    ///
    /// # Returns
    ///
    /// - [`mpsc::Receiver`]: A [`tokio`] data channel with a type of
    ///   [`winternitz::PublicKey`] and size of operator's winternitz public
    ///   keys count
    /// - [`mpsc::Receiver`]: A [`tokio`] data channel with a type of
    ///   [`PublicHash`] and size of operator's challenge ack preimages & hashes
    ///   count
    ///
    pub async fn get_params(
        &self,
    ) -> Result<
        (
            mpsc::Receiver<winternitz::PublicKey>,
            mpsc::Receiver<schnorr::Signature>,
        ),
        BridgeError,
    > {
        tracing::info!("Generating operator params");
        let wpks = self.generate_kickoff_winternitz_pubkeys()?;
        let (wpk_tx, wpk_rx) = mpsc::channel(wpks.len());
        let kickoff_wpks = KickoffWinternitzKeys::new(
            wpks,
            self.config.protocol_paramset().num_kickoffs_per_round,
            self.config.protocol_paramset().num_round_txs,
        );
        let kickoff_sigs = self.generate_unspent_kickoff_sigs(&kickoff_wpks)?;
        let wpks = kickoff_wpks.keys.clone();
        let (sig_tx, sig_rx) = mpsc::channel(kickoff_sigs.len());

        tokio::spawn(async move {
            for wpk in wpks {
                wpk_tx
                    .send(wpk)
                    .await
                    .wrap_err("Failed to send winternitz public key")?;
            }

            for sig in kickoff_sigs {
                sig_tx
                    .send(sig)
                    .await
                    .wrap_err("Failed to send kickoff signature")?;
            }

            Ok::<(), BridgeError>(())
        });

        Ok((wpk_rx, sig_rx))
    }

    pub async fn deposit_sign(
        &self,
        mut deposit_data: DepositData,
    ) -> Result<mpsc::Receiver<schnorr::Signature>, BridgeError> {
        self.citrea_client
            .check_nofn_correctness(deposit_data.get_nofn_xonly_pk()?)
            .await?;

        let mut tweak_cache = TweakCache::default();
        let (sig_tx, sig_rx) = mpsc::channel(constants::DEFAULT_CHANNEL_SIZE);

        let deposit_blockhash = self
            .rpc
            .get_blockhash_of_tx(&deposit_data.get_deposit_outpoint().txid)
            .await?;

        let mut sighash_stream = Box::pin(create_operator_sighash_stream(
            self.db.clone(),
            self.signer.xonly_public_key,
            self.config.clone(),
            deposit_data,
            deposit_blockhash,
        ));

        let signer = self.signer.clone();
        tokio::spawn(async move {
            while let Some(sighash) = sighash_stream.next().await {
                // None because utxos that operators need to sign do not have scripts
                let (sighash, sig_info) = sighash?;
                let sig = signer.sign_with_tweak_data(
                    sighash,
                    sig_info.tweak_data,
                    Some(&mut tweak_cache),
                )?;

                if sig_tx.send(sig).await.is_err() {
                    break;
                }
            }

            Ok::<(), BridgeError>(())
        });

        Ok(sig_rx)
    }

    /// Creates the round state machine by adding a system event to the database
    #[cfg(feature = "automation")]
    pub async fn track_rounds(&self) -> Result<(), BridgeError> {
        let mut dbtx = self.db.begin_transaction().await?;
        // set operators own kickoff winternitz public keys before creating the round state machine
        // as round machine needs kickoff keys to create the first round tx
        self.db
            .set_operator_kickoff_winternitz_public_keys(
                Some(&mut dbtx),
                self.signer.xonly_public_key,
                self.generate_kickoff_winternitz_pubkeys()?,
            )
            .await?;

        StateManager::<Operator<C>>::dispatch_new_round_machine(
            self.db.clone(),
            &mut dbtx,
            self.data(),
        )
        .await?;
        dbtx.commit().await?;
        Ok(())
    }

    /// Checks if the withdrawal amount is within the acceptable range.
    fn is_profitable(
        input_amount: Amount,
        withdrawal_amount: Amount,
        bridge_amount_sats: Amount,
        operator_withdrawal_fee_sats: Amount,
    ) -> bool {
        if withdrawal_amount
            .to_sat()
            .wrapping_sub(input_amount.to_sat())
            > bridge_amount_sats.to_sat()
        {
            return false;
        }

        // Calculate net profit after the withdrawal.
        let net_profit = bridge_amount_sats - withdrawal_amount;

        // Net profit must be bigger than withdrawal fee.
        net_profit >= operator_withdrawal_fee_sats
    }

    /// Prepares a withdrawal by:
    ///
    /// 1. Checking if the withdrawal has been made on Citrea
    /// 2. Verifying the given signature
    /// 3. Checking if the withdrawal is profitable or not
    /// 4. Funding the witdhrawal transaction
    ///
    /// # Parameters
    ///
    /// - `withdrawal_idx`: Citrea withdrawal UTXO index
    /// - `in_signature`: User's signature that is going to be used for signing
    ///   withdrawal transaction input
    /// - `in_outpoint`: User's input for the payout transaction
    /// - `out_script_pubkey`: User's script pubkey which will be used
    ///   in the payout transaction's output
    /// - `out_amount`: Payout transaction output's value
    ///
    /// # Returns
    ///
    /// - [`Txid`]: Payout transaction's txid
    pub async fn withdraw(
        &self,
        withdrawal_index: u32,
        in_signature: schnorr::Signature,
        in_outpoint: OutPoint,
        out_script_pubkey: ScriptBuf,
        out_amount: Amount,
    ) -> Result<Txid, BridgeError> {
        tracing::info!(
            "Withdrawing with index: {}, in_signature: {}, in_outpoint: {:?}, out_script_pubkey: {}, out_amount: {}",
            withdrawal_index,
            in_signature.to_string(),
            in_outpoint,
            out_script_pubkey.to_string(),
            out_amount
        );

        // Prepare input and output of the payout transaction.
        let input_prevout = self.rpc.get_txout_from_outpoint(&in_outpoint).await?;
        let input_utxo = UTXO {
            outpoint: in_outpoint,
            txout: input_prevout,
        };
        let output_txout = TxOut {
            value: out_amount,
            script_pubkey: out_script_pubkey,
        };

        // Check Citrea for the withdrawal state.
        let withdrawal_utxo = self
            .db
            .get_withdrawal_utxo_from_citrea_withdrawal(None, withdrawal_index)
            .await?;

        match withdrawal_utxo {
            Some(withdrawal_utxo) => {
                if withdrawal_utxo != input_utxo.outpoint {
                    return Err(eyre::eyre!("Input UTXO does not match withdrawal UTXO from Citrea: Input Outpoint: {0}, Withdrawal Outpoint (from Citrea): {1}", input_utxo.outpoint, withdrawal_utxo).into());
                }
            }
            None => {
                return Err(eyre::eyre!(
                    "User's withdrawal UTXO is not set for withdrawal index: {0}",
                    withdrawal_index
                )
                .into());
            }
        }

        let operator_withdrawal_fee_sats =
            self.config
                .operator_withdrawal_fee_sats
                .ok_or(BridgeError::ConfigError(
                    "Operator withdrawal fee sats is not specified in configuration file"
                        .to_string(),
                ))?;
        if !Self::is_profitable(
            input_utxo.txout.value,
            output_txout.value,
            self.config.protocol_paramset().bridge_amount,
            operator_withdrawal_fee_sats,
        ) {
            return Err(eyre::eyre!("Not enough fee for operator").into());
        }

        let user_xonly_pk =
            XOnlyPublicKey::from_slice(&input_utxo.txout.script_pubkey.as_bytes()[2..34])
                .wrap_err("Failed to extract xonly public key from input utxo script pubkey")?;

        let payout_txhandler = builder::transaction::create_payout_txhandler(
            input_utxo,
            output_txout,
            self.signer.xonly_public_key,
            in_signature,
            self.config.protocol_paramset().network,
        )?;

        // tracing::info!("Payout txhandler: {:?}", hex::encode(bitcoin::consensus::serialize(&payout_txhandler.get_cached_tx())));

        let sighash = payout_txhandler
            .calculate_sighash_txin(0, bitcoin::sighash::TapSighashType::SinglePlusAnyoneCanPay)?;

        SECP.verify_schnorr(
            &in_signature,
            &Message::from_digest(*sighash.as_byte_array()),
            &user_xonly_pk,
        )
        .wrap_err("Failed to verify signature received from user for payout txin")?;

        let funded_tx = self
            .rpc
            .client
            .fund_raw_transaction(
                payout_txhandler.get_cached_tx(),
                Some(&bitcoincore_rpc::json::FundRawTransactionOptions {
                    add_inputs: Some(true),
                    change_address: None,
                    change_position: Some(1),
                    change_type: None,
                    include_watching: None,
                    lock_unspents: None,
                    fee_rate: None,
                    subtract_fee_from_outputs: None,
                    replaceable: None,
                    conf_target: None,
                    estimate_mode: None,
                }),
                None,
            )
            .await
            .wrap_err("Failed to fund raw transaction")?
            .hex;

        let signed_tx: Transaction = deserialize(
            &self
                .rpc
                .client
                .sign_raw_transaction_with_wallet(&funded_tx, None, None)
                .await
                .wrap_err("Failed to sign funded tx through bitcoin RPC")?
                .hex,
        )
        .wrap_err("Failed to deserialize signed tx")?;

        Ok(self
            .rpc
            .client
            .send_raw_transaction(&signed_tx)
            .await
            .wrap_err("Failed to send transaction to signed tx")?)
    }

    /// Generates Winternitz public keys for every  BitVM assert tx for a deposit.
    ///
    /// # Returns
    ///
    /// - [`Vec<Vec<winternitz::PublicKey>>`]: Winternitz public keys for
    ///   `watchtower index` row and `BitVM assert tx index` column.
    pub fn generate_assert_winternitz_pubkeys(
        &self,
        deposit_outpoint: bitcoin::OutPoint,
    ) -> Result<Vec<winternitz::PublicKey>, BridgeError> {
        tracing::debug!("Generating assert winternitz pubkeys");
        let bitvm_pks = self
            .signer
            .generate_bitvm_pks_for_deposit(deposit_outpoint, self.config.protocol_paramset())?;

        let flattened_wpks = bitvm_pks.to_flattened_vec();

        Ok(flattened_wpks)
    }
    /// Generates Winternitz public keys for every blockhash commit to be used in kickoff utxos.
    /// Unique for each kickoff utxo of operator.
    ///
    /// # Returns
    ///
    /// - [`Vec<Vec<winternitz::PublicKey>>`]: Winternitz public keys for
    ///   `round_index` row and `kickoff_idx` column.
    pub fn generate_kickoff_winternitz_pubkeys(
        &self,
    ) -> Result<Vec<winternitz::PublicKey>, BridgeError> {
        let mut winternitz_pubkeys =
            Vec::with_capacity(self.config.get_num_kickoff_winternitz_pks());

        // we need num_round_txs + 1 because the last round includes reimburse generators of previous round
        for round_idx in RoundIndex::iter_rounds(self.config.protocol_paramset().num_round_txs + 1)
        {
            for kickoff_idx in 0..self.config.protocol_paramset().num_kickoffs_per_round {
                let path = WinternitzDerivationPath::Kickoff(
                    round_idx,
                    kickoff_idx as u32,
                    self.config.protocol_paramset(),
                );
                winternitz_pubkeys.push(self.signer.derive_winternitz_pk(path)?);
            }
        }

        if winternitz_pubkeys.len() != self.config.get_num_kickoff_winternitz_pks() {
            return Err(eyre::eyre!(
                "Expected {} number of kickoff winternitz pubkeys, but got {}",
                self.config.get_num_kickoff_winternitz_pks(),
                winternitz_pubkeys.len()
            )
            .into());
        }

        Ok(winternitz_pubkeys)
    }

    pub fn generate_unspent_kickoff_sigs(
        &self,
        kickoff_wpks: &KickoffWinternitzKeys,
    ) -> Result<Vec<Signature>, BridgeError> {
        let mut tweak_cache = TweakCache::default();
        let mut sigs: Vec<Signature> =
            Vec::with_capacity(self.config.get_num_unspent_kickoff_sigs());
        let mut prev_ready_to_reimburse: Option<TxHandler> = None;
        let operator_data = OperatorData {
            xonly_pk: self.signer.xonly_public_key,
            collateral_funding_outpoint: self.collateral_funding_outpoint,
            reimburse_addr: self.reimburse_addr.clone(),
        };
        for round_idx in RoundIndex::iter_rounds(self.config.protocol_paramset().num_round_txs) {
            let txhandlers = create_round_txhandlers(
                self.config.protocol_paramset(),
                round_idx,
                &operator_data,
                kickoff_wpks,
                prev_ready_to_reimburse.as_ref(),
            )?;
            for txhandler in txhandlers {
                if let TransactionType::UnspentKickoff(kickoff_idx) =
                    txhandler.get_transaction_type()
                {
                    let partial = PartialSignatureInfo {
                        operator_idx: 0, // dummy value, doesn't
                        round_idx,
                        kickoff_utxo_idx: kickoff_idx,
                    };
                    let sighashes = txhandler
                        .calculate_shared_txins_sighash(EntityType::OperatorSetup, partial)?;
                    let signed_sigs: Result<Vec<_>, _> = sighashes
                        .into_iter()
                        .map(|(sighash, sig_info)| {
                            self.signer.sign_with_tweak_data(
                                sighash,
                                sig_info.tweak_data,
                                Some(&mut tweak_cache),
                            )
                        })
                        .collect();
                    sigs.extend(signed_sigs?);
                }
                if let TransactionType::ReadyToReimburse = txhandler.get_transaction_type() {
                    prev_ready_to_reimburse = Some(txhandler);
                }
            }
        }
        if sigs.len() != self.config.get_num_unspent_kickoff_sigs() {
            return Err(eyre::eyre!(
                "Expected {} number of unspent kickoff sigs, but got {}",
                self.config.get_num_unspent_kickoff_sigs(),
                sigs.len()
            )
            .into());
        }
        Ok(sigs)
    }

    pub fn generate_challenge_ack_preimages_and_hashes(
        &self,
        deposit_data: &DepositData,
    ) -> Result<Vec<PublicHash>, BridgeError> {
        let mut hashes = Vec::with_capacity(self.config.get_num_challenge_ack_hashes(deposit_data));

        for watchtower_idx in 0..deposit_data.get_num_watchtowers() {
            let path = WinternitzDerivationPath::ChallengeAckHash(
                watchtower_idx as u32,
                deposit_data.get_deposit_outpoint(),
                self.config.protocol_paramset(),
            );
            let hash = self.signer.generate_public_hash_from_path(path)?;
            hashes.push(hash);
        }

        if hashes.len() != self.config.get_num_challenge_ack_hashes(deposit_data) {
            return Err(eyre::eyre!(
                "Expected {} number of challenge ack hashes, but got {}",
                self.config.get_num_challenge_ack_hashes(deposit_data),
                hashes.len()
            )
            .into());
        }

        Ok(hashes)
    }

    pub async fn handle_finalized_payout<'a>(
        &'a self,
        dbtx: DatabaseTransaction<'a, '_>,
        deposit_outpoint: OutPoint,
        payout_tx_blockhash: BlockHash,
    ) -> Result<bitcoin::Txid, BridgeError> {
        let (deposit_id, _) = self
            .db
            .get_deposit_data(Some(dbtx), deposit_outpoint)
            .await?
            .ok_or(BridgeError::DatabaseError(sqlx::Error::RowNotFound))?;

        // get unused kickoff connector
        let (round_idx, kickoff_idx) = self
            .db
            .get_unused_and_signed_kickoff_connector(
                Some(dbtx),
                deposit_id,
                self.signer.xonly_public_key,
            )
            .await?
            .ok_or(BridgeError::DatabaseError(sqlx::Error::RowNotFound))?;

        let current_round_index = self
            .db
            .get_current_round_index(Some(dbtx))
            .await?
            .ok_or(BridgeError::DatabaseError(sqlx::Error::RowNotFound))?;

        #[cfg(feature = "automation")]
        if current_round_index != round_idx {
            // we currently have no free kickoff connectors in the current round, so we need to end round first
            // if current_round_index should only be smaller than round_idx, and should not be smaller by more than 1
            // so sanity check:
            if current_round_index + 1 != round_idx {
                return Err(eyre::eyre!(
                    "Internal error: Expected the current round ({}) to be equal to or 1 less than the round of the first available kickoff for deposit reimbursement ({}) for deposit {:?}. If the round is less than the current round, there is an issue with the logic of the fn that gets the first available kickoff. If the round is greater, that means the next round do not have any kickoff connectors available for reimbursement, which should not be possible.",
                    current_round_index, round_idx, deposit_outpoint
                ).into());
            }
            // start the next round to be able to get reimbursement for the payout
            self.end_round(dbtx).await?;
        }

        let round_idx = RoundIndex::from_index(round_idx as usize);

        // get signed txs,
        let kickoff_data = KickoffData {
            operator_xonly_pk: self.signer.xonly_public_key,
            round_idx,
            kickoff_idx,
        };

        let transaction_data = TransactionRequestData {
            deposit_outpoint,
            kickoff_data,
        };

        let payout_tx_blockhash: [u8; 20] = payout_tx_blockhash.as_byte_array().last_20_bytes();

        #[cfg(test)]
        let mut payout_tx_blockhash = payout_tx_blockhash;

        #[cfg(test)]
        {
            if self.config.test_params.disrupt_payout_tx_block_hash_commit {
                tracing::info!("Disrupting latest blockhash for testing purposes",);
                payout_tx_blockhash[19] ^= 0x01;
            }
        }

        let signed_txs = create_and_sign_txs(
            self.db.clone(),
            &self.signer,
            self.config.clone(),
            transaction_data,
            Some(payout_tx_blockhash),
        )
        .await?;

        let tx_metadata = Some(TxMetadata {
            tx_type: TransactionType::Dummy, // will be replaced in add_tx_to_queue
            operator_xonly_pk: Some(self.signer.xonly_public_key),
            round_idx: Some(round_idx),
            kickoff_idx: Some(kickoff_idx),
            deposit_outpoint: Some(deposit_outpoint),
        });

        // try to send them
        for (tx_type, signed_tx) in &signed_txs {
            match *tx_type {
                TransactionType::Kickoff
                | TransactionType::OperatorChallengeAck(_)
                | TransactionType::WatchtowerChallengeTimeout(_)
                | TransactionType::ChallengeTimeout
                | TransactionType::DisproveTimeout
                | TransactionType::Reimburse => {
                    #[cfg(feature = "automation")]
                    self.tx_sender
                        .add_tx_to_queue(
                            dbtx,
                            *tx_type,
                            signed_tx,
                            &signed_txs,
                            tx_metadata,
                            &self.config,
                            None,
                        )
                        .await?;
                }
                _ => {}
            }
        }

        let kickoff_txid = signed_txs
            .iter()
            .find_map(|(tx_type, tx)| {
                if let TransactionType::Kickoff = tx_type {
                    Some(tx.compute_txid())
                } else {
                    None
                }
            })
            .ok_or(eyre::eyre!(
                "Couldn't find kickoff tx in signed_txs".to_string(),
            ))?;

        // mark the kickoff connector as used
        self.db
            .set_kickoff_connector_as_used(Some(dbtx), round_idx, kickoff_idx, Some(kickoff_txid))
            .await?;

        Ok(kickoff_txid)
    }

    #[cfg(feature = "automation")]
    async fn start_first_round(
        &self,
        dbtx: DatabaseTransaction<'_, '_>,
        kickoff_wpks: KickoffWinternitzKeys,
    ) -> Result<(), BridgeError> {
        // try to send the first round tx
        let (mut first_round_tx, _) = create_round_nth_txhandler(
            self.signer.xonly_public_key,
            self.collateral_funding_outpoint,
            self.config.protocol_paramset().collateral_funding_amount,
            RoundIndex::Round(0),
            &kickoff_wpks,
            self.config.protocol_paramset(),
        )?;

        self.signer
            .tx_sign_and_fill_sigs(&mut first_round_tx, &[], None)?;

        self.tx_sender
            .insert_try_to_send(
                dbtx,
                Some(TxMetadata {
                    tx_type: TransactionType::Round,
                    operator_xonly_pk: None,
                    round_idx: Some(RoundIndex::Round(0)),
                    kickoff_idx: None,
                    deposit_outpoint: None,
                }),
                first_round_tx.get_cached_tx(),
                FeePayingType::CPFP,
                None,
                &[],
                &[],
                &[],
                &[],
            )
            .await?;

        // update current round index to 1
        self.db
            .update_current_round_index(Some(dbtx), RoundIndex::Round(0))
            .await?;

        Ok(())
    }

    #[cfg(feature = "automation")]
    pub async fn end_round<'a>(
        &'a self,
        dbtx: DatabaseTransaction<'a, '_>,
    ) -> Result<(), BridgeError> {
        // get current round index
        let current_round_index = self.db.get_current_round_index(Some(dbtx)).await?;
        let current_round_index = current_round_index.unwrap_or(0);

        let mut activation_prerequisites = Vec::new();

        let operator_winternitz_public_keys = self
            .db
            .get_operator_kickoff_winternitz_public_keys(None, self.signer.xonly_public_key)
            .await?;
        let kickoff_wpks = KickoffWinternitzKeys::new(
            operator_winternitz_public_keys,
            self.config.protocol_paramset().num_kickoffs_per_round,
            self.config.protocol_paramset().num_round_txs,
        );

        let current_round = RoundIndex::from_index(current_round_index as usize);

        // if we are at round 0, which is just the collateral, we need to start the first round
        if current_round == RoundIndex::Collateral {
            return self.start_first_round(dbtx, kickoff_wpks).await;
        }

        let (current_round_txhandler, mut ready_to_reimburse_txhandler) =
            create_round_nth_txhandler(
                self.signer.xonly_public_key,
                self.collateral_funding_outpoint,
                self.config.protocol_paramset().collateral_funding_amount,
                current_round,
                &kickoff_wpks,
                self.config.protocol_paramset(),
            )?;

        let (mut next_round_txhandler, _) = create_round_nth_txhandler(
            self.signer.xonly_public_key,
            self.collateral_funding_outpoint,
            self.config.protocol_paramset().collateral_funding_amount,
            current_round.next_round(),
            &kickoff_wpks,
            self.config.protocol_paramset(),
        )?;

        let mut tweak_cache = TweakCache::default();

        // sign ready to reimburse tx
        self.signer.tx_sign_and_fill_sigs(
            &mut ready_to_reimburse_txhandler,
            &[],
            Some(&mut tweak_cache),
        )?;

        // sign next round tx
        self.signer.tx_sign_and_fill_sigs(
            &mut next_round_txhandler,
            &[],
            Some(&mut tweak_cache),
        )?;

        let current_round_txid = current_round_txhandler.get_cached_tx().compute_txid();
        let ready_to_reimburse_tx = ready_to_reimburse_txhandler.get_cached_tx();
        let next_round_tx = next_round_txhandler.get_cached_tx();

        let ready_to_reimburse_txid = ready_to_reimburse_tx.compute_txid();

        let mut unspent_kickoff_connector_indices = Vec::new();

        // get kickoff txid for used kickoff connector
        for kickoff_connector_idx in
            0..self.config.protocol_paramset().num_kickoffs_per_round as u32
        {
            let kickoff_txid = self
                .db
                .get_kickoff_txid_for_used_kickoff_connector(
                    Some(dbtx),
                    current_round,
                    kickoff_connector_idx,
                )
                .await?;
            match kickoff_txid {
                Some(kickoff_txid) => {
                    activation_prerequisites.push(ActivatedWithOutpoint {
                        outpoint: OutPoint {
                            txid: kickoff_txid,
                            vout: 1, // Kickoff finalizer output index
                        },
                        relative_block_height: self.config.protocol_paramset().finality_depth,
                    });
                }
                None => {
                    let unspent_kickoff_connector = OutPoint {
                        txid: current_round_txid,
                        vout: kickoff_connector_idx + 1, // add 1 since the first output is collateral
                    };
                    unspent_kickoff_connector_indices.push(kickoff_connector_idx as usize);
                    self.db
                        .set_kickoff_connector_as_used(
                            Some(dbtx),
                            current_round,
                            kickoff_connector_idx,
                            None,
                        )
                        .await?;
                    activation_prerequisites.push(ActivatedWithOutpoint {
                        outpoint: unspent_kickoff_connector,
                        relative_block_height: self.config.protocol_paramset().finality_depth,
                    });
                }
            }
        }

        // Burn unused kickoff connectors
        let mut burn_unspent_kickoff_connectors_tx =
            create_burn_unused_kickoff_connectors_txhandler(
                &current_round_txhandler,
                &unspent_kickoff_connector_indices,
                &self.signer.address,
                self.config.protocol_paramset(),
            )?;

        // sign burn unused kickoff connectors tx
        self.signer.tx_sign_and_fill_sigs(
            &mut burn_unspent_kickoff_connectors_tx,
            &[],
            Some(&mut tweak_cache),
        )?;

        self.tx_sender
            .insert_try_to_send(
                dbtx,
                Some(TxMetadata {
                    tx_type: TransactionType::BurnUnusedKickoffConnectors,
                    operator_xonly_pk: Some(self.signer.xonly_public_key),
                    round_idx: Some(current_round),
                    kickoff_idx: None,
                    deposit_outpoint: None,
                }),
                burn_unspent_kickoff_connectors_tx.get_cached_tx(),
                FeePayingType::CPFP,
                None,
                &[],
                &[],
                &[],
                &[],
            )
            .await?;

        // send ready to reimburse tx
        self.tx_sender
            .insert_try_to_send(
                dbtx,
                Some(TxMetadata {
                    tx_type: TransactionType::ReadyToReimburse,
                    operator_xonly_pk: Some(self.signer.xonly_public_key),
                    round_idx: Some(current_round),
                    kickoff_idx: None,
                    deposit_outpoint: None,
                }),
                ready_to_reimburse_tx,
                FeePayingType::CPFP,
                None,
                &[],
                &[],
                &[],
                &activation_prerequisites,
            )
            .await?;

        // send next round tx
        self.tx_sender
            .insert_try_to_send(
                dbtx,
                Some(TxMetadata {
                    tx_type: TransactionType::Round,
                    operator_xonly_pk: Some(self.signer.xonly_public_key),
                    round_idx: Some(current_round.next_round()),
                    kickoff_idx: None,
                    deposit_outpoint: None,
                }),
                next_round_tx,
                FeePayingType::CPFP,
                None,
                &[],
                &[],
                &[ActivatedWithTxid {
                    txid: ready_to_reimburse_txid,
                    relative_block_height: self
                        .config
                        .protocol_paramset()
                        .operator_reimburse_timelock
                        as u32,
                }],
                &[],
            )
            .await?;

        // update current round index
        self.db
            .update_current_round_index(Some(dbtx), current_round.next_round())
            .await?;

        Ok(())
    }

    #[cfg(feature = "automation")]
    async fn send_asserts(
        &self,
        kickoff_data: KickoffData,
        deposit_data: DepositData,
        watchtower_challenges: HashMap<usize, Transaction>,
        _payout_blockhash: Witness,
        latest_blockhash: Witness,
    ) -> Result<(), BridgeError> {
        let context = ContractContext::new_context_for_kickoff(
            kickoff_data,
            deposit_data.clone(),
            self.config.protocol_paramset(),
        );
        let mut db_cache =
            crate::builder::transaction::ReimburseDbCache::from_context(self.db.clone(), &context);
        let txhandlers = builder::transaction::create_txhandlers(
            TransactionType::Kickoff,
            context,
            &mut crate::builder::transaction::TxHandlerCache::new(),
            &mut db_cache,
        )
        .await?;
        let move_txid = txhandlers
            .get(&TransactionType::MoveToVault)
            .ok_or(eyre::eyre!(
                "Move to vault txhandler not found in send_asserts"
            ))?
            .get_cached_tx()
            .compute_txid();
        let kickoff_tx = txhandlers
            .get(&TransactionType::Kickoff)
            .ok_or(eyre::eyre!("Kickoff txhandler not found in send_asserts"))?
            .get_cached_tx();

        let (payout_op_xonly_pk_opt, payout_block_hash, payout_txid, deposit_idx) = self
            .db
            .get_payout_info_from_move_txid(None, move_txid)
            .await
            .wrap_err("Failed to get payout info from db during sending asserts.")?
            .ok_or_eyre(format!(
                "Payout info not found in db while sending asserts for move txid: {}",
                move_txid
            ))?;

        let payout_op_xonly_pk = payout_op_xonly_pk_opt.ok_or_eyre(format!(
            "Payout operator xonly pk not found in payout info DB while sending asserts for deposit move txid: {}",
            move_txid
        ))?;

        tracing::info!("Sending asserts for deposit_idx: {:?}", deposit_idx);

        if payout_op_xonly_pk != kickoff_data.operator_xonly_pk {
            return Err(eyre::eyre!(
                "Payout operator xonly pk does not match kickoff operator xonly pk in send_asserts"
            )
            .into());
        }

        let (payout_block_height, payout_block) = self
            .db
            .get_full_block_from_hash(None, payout_block_hash)
            .await?
            .ok_or_eyre(format!(
                "Payout block {:?} {:?} not found in db",
                payout_op_xonly_pk, payout_block_hash
            ))?;

        let payout_tx_index = payout_block
            .txdata
            .iter()
            .position(|tx| tx.compute_txid() == payout_txid)
            .ok_or_eyre(format!(
                "Payout txid {:?} not found in block {:?} {:?}",
                payout_txid, payout_op_xonly_pk, payout_block_hash
            ))?;
        let payout_tx = &payout_block.txdata[payout_tx_index];
        tracing::debug!("Calculated payout tx in send_asserts: {:?}", payout_tx);

        let (light_client_proof, lcp_receipt, l2_height) = self
            .citrea_client
            .get_light_client_proof(payout_block_height as u64)
            .await
            .wrap_err("Failed to get light client proof for payout block height")?
            .ok_or_eyre("Light client proof is not available for payout block height")?;
        tracing::info!("Got light client proof in send_asserts");

        let storage_proof = self
            .citrea_client
            .get_storage_proof(l2_height, deposit_idx as u32)
            .await
            .wrap_err(format!(
                "Failed to get storage proof for move txid {:?}, l2 height {}, deposit_idx {}",
                move_txid, l2_height, deposit_idx
            ))?;

        tracing::debug!("Got storage proof in send_asserts {:?}", storage_proof);

        // get committed latest blockhash
        let wt_derive_path = ClementineBitVMPublicKeys::get_latest_blockhash_derivation(
            deposit_data.get_deposit_outpoint(),
            self.config.protocol_paramset(),
        );
        let commits = extract_winternitz_commits(
            latest_blockhash,
            &[wt_derive_path],
            self.config.protocol_paramset(),
        )?;

        let latest_blockhash = commits
            .first()
            .ok_or_eyre("Failed to get latest blockhash in send_asserts")?
            .to_owned();

        let rpc_current_finalized_height = self
            .rpc
            .get_current_chain_height()
            .await?
            .saturating_sub(self.config.protocol_paramset().finality_depth);

        // update headers in case the sync (state machine handle_finalized_block) is behind
        self.db
            .fetch_and_save_missing_blocks(
                &self.rpc,
                self.config.protocol_paramset().genesis_height,
                rpc_current_finalized_height + 1,
            )
            .await?;

        let current_height = self
            .db
            .get_latest_finalized_block_height(None)
            .await?
            .ok_or_eyre("Failed to get current finalized block height")?;

        let block_hashes = self
            .db
            .get_block_info_from_range(
                None,
                self.config.protocol_paramset().genesis_height as u64,
                current_height,
            )
            .await?;

        #[cfg(test)]
        let mut latest_blockhash = latest_blockhash;

        #[cfg(test)]
        {
            if self.config.test_params.disrupt_latest_block_hash_commit {
                tracing::info!("Correcting latest blockhash for testing purposes",);
                latest_blockhash[19] ^= 0x01;
            }
        }

        // find out which blockhash is latest_blockhash (only last 20 bytes is committed to Witness)
        let latest_blockhash_index = block_hashes
            .iter()
            .position(|(block_hash, _)| {
                block_hash.to_byte_array()[12..].to_vec() == latest_blockhash
            })
            .ok_or_eyre("Failed to find latest blockhash in send_asserts")?;

        let latest_blockhash = block_hashes[latest_blockhash_index].0;

        let (current_hcp, hcp_height) = self
            .header_chain_prover
            .prove_till_hash(latest_blockhash)
            .await?;
        tracing::info!("Got header chain proof in send_asserts");

        let blockhashes_serialized: Vec<[u8; 32]> = block_hashes
            .iter()
            .take(latest_blockhash_index + 1) // get all blocks up to and including latest_blockhash
            .map(|(block_hash, _)| block_hash.to_byte_array())
            .collect::<Vec<_>>();

        tracing::debug!(
            "Genesis height - Before SPV: {},",
            self.config.protocol_paramset().genesis_height
        );

        let spv = create_spv(
            payout_tx.clone(),
            &blockhashes_serialized,
            payout_block.clone(),
            payout_block_height,
            self.config.protocol_paramset().genesis_height,
            payout_tx_index as u32,
        );
        tracing::info!("Calculated spv proof in send_asserts");

        let mut wt_contexts = Vec::new();
        for (_, tx) in watchtower_challenges.iter() {
            wt_contexts.push(WatchtowerContext {
                watchtower_tx: tx.clone(),
                prevout_txs: self.rpc.get_prevout_txs(tx).await?,
            });
        }

        #[cfg(test)]
        {
            if self.config.test_params.operator_forgot_watchtower_challenge {
                tracing::info!("Disrupting watchtower challenges in send_asserts");
                wt_contexts.pop();
            }
        }

        let watchtower_challenge_connector_start_idx =
            (FIRST_FIVE_OUTPUTS + NUMBER_OF_ASSERT_TXS) as u16;

        let bridge_circuit_host_params = BridgeCircuitHostParams::new_with_wt_tx(
            kickoff_tx.clone(),
            spv,
            current_hcp,
            light_client_proof,
            lcp_receipt,
            storage_proof,
            self.config.protocol_paramset().network,
            &wt_contexts,
            watchtower_challenge_connector_start_idx,
        )
        .wrap_err("Failed to create bridge circuit host params in send_asserts")?;

        let bridge_circuit_elf = match self.config.protocol_paramset().network {
            bitcoin::Network::Bitcoin => MAINNET_BRIDGE_CIRCUIT_ELF,
            bitcoin::Network::Testnet4 => TESTNET4_BRIDGE_CIRCUIT_ELF,
            bitcoin::Network::Signet => SIGNET_BRIDGE_CIRCUIT_ELF,
            bitcoin::Network::Regtest => REGTEST_BRIDGE_CIRCUIT_ELF,
            _ => {
                return Err(eyre::eyre!(
                    "Unsupported network {:?} in send_asserts",
                    self.config.protocol_paramset().network
                )
                .into())
            }
        };
        tracing::info!("Starting proving bridge circuit to send asserts");
        let (g16_proof, g16_output, public_inputs) =
            prove_bridge_circuit(bridge_circuit_host_params, bridge_circuit_elf)?;
        tracing::info!("Proved bridge circuit in send_asserts");
        let public_input_scalar = ark_bn254::Fr::from_be_bytes_mod_order(&g16_output);

        #[cfg(test)]
        let mut public_inputs = public_inputs;

        #[cfg(test)]
        {
            if self
                .config
                .test_params
                .disrupt_challenge_sending_watchtowers_commit
            {
                tracing::info!("Disrupting challenge sending watchtowers commit in send_asserts");
                public_inputs.challenge_sending_watchtowers[0] ^= 0x01;
                tracing::info!(
                    "Disrupted challenge sending watchtowers commit: {:?}",
                    public_inputs.challenge_sending_watchtowers
                );
            }
        }
        tracing::info!(
            "Challenge sending watchtowers commit: {:?}",
            public_inputs.challenge_sending_watchtowers
        );

        let asserts = if cfg!(test) && is_dev_mode() {
            generate_assertions(
                g16_proof,
                vec![public_input_scalar],
                &get_ark_verifying_key_dev_mode_bridge(),
            )
            .map_err(|e| eyre::eyre!("Failed to generate dev mode assertions: {}", e))?
        } else {
            generate_assertions(
                g16_proof,
                vec![public_input_scalar],
                &get_ark_verifying_key(),
            )
            .map_err(|e| eyre::eyre!("Failed to generate assertions: {}", e))?
        };

        #[cfg(test)]
        let mut asserts = asserts;

        #[cfg(test)]
        {
            if self.config.test_params.corrupted_asserts {
                tracing::info!("Disrupting asserts commit in send_asserts");
                asserts.0[0][0] ^= 0x01;
            }
        }

        let assert_txs = self
            .create_assert_commitment_txs(
                TransactionRequestData {
                    kickoff_data,
                    deposit_outpoint: deposit_data.get_deposit_outpoint(),
                },
                ClementineBitVMPublicKeys::get_assert_commit_data(
                    asserts,
                    &public_inputs.challenge_sending_watchtowers,
                ),
            )
            .await?;

        let mut dbtx = self.db.begin_transaction().await?;
        for (tx_type, tx) in assert_txs {
            self.tx_sender
                .add_tx_to_queue(
                    &mut dbtx,
                    tx_type,
                    &tx,
                    &[],
                    Some(TxMetadata {
                        tx_type,
                        operator_xonly_pk: Some(self.signer.xonly_public_key),
                        round_idx: Some(kickoff_data.round_idx),
                        kickoff_idx: Some(kickoff_data.kickoff_idx),
                        deposit_outpoint: Some(deposit_data.get_deposit_outpoint()),
                    }),
                    &self.config,
                    None,
                )
                .await?;
        }
        dbtx.commit().await?;
        Ok(())
    }

    #[cfg(feature = "automation")]
    fn data(&self) -> OperatorData {
        OperatorData {
            xonly_pk: self.signer.xonly_public_key,
            collateral_funding_outpoint: self.collateral_funding_outpoint,
            reimburse_addr: self.reimburse_addr.clone(),
        }
    }

    #[cfg(feature = "automation")]
    async fn send_latest_blockhash(
        &self,
        kickoff_data: KickoffData,
        deposit_data: DepositData,
        latest_blockhash: BlockHash,
    ) -> Result<(), BridgeError> {
        tracing::warn!("Operator sending latest blockhash");
        let deposit_outpoint = deposit_data.get_deposit_outpoint();
        let (tx_type, tx) = self
            .create_latest_blockhash_tx(
                TransactionRequestData {
                    deposit_outpoint,
                    kickoff_data,
                },
                latest_blockhash,
            )
            .await?;
        if tx_type != TransactionType::LatestBlockhash {
            return Err(eyre::eyre!("Latest blockhash tx type is not LatestBlockhash").into());
        }
        let mut dbtx = self.db.begin_transaction().await?;
        self.tx_sender
            .add_tx_to_queue(
                &mut dbtx,
                tx_type,
                &tx,
                &[],
                Some(TxMetadata {
                    tx_type,
                    operator_xonly_pk: Some(self.signer.xonly_public_key),
                    round_idx: Some(kickoff_data.round_idx),
                    kickoff_idx: Some(kickoff_data.kickoff_idx),
                    deposit_outpoint: Some(deposit_outpoint),
                }),
                &self.config,
                None,
            )
            .await?;
        dbtx.commit().await?;
        Ok(())
    }
}

impl<C> NamedEntity for Operator<C>
where
    C: CitreaClientT,
{
    const ENTITY_NAME: &'static str = "operator";
}

#[cfg(feature = "automation")]
mod states {
    use super::*;
    use crate::builder::transaction::input::UtxoVout;
    use crate::builder::transaction::{
        create_txhandlers, ContractContext, ReimburseDbCache, TransactionType, TxHandler,
        TxHandlerCache,
    };
    use crate::states::context::DutyResult;
    use crate::states::{block_cache, Duty, Owner, StateManager};
    use std::collections::BTreeMap;
    use std::sync::Arc;

    #[tonic::async_trait]
    impl<C> Owner for Operator<C>
    where
        C: CitreaClientT,
    {
        async fn handle_duty(&self, duty: Duty) -> Result<DutyResult, BridgeError> {
            match duty {
                Duty::NewReadyToReimburse {
                    round_idx,
                    operator_xonly_pk,
                    used_kickoffs,
                } => {
                    tracing::info!("Operator {:?} called new ready to reimburse with round_idx: {:?}, operator_xonly_pk: {:?}, used_kickoffs: {:?}",
                    self.signer.xonly_public_key, round_idx, operator_xonly_pk, used_kickoffs);
                    Ok(DutyResult::Handled)
                }
                Duty::WatchtowerChallenge { .. } => Ok(DutyResult::Handled),
                Duty::SendOperatorAsserts {
                    kickoff_data,
                    deposit_data,
                    watchtower_challenges,
                    payout_blockhash,
                    latest_blockhash,
                } => {
                    tracing::warn!("Operator {:?} called send operator asserts with kickoff_data: {:?}, deposit_data: {:?}, watchtower_challenges: {:?}",
                    self.signer.xonly_public_key, kickoff_data, deposit_data, watchtower_challenges.len());
                    self.send_asserts(
                        kickoff_data,
                        deposit_data,
                        watchtower_challenges,
                        payout_blockhash,
                        latest_blockhash,
                    )
                    .await?;
                    Ok(DutyResult::Handled)
                }
                Duty::VerifierDisprove { .. } => Ok(DutyResult::Handled),
                Duty::SendLatestBlockhash {
                    kickoff_data,
                    deposit_data,
                    latest_blockhash,
                } => {
                    tracing::warn!("Operator {:?} called send latest blockhash with kickoff_id: {:?}, deposit_data: {:?}, latest_blockhash: {:?}", self.signer.xonly_public_key, kickoff_data, deposit_data, latest_blockhash);
                    self.send_latest_blockhash(kickoff_data, deposit_data, latest_blockhash)
                        .await?;
                    Ok(DutyResult::Handled)
                }
                Duty::CheckIfKickoff {
                    txid,
                    block_height,
                    witness,
                    challenged_before: _,
                } => {
                    tracing::debug!(
                        "Operator {:?} called check if kickoff with txid: {:?}, block_height: {:?}",
                        self.signer.xonly_public_key,
                        txid,
                        block_height,
                    );
                    let kickoff_data = self
                        .db
                        .get_deposit_data_with_kickoff_txid(None, txid)
                        .await?;
                    if let Some((deposit_data, kickoff_data)) = kickoff_data {
                        let mut dbtx = self.db.begin_transaction().await?;
                        StateManager::<Self>::dispatch_new_kickoff_machine(
                            self.db.clone(),
                            &mut dbtx,
                            kickoff_data,
                            block_height,
                            deposit_data,
                            witness,
                        )
                        .await?;
                        dbtx.commit().await?;
                    }
                    Ok(DutyResult::Handled)
                }
            }
        }

        async fn create_txhandlers(
            &self,
            tx_type: TransactionType,
            contract_context: ContractContext,
        ) -> Result<BTreeMap<TransactionType, TxHandler>, BridgeError> {
            let mut db_cache = ReimburseDbCache::from_context(self.db.clone(), &contract_context);
            let txhandlers = create_txhandlers(
                tx_type,
                contract_context,
                &mut TxHandlerCache::new(),
                &mut db_cache,
            )
            .await?;
            Ok(txhandlers)
        }

        async fn handle_finalized_block(
            &self,
            _dbtx: DatabaseTransaction<'_, '_>,
            _block_id: u32,
            _block_height: u32,
            _block_cache: Arc<block_cache::BlockCache>,
            _light_client_proof_wait_interval_secs: Option<u32>,
        ) -> Result<(), BridgeError> {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::operator::Operator;
    use crate::test::common::citrea::MockCitreaClient;
    use crate::test::common::*;
    use bitcoin::hashes::Hash;
    use bitcoin::{OutPoint, Txid};

    // #[tokio::test]
    // async fn set_funding_utxo() {
    //     let mut config = create_test_config_with_thread_name().await;
    //     let rpc = ExtendedRpc::connect(
    //         config.bitcoin_rpc_url.clone(),
    //         config.bitcoin_rpc_user.clone(),
    //         config.bitcoin_rpc_password.clone(),
    //     )
    //     .await;

    //     let operator = Operator::new(config, rpc).await.unwrap();

    //     let funding_utxo = UTXO {
    //         outpoint: OutPoint {
    //             txid: Txid::all_zeros(),
    //             vout: 0x45,
    //         },
    //         txout: TxOut {
    //             value: Amount::from_sat(0x1F),
    //             script_pubkey: ScriptBuf::new(),
    //         },
    //     };

    //     operator
    //         .set_funding_utxo(funding_utxo.clone())
    //         .await
    //         .unwrap();

    //     let db_funding_utxo = operator.db.get_funding_utxo(None).await.unwrap().unwrap();

    //     assert_eq!(funding_utxo, db_funding_utxo);
    // }

    // #[tokio::test]
    // async fn is_profitable() {
    //     let mut config = create_test_config_with_thread_name().await;
    //     let rpc = ExtendedRpc::connect(
    //         config.bitcoin_rpc_url.clone(),
    //         config.bitcoin_rpc_user.clone(),
    //         config.bitcoin_rpc_password.clone(),
    //     )
    //     .await;

    //     config.protocol_paramset().bridge_amount = Amount::from_sat(0x45);
    //     config.operator_withdrawal_fee_sats = Some(Amount::from_sat(0x1F));

    //     let operator = Operator::new(config.clone(), rpc).await.unwrap();

    //     // Smaller input amount must not cause a panic.
    //     operator.is_profitable(Amount::from_sat(3), Amount::from_sat(1));
    //     // Bigger input amount must not cause a panic.
    //     operator.is_profitable(Amount::from_sat(6), Amount::from_sat(9));

    //     // False because difference between input and withdrawal amount is
    //     // bigger than `config.protocol_paramset().bridge_amount`.
    //     assert!(!operator.is_profitable(Amount::from_sat(6), Amount::from_sat(90)));

    //     // False because net profit is smaller than
    //     // `config.operator_withdrawal_fee_sats`.
    //     assert!(!operator.is_profitable(Amount::from_sat(0), config.protocol_paramset().bridge_amount));

    //     // True because net profit is bigger than
    //     // `config.operator_withdrawal_fee_sats`.
    //     assert!(operator.is_profitable(
    //         Amount::from_sat(0),
    //         config.operator_withdrawal_fee_sats.unwrap() - Amount::from_sat(1)
    //     ));
    // }

    #[tokio::test]
    #[ignore = "Design changes in progress"]
    async fn get_winternitz_public_keys() {
        let mut config = create_test_config_with_thread_name().await;
        let _regtest = create_regtest_rpc(&mut config).await;

        let operator = Operator::<MockCitreaClient>::new(config.clone())
            .await
            .unwrap();

        let deposit_outpoint = OutPoint {
            txid: Txid::all_zeros(),
            vout: 2,
        };

        let winternitz_public_key = operator
            .generate_assert_winternitz_pubkeys(deposit_outpoint)
            .unwrap();
        assert_eq!(
            winternitz_public_key.len(),
            config.protocol_paramset().num_round_txs
                * config.protocol_paramset().num_kickoffs_per_round
        );
    }

    #[tokio::test]
    async fn operator_get_params() {
        let mut config = create_test_config_with_thread_name().await;
        let _regtest = create_regtest_rpc(&mut config).await;

        let operator = Operator::<MockCitreaClient>::new(config.clone())
            .await
            .unwrap();
        let actual_wpks = operator.generate_kickoff_winternitz_pubkeys().unwrap();

        let (mut wpk_rx, _) = operator.get_params().await.unwrap();
        let mut idx = 0;
        while let Some(wpk) = wpk_rx.recv().await {
            assert_eq!(actual_wpks[idx], wpk);
            idx += 1;
        }
        assert_eq!(idx, actual_wpks.len());
    }
}