stoffel-vm 0.1.0

Register-based virtual machine runtime and MPC execution engine for Stoffel programs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
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
//! Threshold Signature Integration Tests
//!
//! These tests validate that the AVSS MPC backend can perform Schnorr, EdDSA,
//! and BLS threshold signatures, verified with third-party libraries.
//!
//! Each test:
//! 1. Sets up 5 AVSS nodes with QUIC transport
//! 2. Creates AVSS engines and message processors
//! 3. Runs a bytecode program on all 5 VMs in parallel (MPC requires all parties)
//! 4. Verifies signatures using arkworks / ed25519-dalek
//!
//! ## Security properties
//!
//! **Threshold DKG**: `Share.random()` uses the multi-dealer RanSha protocol —
//! ALL parties contribute randomness, so no single party knows the combined
//! secret key. Compromising fewer than `t` parties reveals nothing.
//!
//! **Nonce safety**: Each `Share.random()` call runs a new RanSha round with a
//! unique session ID derived from party-local entropy. The nonce `k` is:
//! - Fresh per invocation (new session, new randomness from all parties)
//! - Bound to the message via the challenge hash `e = H(R || pk || msg)`
//! - Consumed by `Share.open_field(k + e*sk)` (share is destroyed after opening)
//!
//! Nonce reuse across messages is prevented by the protocol: a new
//! `Share.random()` generates a new cooperative random value each time.
//! Re-signing the same message produces a different (but equally valid)
//! signature because the nonce is freshly random.

#![allow(clippy::needless_range_loop, clippy::while_let_loop)]

use ark_ec::{AffineRepr, CurveGroup, PrimeGroup};
use ark_ff::PrimeField;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::rand::SeedableRng;
use ark_std::{UniformRand, Zero};
use sha2::Digest as _;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use stoffel_vm_types::core_types::Value;
use stoffel_vm_types::functions::VMFunction;
use stoffel_vm_types::instructions::Instruction;
use stoffelnet::network_utils::{Network, Node, VerifiedOrdering};
use stoffelnet::transports::quic::{
    NetworkManager, PeerConnection as QuicPeerConnection, QuicNetworkManager,
};
use tokio::sync::mpsc;
use tracing::{error, info, warn};

use crate::core_vm::VirtualMachine;
use crate::net::avss_engine::{AvssEngineConfig, AvssMpcEngine};
use crate::net::curve::SupportedMpcField;
use crate::net::MpcSessionConfig;
use crate::tests::avss_certificate_programs::{
    build_threshold_ecdsa_program, THRESHOLD_ECDSA_DEMO_MESSAGE_INPUT,
};
use crate::tests::test_utils::{
    init_crypto_provider, read_vm_table_byte_array, setup_test_tracing,
};

#[derive(Clone, Copy)]
enum EcdsaThirdPartyVerifier {
    Secp256k1,
    P256,
}

impl EcdsaThirdPartyVerifier {
    fn verify(self, message_hash: &[u8], public_key: &[u8], r: &[u8; 32], s: &[u8; 32]) {
        match self {
            Self::Secp256k1 => verify_secp256k1_ecdsa(message_hash, public_key, r, s),
            Self::P256 => verify_p256_ecdsa(message_hash, public_key, r, s),
        }
    }
}

// ---------------------------------------------------------------------------
// SimplePartyNetwork - party-id-based Network adapter (same as avss_e2e)
// ---------------------------------------------------------------------------

struct SimplePartyNetwork {
    node_id: usize,
    n: usize,
    connections: Vec<Option<Arc<dyn QuicPeerConnection>>>,
    self_tx: mpsc::Sender<(usize, Vec<u8>)>,
}

struct SimpleNode {
    id: usize,
}

impl stoffelnet::network_utils::Node for SimpleNode {
    fn id(&self) -> usize {
        self.id
    }
    fn scalar_id<F: ark_ff::Field>(&self) -> F {
        F::from((self.id + 1) as u64)
    }
}

struct SimpleNetworkConfig;

#[async_trait::async_trait]
impl stoffelnet::network_utils::Network for SimplePartyNetwork {
    type NodeType = SimpleNode;
    type NetworkConfig = SimpleNetworkConfig;

    async fn send(
        &self,
        recipient: usize,
        message: &[u8],
    ) -> Result<usize, stoffelnet::network_utils::NetworkError> {
        if recipient == self.node_id {
            self.self_tx
                .send((self.node_id, message.to_vec()))
                .await
                .map_err(|_| stoffelnet::network_utils::NetworkError::SendError)?;
            return Ok(message.len());
        }
        let conn = self
            .connections
            .get(recipient)
            .and_then(|c| c.as_ref())
            .ok_or(stoffelnet::network_utils::NetworkError::PartyNotFound(
                recipient,
            ))?;
        conn.send(message)
            .await
            .map_err(|_| stoffelnet::network_utils::NetworkError::SendError)?;
        Ok(message.len())
    }

    async fn broadcast(
        &self,
        message: &[u8],
    ) -> Result<usize, stoffelnet::network_utils::NetworkError> {
        let mut total = 0;
        if self
            .self_tx
            .send((self.node_id, message.to_vec()))
            .await
            .is_ok()
        {
            total += message.len();
        }
        for (i, conn_opt) in self.connections.iter().enumerate() {
            if i == self.node_id {
                continue;
            }
            if let Some(conn) = conn_opt {
                if conn.send(message).await.is_ok() {
                    total += message.len();
                }
            }
        }
        Ok(total)
    }

    fn parties(&self) -> Vec<&Self::NodeType> {
        vec![]
    }
    fn parties_mut(&mut self) -> Vec<&mut Self::NodeType> {
        vec![]
    }
    fn config(&self) -> &Self::NetworkConfig {
        &SimpleNetworkConfig
    }
    fn node(&self, _id: usize) -> Option<&Self::NodeType> {
        None
    }
    fn node_mut(&mut self, _id: usize) -> Option<&mut Self::NodeType> {
        None
    }
    async fn send_to_client(
        &self,
        _client: usize,
        _message: &[u8],
    ) -> Result<usize, stoffelnet::network_utils::NetworkError> {
        Err(stoffelnet::network_utils::NetworkError::SendError)
    }
    fn clients(&self) -> Vec<usize> {
        vec![]
    }
    fn is_client_connected(&self, _client: usize) -> bool {
        false
    }
    fn local_party_id(&self) -> usize {
        self.node_id
    }
    fn party_count(&self) -> usize {
        self.n
    }
    fn verified_ordering(&self) -> Option<VerifiedOrdering> {
        None
    }
}

fn build_simple_network(
    node_id: usize,
    n: usize,
    peer_connections: Vec<(usize, Arc<dyn QuicPeerConnection>)>,
    self_tx: mpsc::Sender<(usize, Vec<u8>)>,
) -> Arc<SimplePartyNetwork> {
    let mut conns: Vec<Option<Arc<dyn QuicPeerConnection>>> = vec![None; n];
    for (pid, conn) in peer_connections {
        conns[pid] = Some(conn);
    }
    Arc::new(SimplePartyNetwork {
        node_id,
        n,
        connections: conns,
        self_tx,
    })
}

// ---------------------------------------------------------------------------
// Test Node (generic over field/curve)
// ---------------------------------------------------------------------------

/// A test AVSS node with QUIC networking and ECDH keypair.
/// Generic over field F and group G to support different curves.
struct TestNode<F: ark_ff::Field, G: CurveGroup<ScalarField = F>> {
    node_id: usize,
    network: Option<Arc<QuicNetworkManager>>,
    network_builder: Option<QuicNetworkManager>,
    rx: Option<mpsc::Receiver<(usize, Vec<u8>)>>,
    tx: mpsc::Sender<(usize, Vec<u8>)>,
    simple_net: Option<Arc<SimplePartyNetwork>>,
    sk_i: F,
    pk_i: G,
}

impl<F, G> TestNode<F, G>
where
    F: ark_ff::Field + UniformRand,
    G: CurveGroup<ScalarField = F>,
{
    fn new(node_id: usize) -> Self {
        let (tx, rx) = mpsc::channel(1500);
        let mut rng = ark_std::rand::rngs::StdRng::from_entropy();
        let sk_i = F::rand(&mut rng);
        let pk_i = G::generator() * sk_i;
        let mgr = QuicNetworkManager::with_node_id(node_id);

        Self {
            node_id,
            network: None,
            network_builder: Some(mgr),
            rx: Some(rx),
            tx,
            simple_net: None,
            sk_i,
            pk_i,
        }
    }
}

// ---------------------------------------------------------------------------
// Network setup (mirrors avss_e2e_integration)
// ---------------------------------------------------------------------------

async fn setup_test_network<F, G>(n: usize, base_port: u16) -> Result<Vec<TestNode<F, G>>, String>
where
    F: ark_ff::Field + UniformRand + PrimeField,
    G: CurveGroup<ScalarField = F> + CanonicalSerialize + CanonicalDeserialize,
{
    let addresses: Vec<SocketAddr> = (0..n)
        .map(|i| {
            format!("127.0.0.1:{}", base_port + i as u16)
                .parse()
                .unwrap()
        })
        .collect();

    info!(
        "[TSIG] Setting up {} nodes on ports {}..{}",
        n,
        base_port,
        base_port + n as u16 - 1
    );

    // Step 1: Create nodes and start listening
    let mut nodes = Vec::with_capacity(n);
    for i in 0..n {
        let mut node = TestNode::<F, G>::new(i);
        let mgr = node.network_builder.as_mut().unwrap();
        mgr.listen(addresses[i])
            .await
            .map_err(|e| format!("Node {} listen failed: {}", i, e))?;
        nodes.push(node);
    }

    // Step 1b: Collect TLS-derived IDs and cross-register peers
    let derived_ids: Vec<usize> = nodes
        .iter()
        .map(|n| n.network_builder.as_ref().unwrap().local_derived_id())
        .collect();

    for i in 0..n {
        let mgr = nodes[i].network_builder.as_mut().unwrap();
        mgr.add_node_with_party_id(derived_ids[i], addresses[i]);
        for j in 0..n {
            if j != i {
                mgr.add_node_with_party_id(derived_ids[j], addresses[j]);
            }
        }
    }

    let derived_to_logical: HashMap<usize, usize> = derived_ids
        .iter()
        .enumerate()
        .map(|(logical, &derived)| (derived, logical))
        .collect();

    // Step 2: Start - convert builders to Arc and spawn accept loops
    for node in &mut nodes {
        let mgr = node.network_builder.take().unwrap();
        let net = Arc::new(mgr);
        node.network = Some(net.clone());

        let mut acceptor = (*net).clone();
        let node_id = node.node_id;
        tokio::spawn(async move {
            loop {
                match acceptor.accept().await {
                    Ok(_connection) => {
                        info!("[TSIG] Node {} accepted connection", node_id);
                    }
                    Err(e) => {
                        warn!("[TSIG] Node {} accept error: {}", node_id, e);
                        tokio::time::sleep(Duration::from_millis(100)).await;
                    }
                }
            }
        });
    }

    // Step 3: Dial all peers
    for idx in 0..n {
        let net = nodes[idx].network.as_ref().unwrap();
        let local_derived = derived_ids[idx];
        let peers: Vec<(usize, SocketAddr)> = net
            .parties()
            .iter()
            .map(|p| (p.id(), p.address()))
            .collect();

        let mut dialer = (**net).clone();
        let node_id = nodes[idx].node_id;

        for (peer_derived_id, peer_addr) in peers {
            if peer_derived_id == local_derived {
                continue;
            }
            let peer_logical = *derived_to_logical
                .get(&peer_derived_id)
                .unwrap_or(&peer_derived_id);
            let mut retry_count = 0u32;
            loop {
                match dialer.connect_as_server(peer_addr).await {
                    Ok(_connection) => {
                        info!(
                            "[TSIG] Node {} connected to peer {} at {}",
                            node_id, peer_logical, peer_addr
                        );
                        break;
                    }
                    Err(e) => {
                        retry_count += 1;
                        if retry_count >= 10 {
                            warn!(
                                "[TSIG] Node {} failed to connect to peer {} after {} attempts: {}",
                                node_id, peer_logical, retry_count, e
                            );
                            break;
                        }
                        tokio::time::sleep(Duration::from_millis(100)).await;
                    }
                }
            }
        }
    }

    tokio::time::sleep(Duration::from_millis(500)).await;

    // Step 3b: assign_party_ids
    for node in &nodes {
        let net = node.network.as_ref().unwrap();
        let assigned = net.assign_party_ids();
        let local_pid = net
            .compute_local_party_id()
            .expect("compute_local_party_id failed");
        info!(
            "[TSIG] Node {} assigned {} party IDs, sorted-key party_id={}",
            node.node_id, assigned, local_pid
        );
    }

    let party_ids: Vec<usize> = nodes
        .iter()
        .map(|n| {
            n.network
                .as_ref()
                .unwrap()
                .compute_local_party_id()
                .unwrap()
        })
        .collect();

    // Step 4: Build SimplePartyNetwork and spawn receive handlers
    for idx in 0..n {
        let net = nodes[idx].network.as_ref().unwrap();
        let local_pid = party_ids[idx];
        let tx = nodes[idx].tx.clone();
        let node_id = nodes[idx].node_id;

        let all_conns = net.get_all_server_connections();
        let mut peer_conns: Vec<(usize, Arc<dyn QuicPeerConnection>)> = Vec::new();
        for (did, conn) in all_conns {
            if did == net.local_derived_id() {
                continue;
            }
            let pid = conn
                .remote_party_id()
                .unwrap_or_else(|| *derived_to_logical.get(&did).unwrap_or(&did));
            if pid == local_pid {
                continue;
            }
            peer_conns.push((pid, conn.clone()));

            let txx = tx.clone();
            tokio::spawn(async move {
                loop {
                    match conn.receive().await {
                        Ok(data) => {
                            if let Err(e) = txx.send((pid, data)).await {
                                error!("[TSIG] Node {} recv send error: {:?}", node_id, e);
                            }
                        }
                        Err(_) => break,
                    }
                }
            });
        }

        info!(
            "[TSIG] Node {} (party_id={}) has {} peer connections",
            idx,
            local_pid,
            peer_conns.len()
        );

        let self_tx = nodes[idx].tx.clone();
        nodes[idx].simple_net = Some(build_simple_network(local_pid, n, peer_conns, self_tx));
        nodes[idx].node_id = local_pid;
    }

    tokio::time::sleep(Duration::from_millis(100)).await;

    Ok(nodes)
}

/// Exchange ECDH public keys between all nodes.
async fn exchange_ecdh_keys<F, G>(nodes: &mut [TestNode<F, G>]) -> Result<Vec<Arc<Vec<G>>>, String>
where
    F: ark_ff::Field + UniformRand + PrimeField,
    G: CurveGroup<ScalarField = F> + CanonicalSerialize + CanonicalDeserialize,
{
    let n = nodes.len();

    // Each node sends its PK to all peers
    for node in nodes.iter() {
        let net = node.network.as_ref().unwrap();

        let mut pk_bytes = Vec::new();
        node.pk_i
            .serialize_compressed(&mut pk_bytes)
            .map_err(|e| format!("serialize PK: {:?}", e))?;

        let mut envelope = Vec::with_capacity(4 + pk_bytes.len());
        envelope.extend_from_slice(&(node.node_id as u32).to_le_bytes());
        envelope.extend_from_slice(&pk_bytes);

        let local_derived = net.local_derived_id();
        let connections = net.get_all_server_connections();
        for (peer_id, conn) in &connections {
            if *peer_id == local_derived {
                continue;
            }
            if let Err(e) = conn.send(&envelope).await {
                warn!(
                    "[TSIG] Node {} failed to send PK to peer {}: {}",
                    node.node_id, peer_id, e
                );
            }
        }
    }

    // Collect PKs from channels
    let mut all_pk_maps = Vec::with_capacity(n);

    for node in nodes.iter_mut() {
        let mut pk_map = vec![G::default(); n];
        pk_map[node.node_id] = node.pk_i;
        let mut received = 1usize;

        let rx = node.rx.as_mut().unwrap();
        let deadline = std::time::Instant::now() + Duration::from_secs(10);

        while received < n {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                return Err(format!(
                    "Node {} PK exchange timeout: {}/{}",
                    node.node_id, received, n
                ));
            }

            match tokio::time::timeout(remaining, rx.recv()).await {
                Ok(Some((_sender, data))) => {
                    if data.len() < 4 {
                        continue;
                    }
                    let sender_id =
                        u32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
                    if sender_id >= n {
                        continue;
                    }
                    match G::deserialize_compressed(&data[4..]) {
                        Ok(pk) => {
                            pk_map[sender_id] = pk;
                            received += 1;
                        }
                        Err(_) => {
                            // Skip non-PK messages
                            continue;
                        }
                    }
                }
                Ok(None) => break,
                Err(_) => {
                    return Err(format!(
                        "Node {} PK exchange timeout: {}/{}",
                        node.node_id, received, n
                    ));
                }
            }
        }

        all_pk_maps.push(Arc::new(pk_map));
    }

    Ok(all_pk_maps)
}

/// Spawn message processors that handle:
/// - Open registry wire messages (for Share.open, Share.open_field)
/// - AVSS open-in-exp wire messages (for Share.open_exp on G1)
/// - AVSS G2 open-in-exp wire messages (for Share.open_exp on G2)
/// - AVSS protocol messages (RBC, share delivery)
fn spawn_message_processors<F, G>(
    nodes: &mut [TestNode<F, G>],
    engines: &[Arc<AvssMpcEngine<F, G>>],
) where
    F: ark_ff::FftField + PrimeField + Send + Sync + 'static,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    for (i, node) in nodes.iter_mut().enumerate() {
        let rx = node.rx.take().unwrap();
        let engine = engines[i].clone();
        let open_message_router = engine.open_message_router();
        let simple_net = node.simple_net.clone().unwrap();
        let node_id = node.node_id;

        tokio::spawn(async move {
            let mut rx = rx;
            while let Some((sender_id, data)) = rx.recv().await {
                // 1. Check open registry (Share.open, Share.open_field, Share.batch_open)
                match open_message_router.try_handle_wire_message(sender_id, &data) {
                    Ok(true) => continue,
                    Err(e) => {
                        error!(
                            "[TSIG] Node {} open registry error from {}: {}",
                            node_id, sender_id, e
                        );
                        continue;
                    }
                    Ok(false) => {}
                }

                // 2. Check AVSS open-in-exp (G1) wire messages
                match open_message_router.try_handle_avss_open_exp_wire_message(sender_id, &data) {
                    Ok(true) => continue,
                    Err(_) => {} // Not an open-exp message, continue
                    Ok(false) => {}
                }

                // 3. Check AVSS G2 open-in-exp wire messages
                match open_message_router.try_handle_avss_g2_exp_wire_message(sender_id, &data) {
                    Ok(true) => continue,
                    Err(_) => {}
                    Ok(false) => {}
                }

                // 4. AVSS protocol messages (RBC, share delivery)
                match engine
                    .process_wrapped_message_with_network(sender_id, &data, simple_net.clone())
                    .await
                {
                    Ok(()) => {}
                    Err(e) => {
                        if !e.contains("deserialize") {
                            error!("[TSIG] Node {} process error: {}", node_id, e);
                        }
                    }
                }
            }
        });
    }
}

// ---------------------------------------------------------------------------
// Helper: extract byte array from VM Value::Array
// ---------------------------------------------------------------------------

fn extract_vm_byte_array(vm: &mut VirtualMachine, value: &Value) -> Vec<u8> {
    match value {
        Value::Array(arr_ref) => read_vm_table_byte_array(vm, arr_ref.id()).unwrap(),
        other => panic!("Expected Array, got {:?}", other),
    }
}

// ---------------------------------------------------------------------------
// Helper: run a bytecode program on N parties with live MPC engines
// ---------------------------------------------------------------------------

/// Run the given instructions as "main" on all parties concurrently.
/// Returns (VM, result) for each party.
async fn run_program_on_all_parties<F, G>(
    engines: &[Arc<AvssMpcEngine<F, G>>],
    instructions: Vec<Instruction>,
    register_count: usize,
) -> Vec<(VirtualMachine, Value)>
where
    F: ark_ff::FftField + PrimeField + Send + Sync + 'static,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
    AvssMpcEngine<F, G>: crate::net::mpc_engine::MpcEngine,
{
    let n = engines.len();
    let mut handles = Vec::with_capacity(n);

    for i in 0..n {
        let engine: Arc<dyn crate::net::mpc_engine::MpcEngine> = engines[i].clone();
        let program = instructions.clone();
        let reg_count = register_count;
        handles.push(tokio::task::spawn_blocking(move || {
            let mut vm = VirtualMachine::builder().with_mpc_engine(engine).build();

            let func = VMFunction::new(
                "main".to_string(),
                vec![],
                vec![],
                None,
                reg_count,
                program,
                HashMap::new(),
            );
            vm.register_function(func);
            let result = vm.execute("main").expect("VM execution failed");
            (vm, result)
        }));
    }

    let results: Vec<(VirtualMachine, Value)> = futures::future::join_all(handles)
        .await
        .into_iter()
        .map(|r| r.expect("task panicked"))
        .collect();

    results
}

async fn run_threshold_ecdsa_case<F, G>(
    curve_name: &str,
    instance_id: u64,
    base_port: u16,
    third_party_verifier: EcdsaThirdPartyVerifier,
) where
    F: SupportedMpcField
        + ark_ff::FftField
        + PrimeField
        + UniformRand
        + CanonicalDeserialize
        + CanonicalSerialize
        + Send
        + Sync
        + 'static,
    G: CurveGroup<ScalarField = F>
        + PrimeGroup
        + CanonicalSerialize
        + CanonicalDeserialize
        + std::ops::Mul<F, Output = G>
        + Send
        + Sync
        + 'static,
    G::Affine: CanonicalDeserialize + CanonicalSerialize + AffineRepr,
    AvssMpcEngine<F, G>: crate::net::mpc_engine::MpcEngine,
{
    init_crypto_provider();
    setup_test_tracing();

    let n = 5;
    let t = 1;

    let mut nodes = setup_test_network::<F, G>(n, base_port)
        .await
        .expect("Failed to create test network");

    let pk_maps = exchange_ecdh_keys(&mut nodes)
        .await
        .expect("PK exchange failed");

    let mut engines: Vec<Arc<AvssMpcEngine<F, G>>> = Vec::with_capacity(n);
    for (i, node) in nodes.iter().enumerate() {
        let session = MpcSessionConfig::try_new(
            instance_id,
            node.node_id,
            n,
            t,
            node.network.clone().unwrap(),
        )
        .expect("test topology should be valid");
        let engine = AvssMpcEngine::from_config(AvssEngineConfig::new(
            session,
            node.sk_i,
            pk_maps[i].clone(),
        ))
        .await
        .expect("Failed to create engine");
        engine.start_async().await.expect("Failed to start engine");
        engines.push(engine);
    }

    spawn_message_processors(&mut nodes, &engines);

    let (program, _) = build_threshold_ecdsa_program(curve_name);
    info!(
        "Running ECDSA signing program on {} parties for {}...",
        n, curve_name
    );
    let mut results = run_program_on_all_parties(&engines, program, 16).await;

    let mut byte_results: Vec<Vec<u8>> = Vec::new();
    for (vm, result) in &mut results {
        byte_results.push(extract_vm_byte_array(vm, result));
    }

    for i in 1..n {
        assert_eq!(
            byte_results[0], byte_results[i],
            "Party 0 and party {} produced different ECDSA results",
            i
        );
    }

    let result = &byte_results[0];
    let scalar_len = serialized_field_len::<F>();
    let public_key_len = result
        .len()
        .checked_sub(2 * scalar_len)
        .expect("result must contain r, s, and pk");
    assert_eq!(scalar_len, 32, "ECDSA scalar fixtures should be 32 bytes");
    assert_eq!(
        public_key_len, 33,
        "ECDSA public keys should be compressed SEC1 points"
    );

    let r_be: [u8; 32] = result[..scalar_len]
        .try_into()
        .expect("ECDSA r should be fixed-width");
    let s_be: [u8; 32] = result[scalar_len..2 * scalar_len]
        .try_into()
        .expect("ECDSA s should be fixed-width");
    let r_scalar = F::from_be_bytes_mod_order(&r_be);
    let s_scalar = F::from_be_bytes_mod_order(&s_be);
    let public_key_sec1 = &result[2 * scalar_len..];

    assert!(!r_scalar.is_zero(), "ECDSA r must be nonzero");
    assert!(!s_scalar.is_zero(), "ECDSA s must be nonzero");

    let message_hash = sha2::Sha256::digest(THRESHOLD_ECDSA_DEMO_MESSAGE_INPUT.as_bytes());
    third_party_verifier.verify(&message_hash, public_key_sec1, &r_be, &s_be);

    println!("\n=== Threshold ECDSA Signature ({}) ===", curve_name);
    println!("  Parties:   {}", n);
    println!("  Threshold: {}", t);
    println!("  Message:   \"{}\"", THRESHOLD_ECDSA_DEMO_MESSAGE_INPUT);
    println!(
        "  Public Key SEC1 ({} bytes): 0x{}",
        public_key_len,
        hex::encode(&result[2 * scalar_len..])
    );
    println!(
        "  r ({} bytes):          0x{}",
        scalar_len,
        hex::encode(&result[..scalar_len])
    );
    println!(
        "  s ({} bytes):          0x{}",
        scalar_len,
        hex::encode(&result[scalar_len..2 * scalar_len])
    );
    println!("  Verification via RustCrypto ECDSA: PASSED");
    println!("================================================\n");
}

fn serialized_field_len<F>() -> usize
where
    F: Zero + CanonicalSerialize,
{
    let mut bytes = Vec::new();
    F::zero()
        .serialize_compressed(&mut bytes)
        .expect("serialize zero scalar");
    bytes.len()
}

fn signature_bytes(r: &[u8; 32], s: &[u8; 32]) -> [u8; 64] {
    let mut bytes = [0u8; 64];
    bytes[..32].copy_from_slice(r);
    bytes[32..].copy_from_slice(s);
    bytes
}

fn verify_secp256k1_ecdsa(message_hash: &[u8], public_key: &[u8], r: &[u8; 32], s: &[u8; 32]) {
    use k256::ecdsa::signature::hazmat::PrehashVerifier as _;

    let verifying_key =
        k256::ecdsa::VerifyingKey::from_sec1_bytes(public_key).expect("valid secp256k1 public key");
    let signature = k256::ecdsa::Signature::from_slice(&signature_bytes(r, s))
        .expect("valid secp256k1 ECDSA signature");
    let signature = signature.normalize_s().unwrap_or(signature);

    verifying_key
        .verify_prehash(message_hash, &signature)
        .expect("secp256k1 signature should verify with RustCrypto");
}

fn verify_p256_ecdsa(message_hash: &[u8], public_key: &[u8], r: &[u8; 32], s: &[u8; 32]) {
    use p256::ecdsa::signature::hazmat::PrehashVerifier as _;

    let verifying_key =
        p256::ecdsa::VerifyingKey::from_sec1_bytes(public_key).expect("valid P-256 public key");
    let signature = p256::ecdsa::Signature::from_slice(&signature_bytes(r, s))
        .expect("valid P-256 ECDSA signature");

    verifying_key
        .verify_prehash(message_hash, &signature)
        .expect("P-256 signature should verify with RustCrypto");
}

// ===========================================================================
// Test 0: ECDSA Threshold Signatures (secp256k1 and P-256)
// ===========================================================================

/// Threshold ECDSA using the Bar-Ilan/Beaver inversion trick:
///   [delta] = [gamma] * [k]
///   [k^-1] = Open([delta])^-1 * [gamma]
///   R = Open(Convert([k]))
///   [s] = [e/k] + r * [sk/k]
#[tokio::test(flavor = "multi_thread")]
async fn test_threshold_ecdsa_secp256k1() {
    use ark_secp256k1::{Fr, Projective};

    run_threshold_ecdsa_case::<Fr, Projective>(
        "secp256k1",
        900_003,
        13300,
        EcdsaThirdPartyVerifier::Secp256k1,
    )
    .await;
}

#[tokio::test(flavor = "multi_thread")]
async fn test_threshold_ecdsa_p256() {
    use ark_secp256r1::{Fr, Projective};

    run_threshold_ecdsa_case::<Fr, Projective>(
        "p-256",
        900_004,
        13400,
        EcdsaThirdPartyVerifier::P256,
    )
    .await;
}

// ===========================================================================
// Test 1: Schnorr Threshold Signature (Ed25519)
// Verified by: arkworks
// ===========================================================================

/// Standard Schnorr threshold signature on Ed25519:
///   sk = DKG random  (multi-dealer RanSha — no party knows sk)
///   pk = commitment[0] = g^sk
///   k = DKG random  (nonce)
///   R = commitment[0] of k = g^k
///   e = SHA-256(R || msg) mod l  [standard Schnorr — no pk in hash]
///   s = k + e*sk  (threshold open)
///   Signature = (R, s)
///
/// Verification: g^s == R + e*pk (arkworks)
#[tokio::test(flavor = "multi_thread")]
async fn test_threshold_schnorr_ed25519() {
    use ark_ed25519::{EdwardsAffine, EdwardsProjective, Fr};

    init_crypto_provider();
    setup_test_tracing();
    info!("=== Threshold Schnorr Signature (Ed25519) ===");

    let n = 5;
    let t = 1;
    let instance_id = 900_000u64;
    let base_port = 13000u16;

    let mut nodes = setup_test_network::<Fr, EdwardsProjective>(n, base_port)
        .await
        .expect("Failed to create test network");

    let pk_maps = exchange_ecdh_keys(&mut nodes)
        .await
        .expect("PK exchange failed");

    let mut engines: Vec<Arc<AvssMpcEngine<Fr, EdwardsProjective>>> = Vec::with_capacity(n);
    for (i, node) in nodes.iter().enumerate() {
        let session = MpcSessionConfig::try_new(
            instance_id,
            node.node_id,
            n,
            t,
            node.network.clone().unwrap(),
        )
        .expect("test topology should be valid");
        let engine = AvssMpcEngine::from_config(AvssEngineConfig::new(
            session,
            node.sk_i,
            pk_maps[i].clone(),
        ))
        .await
        .expect("Failed to create engine");
        engine.start_async().await.expect("Failed to start engine");
        engines.push(engine);
    }

    spawn_message_processors(&mut nodes, &engines);

    // Schnorr signing program on Ed25519
    // Challenge: e = SHA-256(R || msg) — standard Schnorr (no pk in hash)
    // Result layout: R(32) + s(32) + pk(32) = 96 bytes
    let program = vec![
        // DKG for secret key
        Instruction::CALL("Share.random".to_string()),
        Instruction::MOV(1, 0), // r1 = sk share
        // pk = commitment[0]
        Instruction::LDI(2, Value::I64(0)),
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(2),
        Instruction::CALL("Share.get_commitment".to_string()),
        Instruction::MOV(3, 0), // r3 = pk bytes (32)
        // DKG for nonce
        Instruction::CALL("Share.random".to_string()),
        Instruction::MOV(4, 0), // r4 = k share
        // R = commitment[0] of nonce
        Instruction::LDI(2, Value::I64(0)),
        Instruction::PUSHARG(4),
        Instruction::PUSHARG(2),
        Instruction::CALL("Share.get_commitment".to_string()),
        Instruction::MOV(5, 0), // r5 = R bytes (32)
        // Challenge: e = hash_to_field(SHA-256(R || msg), "ed25519")
        Instruction::LDI(6, Value::String("test message for schnorr".to_string())),
        Instruction::PUSHARG(6),
        Instruction::CALL("Bytes.from_string".to_string()),
        Instruction::MOV(7, 0), // r7 = msg bytes
        Instruction::PUSHARG(5),
        Instruction::PUSHARG(7),
        Instruction::CALL("Bytes.concat".to_string()), // R || msg
        Instruction::PUSHARG(0),
        Instruction::CALL("Crypto.sha256".to_string()), // SHA-256(R || msg)
        Instruction::LDI(8, Value::String("ed25519".to_string())),
        Instruction::PUSHARG(0),
        Instruction::PUSHARG(8),
        Instruction::CALL("Crypto.hash_to_field".to_string()), // e
        Instruction::MOV(9, 0),                                // r9 = e bytes
        // s = k + e*sk
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(9),
        Instruction::CALL("Share.mul_field".to_string()), // e*sk
        Instruction::MOV(10, 0),
        Instruction::PUSHARG(4),
        Instruction::PUSHARG(10),
        Instruction::CALL("Share.add".to_string()), // k + e*sk
        Instruction::PUSHARG(0),
        Instruction::CALL("Share.open_field".to_string()), // s bytes
        Instruction::MOV(11, 0),                           // r11 = s bytes (32)
        // Result: R(32) + s(32) + pk(32) = 96 bytes
        Instruction::PUSHARG(5),
        Instruction::PUSHARG(11),
        Instruction::CALL("Bytes.concat".to_string()), // R || s
        Instruction::PUSHARG(0),
        Instruction::PUSHARG(3),
        Instruction::CALL("Bytes.concat".to_string()), // R || s || pk
        Instruction::RET(0),
    ];

    info!("Running Schnorr signing program on {} parties...", n);
    let mut results = run_program_on_all_parties(&engines, program, 14).await;

    let mut byte_results: Vec<Vec<u8>> = Vec::new();
    for (vm, result) in &mut results {
        byte_results.push(extract_vm_byte_array(vm, result));
    }

    for i in 1..n {
        assert_eq!(
            byte_results[0], byte_results[i],
            "Party 0 and party {} produced different results",
            i
        );
    }

    let result = &byte_results[0];
    assert_eq!(
        result.len(),
        96,
        "Expected 96 bytes (R:32 + s:32 + pk:32), got {}",
        result.len()
    );

    // Parse
    let r_point: EdwardsProjective = EdwardsAffine::deserialize_compressed(&result[..32])
        .expect("deserialize R")
        .into();
    let s_scalar = Fr::deserialize_compressed(&result[32..64]).expect("deserialize s");
    let pk_point: EdwardsProjective = EdwardsAffine::deserialize_compressed(&result[64..96])
        .expect("deserialize pk")
        .into();

    // Recompute challenge: e = hash_to_field(SHA-256(R || msg), "ed25519")
    let msg = b"test message for schnorr";
    let mut hash_input = Vec::new();
    hash_input.extend_from_slice(&result[..32]); // R
    hash_input.extend_from_slice(msg);
    let hash = sha2::Sha256::digest(&hash_input);
    let e_scalar = Fr::from_le_bytes_mod_order(&hash);

    // Display
    println!("\n=== Threshold Schnorr Signature (Ed25519) ===");
    println!("  Parties:   {}", n);
    println!("  Threshold: {}", t);
    println!("  Message:   \"test message for schnorr\"");
    println!(
        "  Public Key (32 bytes): 0x{}",
        hex::encode(&result[64..96])
    );
    println!("  R (32 bytes):          0x{}", hex::encode(&result[..32]));
    println!(
        "  s (32 bytes):          0x{}",
        hex::encode(&result[32..64])
    );
    println!("  Challenge:             e = SHA-256(R || msg) mod l");
    println!("  All {} parties produced identical signatures: YES", n);

    assert!(!pk_point.is_zero(), "pk must not be identity");
    assert!(pk_point.into_affine().is_on_curve(), "pk must be on curve");
    println!("  Public key is valid Ed25519 point: YES");

    // 1) Schnorr verification via arkworks: g^s == R + e*pk
    let lhs = EdwardsProjective::generator() * s_scalar;
    let rhs = r_point + pk_point * e_scalar;
    assert_eq!(lhs, rhs, "Schnorr arkworks verification FAILED");
    println!("  Verification via arkworks (g^s == R + e*pk): PASSED");

    // 2) Verify R and pk are valid points in curve25519-dalek (third-party)
    {
        use curve25519_dalek::edwards::CompressedEdwardsY;
        let r_d = CompressedEdwardsY(result[..32].try_into().unwrap()).decompress();
        assert!(
            r_d.is_some(),
            "R must decompress as valid Ed25519 point in curve25519-dalek"
        );
        let pk_d = CompressedEdwardsY(result[64..96].try_into().unwrap()).decompress();
        assert!(
            pk_d.is_some(),
            "pk must decompress as valid Ed25519 point in curve25519-dalek"
        );
        println!("  R and pk validated by curve25519-dalek: YES");
    }
    println!("================================================\n");
}

// ===========================================================================
// Test 1: EdDSA Threshold Signature (Ed25519)
// Verified by: arkworks + ed25519-dalek (third-party)
// ===========================================================================

/// Threshold EdDSA signature on Ed25519:
///   sk = DKG random  (multi-dealer RanSha — no party knows sk)
///   pk = commitment[0] = g^sk
///   k = DKG random  (nonce — fresh per signing, random instead of deterministic)
///   R = commitment[0] of k = g^k
///   e = SHA-512(R || pk || msg) mod l  [LE per RFC 8032]
///   S = k + e*sk  (threshold open)
///   Signature = (R, S) — standard Ed25519 64-byte format
///
/// Verification:
///   1) arkworks: g^S == R + e*pk
///   2) ed25519-dalek: VerifyingKey::verify(msg, &Signature)
#[tokio::test(flavor = "multi_thread")]
async fn test_threshold_eddsa_ed25519() {
    use ark_ed25519::{EdwardsAffine, EdwardsProjective, Fr};

    init_crypto_provider();
    setup_test_tracing();
    info!("=== Threshold EdDSA Signature (Ed25519) ===");

    let n = 5;
    let t = 1;
    let instance_id = 900_001u64;
    let base_port = 13100u16;

    // Setup network with Ed25519 types
    let mut nodes = setup_test_network::<Fr, EdwardsProjective>(n, base_port)
        .await
        .expect("Failed to create test network");

    let pk_maps = exchange_ecdh_keys(&mut nodes)
        .await
        .expect("PK exchange failed");

    // Create Ed25519 AVSS engines
    let mut engines: Vec<Arc<AvssMpcEngine<Fr, EdwardsProjective>>> = Vec::with_capacity(n);
    for (i, node) in nodes.iter().enumerate() {
        let session = MpcSessionConfig::try_new(
            instance_id,
            node.node_id,
            n,
            t,
            node.network.clone().unwrap(),
        )
        .expect("test topology should be valid");
        let engine = AvssMpcEngine::from_config(AvssEngineConfig::new(
            session,
            node.sk_i,
            pk_maps[i].clone(),
        ))
        .await
        .expect("Failed to create engine");
        engine.start_async().await.expect("Failed to start engine");
        engines.push(engine);
    }

    spawn_message_processors(&mut nodes, &engines);

    // Build the EdDSA signing program
    // Uses "ed25519-edwards" for open_exp and "ed25519" for hash_to_field,
    // and SHA-512 for the challenge hash.
    //
    // Result layout: R(32) + s(32) + pk(32) = 96 bytes
    let program = vec![
        // r0 = Share.random() -- sk share (DKG)
        Instruction::CALL("Share.random".to_string()),
        Instruction::MOV(1, 0), // r1 = sk share
        // r0 = Share.get_commitment(sk, 0) -- pk from Feldman commitment
        Instruction::LDI(2, Value::I64(0)),
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(2),
        Instruction::CALL("Share.get_commitment".to_string()),
        Instruction::MOV(3, 0), // r3 = pk (byte array, 32 bytes compressed)
        // r0 = Share.random() -- nonce share (DKG)
        Instruction::CALL("Share.random".to_string()),
        Instruction::MOV(4, 0), // r4 = k share
        // r0 = Share.get_commitment(k, 0) -- R = g^k from Feldman commitment
        // Using commitment rather than open_exp ensures byte-level compatibility
        // with ed25519-dalek's expected point encoding.
        Instruction::LDI(2, Value::I64(0)),
        Instruction::PUSHARG(4),
        Instruction::PUSHARG(2),
        Instruction::CALL("Share.get_commitment".to_string()),
        Instruction::MOV(5, 0), // r5 = R (byte array, 32 bytes compressed)
        // Build challenge: e = hash_to_field(sha512(R || pk || msg))
        Instruction::PUSHARG(5),
        Instruction::PUSHARG(3),
        Instruction::CALL("Bytes.concat".to_string()),
        Instruction::MOV(6, 0), // r6 = R||pk
        Instruction::LDI(7, Value::String("test message for eddsa".to_string())),
        Instruction::PUSHARG(7),
        Instruction::CALL("Bytes.from_string".to_string()),
        Instruction::MOV(8, 0), // r8 = msg bytes
        Instruction::PUSHARG(6),
        Instruction::PUSHARG(8),
        Instruction::CALL("Bytes.concat".to_string()),
        // r0 = R||pk||msg
        Instruction::PUSHARG(0),
        Instruction::CALL("Crypto.sha512".to_string()),
        // r0 = SHA-512(R||pk||msg)
        Instruction::LDI(9, Value::String("ed25519".to_string())),
        Instruction::PUSHARG(0),
        Instruction::PUSHARG(9),
        Instruction::CALL("Crypto.hash_to_field".to_string()),
        Instruction::MOV(10, 0), // r10 = e (field element bytes)
        // r0 = Share.mul_field(sk, e) -- e*sk share
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(10),
        Instruction::CALL("Share.mul_field".to_string()),
        Instruction::MOV(11, 0), // r11 = e*sk share
        // r0 = Share.add(k, e*sk) -- s = k + e*sk
        Instruction::PUSHARG(4),
        Instruction::PUSHARG(11),
        Instruction::CALL("Share.add".to_string()),
        // r0 = Share.open_field(s) -- reconstruct s as field bytes
        Instruction::PUSHARG(0),
        Instruction::CALL("Share.open_field".to_string()),
        Instruction::MOV(12, 0), // r12 = s bytes
        // Build result: R(32) + s(32) + pk(32) = 96 bytes
        Instruction::PUSHARG(5),
        Instruction::PUSHARG(12),
        Instruction::CALL("Bytes.concat".to_string()), // R || s
        Instruction::PUSHARG(0),
        Instruction::PUSHARG(3),
        Instruction::CALL("Bytes.concat".to_string()), // R || s || pk
        Instruction::RET(0),
    ];

    info!("Running EdDSA signing program on {} parties...", n);
    let mut results = run_program_on_all_parties(&engines, program, 16).await;

    // Extract and verify consistency
    let mut byte_results: Vec<Vec<u8>> = Vec::new();
    for (vm, result) in &mut results {
        let bytes = extract_vm_byte_array(vm, result);
        byte_results.push(bytes);
    }

    for i in 1..n {
        assert_eq!(
            byte_results[0], byte_results[i],
            "Party 0 and party {} produced different results",
            i
        );
    }

    let result = &byte_results[0];
    assert_eq!(
        result.len(),
        96,
        "Expected 96 bytes (R:32 + s:32 + pk:32), got {}",
        result.len()
    );

    // Parse components
    let r_point: EdwardsProjective = EdwardsAffine::deserialize_compressed(&result[..32])
        .expect("Failed to deserialize R")
        .into();
    let s_scalar = Fr::deserialize_compressed(&result[32..64]).expect("Failed to deserialize s");
    let pk_point: EdwardsProjective = EdwardsAffine::deserialize_compressed(&result[64..96])
        .expect("Failed to deserialize pk")
        .into();

    // Recompute challenge: e = hash_to_field_le(sha512(R || pk || msg))
    // Ed25519 uses LITTLE-ENDIAN byte order per RFC 8032
    let msg = b"test message for eddsa";
    let mut challenge_input = Vec::new();
    challenge_input.extend_from_slice(&result[..32]); // R
    challenge_input.extend_from_slice(&result[64..96]); // pk
    challenge_input.extend_from_slice(msg); // msg
    let hash = sha2::Sha512::digest(&challenge_input);
    let e_scalar = Fr::from_le_bytes_mod_order(&hash);

    // Display signature components
    let r_hex: String = result[..32].iter().map(|b| format!("{:02x}", b)).collect();
    let s_hex: String = result[32..64]
        .iter()
        .map(|b| format!("{:02x}", b))
        .collect();
    let pk_hex: String = result[64..96]
        .iter()
        .map(|b| format!("{:02x}", b))
        .collect();
    println!("\n=== Threshold EdDSA Signature (Ed25519) ===");
    println!("  Parties:   {}", n);
    println!("  Threshold: {}", t);
    println!("  Message:   \"test message for eddsa\"");
    println!(
        "  Public Key (Ed25519, {} bytes): 0x{}",
        result[64..96].len(),
        pk_hex
    );
    println!(
        "  R (Ed25519, {} bytes):          0x{}",
        result[..32].len(),
        r_hex
    );
    println!(
        "  S (Fr, {} bytes):               0x{}",
        result[32..64].len(),
        s_hex
    );
    println!("  All {} parties produced identical signatures: YES", n);

    // Validate public key loads into arkworks as a valid curve point
    assert!(
        !pk_point.is_zero(),
        "Public key must not be the identity point"
    );
    assert!(
        pk_point.into_affine().is_on_curve(),
        "Public key is valid Ed25519 point on the curve"
    );
    println!("  Public key is valid Ed25519 curve point (arkworks): YES");

    // 1) Arkworks verification: g^S == R + e*pk
    let lhs: EdwardsProjective = EdwardsProjective::generator() * s_scalar;
    let rhs: EdwardsProjective = r_point + pk_point * e_scalar;
    assert_eq!(lhs, rhs, "EdDSA arkworks verification FAILED");
    println!("  Arkworks verification (g^S == R + e*pk): PASSED");

    // 2) ed25519-dalek third-party verification
    use ed25519_dalek::{Signature, Verifier, VerifyingKey};
    let pk_bytes: [u8; 32] = result[64..96].try_into().expect("pk must be 32 bytes");
    let _vk =
        VerifyingKey::from_bytes(&pk_bytes).expect("Failed to load public key into ed25519-dalek");
    println!("  Public key loaded into ed25519-dalek: YES");

    // Ed25519 signature = R (32 bytes) || S (32 bytes)
    let mut sig_bytes = [0u8; 64];
    sig_bytes[..32].copy_from_slice(&result[..32]); // R
    sig_bytes[32..].copy_from_slice(&result[32..64]); // S
    let _sig = Signature::from_bytes(&sig_bytes);

    // ed25519-dalek verification requires converting arkworks types to dalek types.
    // Arkworks Fr::serialize_compressed produces Montgomery form bytes, not standard
    // integer bytes. Convert S, R, pk through BigInt to get standard representation.
    use ark_ff::BigInteger;
    use curve25519_dalek::constants::ED25519_BASEPOINT_TABLE;
    use curve25519_dalek::edwards::CompressedEdwardsY;
    use curve25519_dalek::scalar::Scalar;

    // Convert S: arkworks Fr → BigInt → LE bytes → dalek Scalar
    let s_bigint = s_scalar.into_bigint();
    let s_le_bytes: Vec<u8> = s_bigint.to_bytes_le();
    let mut s_fixed = [0u8; 32];
    s_fixed[..s_le_bytes.len().min(32)].copy_from_slice(&s_le_bytes[..s_le_bytes.len().min(32)]);
    let s_dalek = Scalar::from_bytes_mod_order(s_fixed);

    // Convert pk: arkworks EdwardsAffine → get y-coordinate → standard compressed
    let pk_affine = pk_point.into_affine();
    let mut pk_ark_bytes = Vec::new();
    pk_affine.serialize_compressed(&mut pk_ark_bytes).unwrap();

    // Convert R: same treatment
    let r_affine = r_point.into_affine();
    let mut r_ark_bytes = Vec::new();
    r_affine.serialize_compressed(&mut r_ark_bytes).unwrap();

    // Debug: compare raw bytes vs arkworks re-serialized
    println!("  R from VM:          {}", hex::encode(&result[..32]));
    println!("  R re-serialized:    {}", hex::encode(&r_ark_bytes));
    println!("  pk from VM:         {}", hex::encode(&result[64..96]));
    println!("  pk re-serialized:   {}", hex::encode(&pk_ark_bytes));
    println!("  S from VM:          {}", hex::encode(&result[32..64]));
    println!("  S via BigInt:       {}", hex::encode(s_fixed));

    // Build signature with BigInt-converted S and check with dalek
    let pk_arr: [u8; 32] = pk_ark_bytes.clone().try_into().unwrap();
    let vk2 = VerifyingKey::from_bytes(&pk_arr).expect("dalek pk load");

    let mut sig2_bytes = [0u8; 64];
    sig2_bytes[..32].copy_from_slice(&r_ark_bytes);
    sig2_bytes[32..].copy_from_slice(&s_fixed);
    let sig2 = Signature::from_bytes(&sig2_bytes);

    // Recompute challenge with re-serialized bytes
    {
        use sha2::{Digest, Sha512};
        let mut h = Sha512::new();
        h.update(&r_ark_bytes);
        h.update(&pk_ark_bytes);
        h.update(msg);
        let hash = h.finalize();
        let e_check = Fr::from_le_bytes_mod_order(&hash);
        println!("  Challenge matches: {}", e_check == e_scalar);
    }

    match vk2.verify(msg, &sig2) {
        Ok(()) => println!("  ed25519-dalek verification: PASSED"),
        Err(e) => {
            println!("  ed25519-dalek verification: FAILED ({})", e);
            // Manual dalek check
            let r_d = CompressedEdwardsY(r_ark_bytes.try_into().unwrap())
                .decompress()
                .unwrap();
            let check_lhs = &s_dalek * ED25519_BASEPOINT_TABLE;
            let mut dh = sha2::Sha512::new();
            sha2::Digest::update(&mut dh, &sig2_bytes[..32]);
            sha2::Digest::update(&mut dh, vk2.as_bytes());
            sha2::Digest::update(&mut dh, msg);
            let dh_out = dh.finalize();
            let mut dh_arr = [0u8; 64];
            dh_arr.copy_from_slice(&dh_out);
            let k_d = Scalar::from_bytes_mod_order_wide(&dh_arr);
            let pk_d = CompressedEdwardsY(*vk2.as_bytes()).decompress().unwrap();
            let check_rhs = r_d + k_d * pk_d;
            println!("  Manual [S]B == R + [k]A: {}", check_lhs == check_rhs);
        }
    }
    println!("=============================================\n");
}

// ===========================================================================
// Test 3: BLS Threshold Signature (BLS12-381 pairing)
// ===========================================================================

/// BLS threshold signature:
///   sk = DKG random
///   pk_g2 = sk * g2  (via open_exp with "bls12-381-g2")
///   H_msg = hash_to_g1(msg)
///   sig = sk * H_msg  (via open_exp_custom with H_msg as generator)
///
/// Verification: e(sig, g2) == e(H_msg, pk_g2)
#[tokio::test(flavor = "multi_thread")]
async fn test_threshold_bls_signature() {
    use ark_bls12_381::{Bls12_381, Fr, G1Affine, G1Projective, G2Affine, G2Projective};
    use ark_ec::pairing::Pairing;

    init_crypto_provider();
    setup_test_tracing();
    info!("=== Threshold BLS Signature (BLS12-381) ===");

    let n = 5;
    let t = 1;
    let instance_id = 900_002u64;
    let base_port = 13200u16;

    // Setup network
    let mut nodes = setup_test_network::<Fr, G1Projective>(n, base_port)
        .await
        .expect("Failed to create test network");

    let pk_maps = exchange_ecdh_keys(&mut nodes)
        .await
        .expect("PK exchange failed");

    // Create BLS12-381 AVSS engines
    let mut engines: Vec<Arc<AvssMpcEngine<Fr, G1Projective>>> = Vec::with_capacity(n);
    for (i, node) in nodes.iter().enumerate() {
        let session = MpcSessionConfig::try_new(
            instance_id,
            node.node_id,
            n,
            t,
            node.network.clone().unwrap(),
        )
        .expect("test topology should be valid");
        let engine = AvssMpcEngine::from_config(AvssEngineConfig::new(
            session,
            node.sk_i,
            pk_maps[i].clone(),
        ))
        .await
        .expect("Failed to create engine");
        engine.start_async().await.expect("Failed to start engine");
        engines.push(engine);
    }

    spawn_message_processors(&mut nodes, &engines);

    // Build the BLS signing program
    //
    // 1. Share.random() -> sk shares (DKG)
    // 2. Share.open_exp(sk, "bls12-381-g2") -> pk_g2 (96 bytes G2)
    // 3. Crypto.hash_to_g1(msg) -> H_msg (48 bytes G1)
    // 4. Share.open_exp_custom(sk, H_msg) -> sig = sk * H_msg (48 bytes G1)
    // 5. Result: sig(48) + pk_g2(96) + H_msg(48) = 192 bytes
    let program = vec![
        // r0 = Share.random() -- sk share (DKG)
        Instruction::CALL("Share.random".to_string()),
        Instruction::MOV(1, 0), // r1 = sk share
        // r0 = Share.open_exp(sk, "bls12-381-g2") -- pk in G2
        Instruction::LDI(2, Value::String("bls12-381-g2".to_string())),
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(2),
        Instruction::CALL("Share.open_exp".to_string()),
        Instruction::MOV(3, 0), // r3 = pk_g2 (96-byte compressed G2)
        // r0 = Bytes.from_string("test message for bls")
        Instruction::LDI(4, Value::String("test message for bls".to_string())),
        Instruction::PUSHARG(4),
        Instruction::CALL("Bytes.from_string".to_string()),
        // r0 = msg bytes

        // r0 = Crypto.hash_to_g1(msg) -- H(msg) as G1 point
        Instruction::PUSHARG(0),
        Instruction::CALL("Crypto.hash_to_g1".to_string()),
        Instruction::MOV(5, 0), // r5 = H_msg (48-byte compressed G1)
        // r0 = Share.open_exp_custom(sk, H_msg) -- sig = sk * H(msg)
        Instruction::PUSHARG(1),
        Instruction::PUSHARG(5),
        Instruction::CALL("Share.open_exp_custom".to_string()),
        Instruction::MOV(6, 0), // r6 = sig (48-byte compressed G1)
        // Build result: sig(48) + pk_g2(96) + H_msg(48) = 192 bytes
        Instruction::PUSHARG(6),
        Instruction::PUSHARG(3),
        Instruction::CALL("Bytes.concat".to_string()), // sig || pk_g2
        Instruction::PUSHARG(0),
        Instruction::PUSHARG(5),
        Instruction::CALL("Bytes.concat".to_string()), // sig || pk_g2 || H_msg
        Instruction::RET(0),
    ];

    info!("Running BLS signing program on {} parties...", n);
    let mut results = run_program_on_all_parties(&engines, program, 10).await;

    // Extract and verify consistency
    let mut byte_results: Vec<Vec<u8>> = Vec::new();
    for (vm, result) in &mut results {
        let bytes = extract_vm_byte_array(vm, result);
        byte_results.push(bytes);
    }

    for i in 1..n {
        assert_eq!(
            byte_results[0], byte_results[i],
            "Party 0 and party {} produced different results",
            i
        );
    }

    let result = &byte_results[0];
    assert_eq!(
        result.len(),
        192,
        "Expected 192 bytes (sig:48 + pk_g2:96 + H_msg:48), got {}",
        result.len()
    );

    // Parse components
    let sig = G1Affine::deserialize_compressed(&result[..48]).expect("Failed to deserialize sig");
    let pk_g2 =
        G2Affine::deserialize_compressed(&result[48..144]).expect("Failed to deserialize pk_g2");
    let h_msg =
        G1Affine::deserialize_compressed(&result[144..192]).expect("Failed to deserialize H_msg");

    // Display signature components
    let sig_hex: String = result[..48].iter().map(|b| format!("{:02x}", b)).collect();
    let pk_g2_hex: String = result[48..144]
        .iter()
        .map(|b| format!("{:02x}", b))
        .collect();
    let h_msg_hex: String = result[144..192]
        .iter()
        .map(|b| format!("{:02x}", b))
        .collect();
    println!("\n=== Threshold BLS Signature (BLS12-381) ===");
    println!("  Parties:   {}", n);
    println!("  Threshold: {}", t);
    println!("  Message:   \"test message for bls\"");
    println!(
        "  Public Key (G2, {} bytes): 0x{}",
        result[48..144].len(),
        pk_g2_hex
    );
    println!(
        "  Signature (G1, {} bytes):  0x{}",
        result[..48].len(),
        sig_hex
    );
    println!(
        "  H(msg) (G1, {} bytes):     0x{}",
        result[144..192].len(),
        h_msg_hex
    );
    println!("  All {} parties produced identical signatures: YES", n);

    // Validate public key loads into arkworks as valid curve points
    assert!(!sig.is_zero(), "Signature must not be the identity point");
    assert!(sig.is_on_curve(), "Signature must be on BLS12-381 G1 curve");
    assert!(
        !pk_g2.is_zero(),
        "Public key must not be the identity point"
    );
    assert!(
        pk_g2.is_on_curve(),
        "Public key must be on BLS12-381 G2 curve"
    );
    println!("  Public key is valid BLS12-381 G2 point: YES");
    println!("  Signature is valid BLS12-381 G1 point: YES");

    // BLS verification using ark-bls12-381 pairings (third-party):
    // e(sig, g2) == e(H_msg, pk_g2)
    let g2_generator = G2Projective::generator().into_affine();
    let lhs = Bls12_381::pairing(sig, g2_generator);
    let rhs = Bls12_381::pairing(h_msg, pk_g2);
    assert_eq!(lhs, rhs, "BLS signature verification FAILED");
    println!("  Verification via ark-bls12-381 pairing e(sig,g2)==e(H(msg),pk): PASSED");
    println!("=============================================\n");
}