aingle_minimal 0.6.2

Ultra-light AIngle node for IoT devices (<1MB RAM)
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
// Copyright 2019-2026 Apilium Technologies OÜ. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR Commercial

//! CoAP Transport for IoT nodes
//!
//! Implements the Constrained Application Protocol (RFC 7252) for
//! lightweight IoT communication over UDP.
//!
//! # Features
//! - Confirmable (CON) and Non-confirmable (NON) messages
//! - Block-wise transfer for large payloads (RFC 7959)
//! - Multicast discovery
//! - Resource-based routing
//!
//! # Resources
//! - `/.well-known/core` - CoRE Link Format discovery
//! - `/gossip` - Gossip protocol messages
//! - `/record` - Record retrieval
//! - `/announce` - New record announcements
//! - `/ping` - Liveness checks

use coap_lite::{CoapOption, MessageClass, MessageType, Packet, RequestType, ResponseType};

use crate::error::{Error, Result};
use crate::network::Message;
use async_io::Async;
use std::collections::HashMap;
use std::net::{SocketAddr, UdpSocket};
use std::time::{Duration, Instant};

/// Maximum CoAP message size (for non-block transfers)
pub const COAP_MAX_MESSAGE_SIZE: usize = 1024;

/// Default CoAP port
pub const COAP_DEFAULT_PORT: u16 = 5683;

/// CoAP multicast address for discovery (IPv4)
pub const COAP_MULTICAST_IPV4: &str = "224.0.1.187";

/// CoAP multicast address for discovery (IPv6)
#[allow(dead_code)]
pub const COAP_MULTICAST_IPV6: &str = "ff02::fd";

/// Block size for block-wise transfers (256 bytes = SZX 2)
pub const BLOCK_SIZE: usize = 256;

/// Maximum retransmissions for CON messages
pub const MAX_RETRANSMIT: u8 = 4;

/// ACK timeout in milliseconds
pub const ACK_TIMEOUT_MS: u64 = 2000;

/// CoAP message token for tracking requests
pub type Token = Vec<u8>;

/// Pending request tracking
#[derive(Debug)]
struct PendingRequest {
    /// Original request packet
    packet: Packet,
    /// Destination address
    addr: SocketAddr,
    /// Time sent
    sent_at: Instant,
    /// Retransmission count
    retransmits: u8,
}

/// Block transfer state
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct BlockState {
    /// Full data being transferred
    data: Vec<u8>,
    /// Current block number
    block_num: u32,
    /// More blocks flag
    more: bool,
}

/// CoAP Server for handling incoming requests
pub struct CoapServer {
    /// UDP socket (async)
    socket: Option<Async<UdpSocket>>,
    /// Bind address
    bind_addr: String,
    /// Port
    port: u16,
    /// Node ID for identification
    #[allow(dead_code)]
    node_id: String,
    /// Message ID counter
    message_id: u16,
    /// Pending requests awaiting ACK
    pending_requests: HashMap<u16, PendingRequest>,
    /// Block transfer states (for future block-wise receive)
    #[allow(dead_code)]
    block_states: HashMap<Token, BlockState>,
    /// Running flag
    running: bool,
}

impl CoapServer {
    /// Create a new CoAP server
    pub fn new(bind_addr: String, port: u16, node_id: String) -> Self {
        Self {
            socket: None,
            bind_addr,
            port,
            node_id,
            message_id: rand::random(),
            pending_requests: HashMap::new(),
            block_states: HashMap::new(),
            running: false,
        }
    }

    /// Start the CoAP server
    pub async fn start(&mut self) -> Result<()> {
        let addr = format!("{}:{}", self.bind_addr, self.port);
        let socket = UdpSocket::bind(&addr)
            .map_err(|e| Error::network(format!("Failed to bind CoAP socket: {}", e)))?;

        // Set non-blocking for async
        socket
            .set_nonblocking(true)
            .map_err(|e| Error::network(format!("Failed to set non-blocking: {}", e)))?;

        let async_socket = Async::new(socket)
            .map_err(|e| Error::network(format!("Failed to create async socket: {}", e)))?;

        self.socket = Some(async_socket);
        self.running = true;

        log::info!("CoAP server started on {}:{}", self.bind_addr, self.port);
        Ok(())
    }

    /// Stop the CoAP server
    pub async fn stop(&mut self) -> Result<()> {
        self.running = false;
        self.socket = None;
        log::info!("CoAP server stopped");
        Ok(())
    }

    /// Check if server is running
    pub fn is_running(&self) -> bool {
        self.running && self.socket.is_some()
    }

    /// Receive and process a single message
    pub async fn recv(&self) -> Result<Option<(SocketAddr, Message)>> {
        let socket = self
            .socket
            .as_ref()
            .ok_or_else(|| Error::network("Socket not initialized".to_string()))?;

        let mut buf = [0u8; 2048];

        match socket.recv_from(&mut buf).await {
            Ok((len, addr)) => {
                let packet = Packet::from_bytes(&buf[..len])
                    .map_err(|e| Error::network(format!("Failed to parse CoAP packet: {:?}", e)))?;

                // Process the packet and convert to Message
                if let Some(msg) = self.process_packet(&packet, &addr)? {
                    return Ok(Some((addr, msg)));
                }
                Ok(None)
            }
            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => Ok(None),
            Err(e) => Err(Error::network(format!("Receive error: {}", e))),
        }
    }

    /// Process incoming CoAP packet
    fn process_packet(&self, packet: &Packet, addr: &SocketAddr) -> Result<Option<Message>> {
        let path = Self::extract_path(packet);

        log::debug!(
            "CoAP request from {}: {} {:?}",
            addr,
            path,
            packet.header.code
        );

        match path.as_str() {
            "/.well-known/core" => {
                // Discovery - return available resources
                Ok(None) // Handled separately
            }
            "/ping" => {
                // Liveness check
                if !packet.payload.is_empty() {
                    let node_id = String::from_utf8_lossy(&packet.payload).to_string();
                    Ok(Some(Message::Ping { node_id }))
                } else {
                    Ok(Some(Message::Ping {
                        node_id: "unknown".to_string(),
                    }))
                }
            }
            "/gossip" => {
                // Gossip request
                if !packet.payload.is_empty() {
                    let msg: Message = serde_json::from_slice(&packet.payload)
                        .map_err(|e| Error::Serialization(e.to_string()))?;
                    Ok(Some(msg))
                } else {
                    Ok(None)
                }
            }
            "/record" => {
                // Record request
                if !packet.payload.is_empty() {
                    let msg: Message = serde_json::from_slice(&packet.payload)
                        .map_err(|e| Error::Serialization(e.to_string()))?;
                    Ok(Some(msg))
                } else {
                    Ok(None)
                }
            }
            "/announce" => {
                // New record announcement
                if !packet.payload.is_empty() {
                    let msg: Message = serde_json::from_slice(&packet.payload)
                        .map_err(|e| Error::Serialization(e.to_string()))?;
                    Ok(Some(msg))
                } else {
                    Ok(None)
                }
            }
            // RPC endpoint: /rpc/{method}
            p if p.starts_with("/rpc/") => {
                if !packet.payload.is_empty() {
                    let msg: Message = serde_json::from_slice(&packet.payload)
                        .map_err(|e| Error::Serialization(e.to_string()))?;
                    Ok(Some(msg))
                } else {
                    Ok(None)
                }
            }
            _ => {
                log::warn!("Unknown CoAP path: {}", path);
                Ok(None)
            }
        }
    }

    /// Extract URI path from CoAP packet
    fn extract_path(packet: &Packet) -> String {
        let mut path = String::from("/");

        // Get UriPath options and build path
        if let Some(uri_paths) = packet.get_option(CoapOption::UriPath) {
            for segment in uri_paths {
                if path.len() > 1 {
                    path.push('/');
                }
                path.push_str(&String::from_utf8_lossy(segment));
            }
        }

        if path == "/" {
            path = "/.well-known/core".to_string();
        }
        path
    }

    /// Send a CoAP message
    pub async fn send(
        &mut self,
        addr: &SocketAddr,
        message: &Message,
        confirmable: bool,
    ) -> Result<()> {
        let payload =
            serde_json::to_vec(message).map_err(|e| Error::Serialization(e.to_string()))?;

        // Determine the path based on message type
        let path = Self::message_to_path(message);

        // Check if we need block-wise transfer
        if payload.len() > COAP_MAX_MESSAGE_SIZE {
            return self.send_blocks(addr, &path, &payload, confirmable).await;
        }

        let packet = self.create_request_packet(&path, &payload, confirmable);
        let bytes = packet
            .to_bytes()
            .map_err(|e| Error::network(format!("Failed to serialize packet: {:?}", e)))?;

        {
            let socket = self
                .socket
                .as_ref()
                .ok_or_else(|| Error::network("Socket not initialized".to_string()))?;
            socket
                .send_to(&bytes, *addr)
                .await
                .map_err(|e| Error::network(format!("Send error: {}", e)))?;
        }

        if confirmable {
            // Track for retransmission
            self.pending_requests.insert(
                packet.header.message_id,
                PendingRequest {
                    packet,
                    addr: *addr,
                    sent_at: Instant::now(),
                    retransmits: 0,
                },
            );
        }

        log::debug!("CoAP sent to {}: {} ({} bytes)", addr, path, bytes.len());
        Ok(())
    }

    /// Send message using block-wise transfer
    async fn send_blocks(
        &mut self,
        addr: &SocketAddr,
        path: &str,
        data: &[u8],
        confirmable: bool,
    ) -> Result<()> {
        let total_blocks = data.len().div_ceil(BLOCK_SIZE);

        for block_num in 0..total_blocks {
            let start = block_num * BLOCK_SIZE;
            let end = std::cmp::min(start + BLOCK_SIZE, data.len());
            let block_data = &data[start..end];
            let more = block_num < total_blocks - 1;

            let mut packet = self.create_request_packet(path, block_data, confirmable);

            // Add Block1 option (SZX=2 for 256 bytes)
            // Block1 format: NUM (4+ bits) | M (1 bit) | SZX (3 bits)
            let block1_value = ((block_num as u32) << 4) | (if more { 0x08 } else { 0x00 }) | 0x02;
            let block1_bytes = if block1_value <= 0xFF {
                vec![block1_value as u8]
            } else if block1_value <= 0xFFFF {
                block1_value.to_be_bytes()[2..].to_vec()
            } else {
                block1_value.to_be_bytes().to_vec()
            };
            packet.add_option(CoapOption::Block1, block1_bytes);

            let bytes = packet
                .to_bytes()
                .map_err(|e| Error::network(format!("Failed to serialize block: {:?}", e)))?;

            {
                let socket = self
                    .socket
                    .as_ref()
                    .ok_or_else(|| Error::network("Socket not initialized".to_string()))?;
                socket
                    .send_to(&bytes, *addr)
                    .await
                    .map_err(|e| Error::network(format!("Send block error: {}", e)))?;
            }

            log::trace!("Sent block {}/{} to {}", block_num + 1, total_blocks, addr);
        }

        Ok(())
    }

    /// Create a CoAP request packet
    fn create_request_packet(&mut self, path: &str, payload: &[u8], confirmable: bool) -> Packet {
        let mut packet = Packet::new();

        packet.header.set_version(1);
        packet.header.set_type(if confirmable {
            MessageType::Confirmable
        } else {
            MessageType::NonConfirmable
        });
        packet.header.code = MessageClass::Request(RequestType::Post);
        packet.header.message_id = self.next_message_id();
        packet.set_token(self.generate_token());

        // Add URI path options
        for segment in path.trim_start_matches('/').split('/') {
            if !segment.is_empty() {
                packet.add_option(CoapOption::UriPath, segment.as_bytes().to_vec());
            }
        }

        // Add content format (application/json = 50)
        packet.add_option(CoapOption::ContentFormat, vec![50]);

        packet.payload = payload.to_vec();

        packet
    }

    /// Send a CoAP response
    pub async fn send_response(
        &self,
        addr: &SocketAddr,
        request: &Packet,
        response_code: ResponseType,
        payload: Option<&[u8]>,
    ) -> Result<()> {
        let socket = self
            .socket
            .as_ref()
            .ok_or_else(|| Error::network("Socket not initialized".to_string()))?;

        let mut response = Packet::new();
        response.header.set_version(1);
        response.header.set_type(MessageType::Acknowledgement);
        response.header.code = MessageClass::Response(response_code);
        response.header.message_id = request.header.message_id;
        response.set_token(request.get_token().to_vec());

        if let Some(data) = payload {
            response.add_option(CoapOption::ContentFormat, vec![50]);
            response.payload = data.to_vec();
        }

        let bytes = response
            .to_bytes()
            .map_err(|e| Error::network(format!("Failed to serialize response: {:?}", e)))?;

        socket
            .send_to(&bytes, *addr)
            .await
            .map_err(|e| Error::network(format!("Send response error: {}", e)))?;

        Ok(())
    }

    /// Map message type to CoAP path
    fn message_to_path(message: &Message) -> String {
        match message {
            Message::Ping { .. } => "/ping".to_string(),
            Message::Pong { .. } => "/ping".to_string(),
            Message::GossipRequest { .. } => "/gossip".to_string(),
            Message::GossipResponse { .. } => "/gossip".to_string(),
            Message::NewRecord { .. } => "/announce".to_string(),
            Message::GetRecord { .. } => "/record".to_string(),
            Message::RecordData { .. } => "/record".to_string(),
            Message::RemoteCall { method, .. } => format!("/rpc/{}", method),
            Message::RemoteCallResponse { .. } => "/rpc/response".to_string(),
            Message::MeshRelay { .. } => "/mesh".to_string(),
        }
    }

    /// Get next message ID
    fn next_message_id(&mut self) -> u16 {
        self.message_id = self.message_id.wrapping_add(1);
        self.message_id
    }

    /// Generate a random token
    fn generate_token(&self) -> Vec<u8> {
        let token: [u8; 4] = rand::random();
        token.to_vec()
    }

    /// Handle retransmissions for pending CON messages
    pub async fn handle_retransmissions(&mut self) -> Result<()> {
        let now = Instant::now();
        let timeout = Duration::from_millis(ACK_TIMEOUT_MS);
        let mut to_remove = Vec::new();
        let mut to_retransmit = Vec::new();

        for (msg_id, pending) in &self.pending_requests {
            if now.duration_since(pending.sent_at) > timeout {
                if pending.retransmits >= MAX_RETRANSMIT {
                    to_remove.push(*msg_id);
                    log::warn!(
                        "CoAP message {} timed out after {} retransmits",
                        msg_id,
                        pending.retransmits
                    );
                } else {
                    to_retransmit.push(*msg_id);
                }
            }
        }

        // Remove timed out requests
        for msg_id in to_remove {
            self.pending_requests.remove(&msg_id);
        }

        // Retransmit
        for msg_id in to_retransmit {
            if let Some(pending) = self.pending_requests.get_mut(&msg_id) {
                let bytes = pending
                    .packet
                    .to_bytes()
                    .map_err(|e| Error::network(format!("Failed to serialize packet: {:?}", e)))?;

                let socket = self
                    .socket
                    .as_ref()
                    .ok_or_else(|| Error::network("Socket not initialized".to_string()))?;

                if let Err(e) = socket.send_to(&bytes, pending.addr).await {
                    log::warn!("Retransmit failed: {}", e);
                } else {
                    pending.retransmits += 1;
                    pending.sent_at = Instant::now();
                    log::debug!(
                        "Retransmitted CoAP message {} (attempt {})",
                        msg_id,
                        pending.retransmits
                    );
                }
            }
        }

        Ok(())
    }

    /// Handle incoming ACK
    pub fn handle_ack(&mut self, message_id: u16) {
        if self.pending_requests.remove(&message_id).is_some() {
            log::trace!("Received ACK for message {}", message_id);
        }
    }

    /// Join multicast group for discovery
    pub fn join_multicast(&self) -> Result<()> {
        // IPv4 multicast
        if let Some(socket) = &self.socket {
            let socket_ref = socket.get_ref();

            let multicast_addr: std::net::Ipv4Addr = COAP_MULTICAST_IPV4
                .parse()
                .map_err(|e| Error::network(format!("Invalid multicast address: {}", e)))?;

            socket_ref
                .join_multicast_v4(&multicast_addr, &std::net::Ipv4Addr::UNSPECIFIED)
                .map_err(|e| Error::network(format!("Failed to join multicast: {}", e)))?;

            log::info!("Joined CoAP multicast group {}", COAP_MULTICAST_IPV4);
        }

        Ok(())
    }

    /// Send multicast discovery request
    pub async fn send_discovery(&mut self) -> Result<()> {
        let multicast_addr: SocketAddr = format!("{}:{}", COAP_MULTICAST_IPV4, COAP_DEFAULT_PORT)
            .parse()
            .map_err(|e| Error::network(format!("Invalid address: {}", e)))?;

        let mut packet = Packet::new();
        packet.header.set_version(1);
        packet.header.set_type(MessageType::NonConfirmable);
        packet.header.code = MessageClass::Request(RequestType::Get);
        packet.header.message_id = self.next_message_id();
        packet.set_token(self.generate_token());
        packet.add_option(CoapOption::UriPath, b".well-known".to_vec());
        packet.add_option(CoapOption::UriPath, b"core".to_vec());

        if let Some(socket) = &self.socket {
            let bytes = packet
                .to_bytes()
                .map_err(|e| Error::network(format!("Failed to serialize discovery: {:?}", e)))?;

            socket
                .send_to(&bytes, multicast_addr)
                .await
                .map_err(|e| Error::network(format!("Discovery send error: {}", e)))?;

            log::debug!("Sent CoAP discovery to {}", multicast_addr);
        }

        Ok(())
    }

    /// Get CoRE Link Format resource description
    pub fn get_core_link_format(&self) -> String {
        "</gossip>;rt=\"aingle.gossip\";ct=50,\
             </record>;rt=\"aingle.record\";ct=50,\
             </announce>;rt=\"aingle.announce\";ct=50,\
             </ping>;rt=\"aingle.ping\""
            .to_string()
    }
}

/// CoAP configuration
#[derive(Debug, Clone)]
pub struct CoapConfig {
    /// Bind address
    pub bind_addr: String,
    /// Port
    pub port: u16,
    /// Enable multicast discovery
    pub enable_multicast: bool,
    /// Use confirmable messages by default
    pub default_confirmable: bool,
    /// ACK timeout in milliseconds
    pub ack_timeout_ms: u64,
    /// Maximum retransmissions
    pub max_retransmit: u8,
}

impl Default for CoapConfig {
    fn default() -> Self {
        Self {
            bind_addr: "0.0.0.0".to_string(),
            port: COAP_DEFAULT_PORT,
            enable_multicast: true,
            default_confirmable: false, // NON by default for IoT efficiency
            ack_timeout_ms: ACK_TIMEOUT_MS,
            max_retransmit: MAX_RETRANSMIT,
        }
    }
}

impl CoapConfig {
    /// IoT-optimized configuration
    pub fn iot_mode() -> Self {
        Self {
            bind_addr: "0.0.0.0".to_string(),
            port: COAP_DEFAULT_PORT,
            enable_multicast: true,
            default_confirmable: false,
            ack_timeout_ms: 1000, // Faster timeout
            max_retransmit: 2,    // Fewer retries
        }
    }
}

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

    #[test]
    fn test_coap_config_default() {
        let config = CoapConfig::default();
        assert_eq!(config.port, 5683);
        assert_eq!(config.bind_addr, "0.0.0.0");
        assert!(config.enable_multicast);
        assert!(!config.default_confirmable);
        assert_eq!(config.ack_timeout_ms, ACK_TIMEOUT_MS);
        assert_eq!(config.max_retransmit, MAX_RETRANSMIT);
    }

    #[test]
    fn test_coap_config_iot() {
        let config = CoapConfig::iot_mode();
        assert_eq!(config.ack_timeout_ms, 1000);
        assert_eq!(config.max_retransmit, 2);
        assert!(config.enable_multicast);
        assert!(!config.default_confirmable);
    }

    #[test]
    fn test_coap_config_clone() {
        let config1 = CoapConfig::default();
        let config2 = config1.clone();
        assert_eq!(config1.port, config2.port);
        assert_eq!(config1.bind_addr, config2.bind_addr);
    }

    #[test]
    fn test_coap_config_debug() {
        let config = CoapConfig::default();
        let debug_str = format!("{:?}", config);
        assert!(debug_str.contains("CoapConfig"));
        assert!(debug_str.contains("5683"));
    }

    #[test]
    fn test_coap_server_creation() {
        let server = CoapServer::new("127.0.0.1".to_string(), 5684, "node1".to_string());
        assert!(!server.is_running());
        assert!(server.socket.is_none());
    }

    #[test]
    fn test_core_link_format() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let links = server.get_core_link_format();
        assert!(links.contains("/gossip"));
        assert!(links.contains("/record"));
        assert!(links.contains("/announce"));
        assert!(links.contains("/ping"));
        assert!(links.contains("rt="));
        assert!(links.contains("ct=50"));
    }

    #[test]
    fn test_message_to_path_all_variants() {
        use crate::types::Hash;

        // Ping
        assert_eq!(
            CoapServer::message_to_path(&Message::Ping {
                node_id: "test".to_string()
            }),
            "/ping"
        );

        // Pong
        assert_eq!(
            CoapServer::message_to_path(&Message::Pong {
                node_id: "test".to_string(),
                latest_seq: 0
            }),
            "/ping"
        );

        // GossipRequest
        assert_eq!(
            CoapServer::message_to_path(&Message::GossipRequest {
                from_seq: 0,
                limit: 10
            }),
            "/gossip"
        );

        // GossipResponse
        assert_eq!(
            CoapServer::message_to_path(&Message::GossipResponse { records: vec![] }),
            "/gossip"
        );

        // NewRecord
        let test_hash = Hash::from_bytes(&[0u8; 32]);
        assert_eq!(
            CoapServer::message_to_path(&Message::NewRecord {
                hash: test_hash.clone()
            }),
            "/announce"
        );

        // GetRecord
        assert_eq!(
            CoapServer::message_to_path(&Message::GetRecord {
                hash: test_hash.clone()
            }),
            "/record"
        );

        // Note: RecordData path test skipped as Record construction is complex
        // The path mapping for RecordData is "/record" which is covered above
    }

    #[test]
    fn test_extract_path_empty() {
        let packet = Packet::new();
        let path = CoapServer::extract_path(&packet);
        assert_eq!(path, "/.well-known/core");
    }

    #[test]
    fn test_extract_path_single_segment() {
        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"ping".to_vec());
        let path = CoapServer::extract_path(&packet);
        assert_eq!(path, "/ping");
    }

    #[test]
    fn test_extract_path_multiple_segments() {
        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b".well-known".to_vec());
        packet.add_option(CoapOption::UriPath, b"core".to_vec());
        let path = CoapServer::extract_path(&packet);
        assert_eq!(path, "/.well-known/core");
    }

    #[test]
    fn test_constants() {
        assert_eq!(COAP_MAX_MESSAGE_SIZE, 1024);
        assert_eq!(COAP_DEFAULT_PORT, 5683);
        assert_eq!(COAP_MULTICAST_IPV4, "224.0.1.187");
        assert_eq!(BLOCK_SIZE, 256);
        assert_eq!(MAX_RETRANSMIT, 4);
        assert_eq!(ACK_TIMEOUT_MS, 2000);
    }

    #[test]
    fn test_coap_server_handle_ack() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        // ACK for non-existent message should not panic
        server.handle_ack(12345);

        // Insert a pending request and handle ACK
        let packet = Packet::new();
        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        server.pending_requests.insert(
            100,
            PendingRequest {
                packet,
                addr,
                sent_at: Instant::now(),
                retransmits: 0,
            },
        );

        assert!(server.pending_requests.contains_key(&100));
        server.handle_ack(100);
        assert!(!server.pending_requests.contains_key(&100));
    }

    #[test]
    fn test_coap_server_next_message_id() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let id1 = server.next_message_id();
        let id2 = server.next_message_id();
        assert_eq!(id2, id1.wrapping_add(1));
    }

    #[test]
    fn test_coap_server_generate_token() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let token1 = server.generate_token();
        let token2 = server.generate_token();

        assert_eq!(token1.len(), 4);
        assert_eq!(token2.len(), 4);
        // Tokens should be different (random)
        // Note: There's a tiny chance they could be equal, but statistically unlikely
    }

    #[test]
    fn test_pending_request_debug() {
        let packet = Packet::new();
        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let pending = PendingRequest {
            packet,
            addr,
            sent_at: Instant::now(),
            retransmits: 2,
        };
        let debug_str = format!("{:?}", pending);
        assert!(debug_str.contains("PendingRequest"));
        assert!(debug_str.contains("retransmits: 2"));
    }

    #[test]
    fn test_create_request_packet_non_confirmable() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let packet = server.create_request_packet("/ping", b"hello", false);

        assert_eq!(packet.header.get_type(), MessageType::NonConfirmable);
        assert_eq!(packet.header.code, MessageClass::Request(RequestType::Post));
        assert_eq!(packet.payload, b"hello");
    }

    #[test]
    fn test_create_request_packet_confirmable() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let packet = server.create_request_packet("/gossip", b"data", true);

        assert_eq!(packet.header.get_type(), MessageType::Confirmable);
        assert!(!packet.get_token().is_empty());
    }

    #[test]
    fn test_create_request_packet_with_path_segments() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let packet = server.create_request_packet("/a/b/c", b"", false);

        // Should have multiple UriPath options
        let uri_paths = packet.get_option(CoapOption::UriPath);
        assert!(uri_paths.is_some());
        let paths: Vec<_> = uri_paths.unwrap().iter().collect();
        assert_eq!(paths.len(), 3);
    }

    #[test]
    fn test_process_packet_ping_with_payload() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"ping".to_vec());
        packet.payload = b"node123".to_vec();

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        if let Ok(Some(Message::Ping { node_id })) = result {
            assert_eq!(node_id, "node123");
        }
    }

    #[test]
    fn test_process_packet_ping_empty_payload() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"ping".to_vec());
        // Empty payload

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        if let Ok(Some(Message::Ping { node_id })) = result {
            assert_eq!(node_id, "unknown");
        }
    }

    #[test]
    fn test_process_packet_unknown_path() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"unknown".to_vec());

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_process_packet_gossip_with_valid_json() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"gossip".to_vec());

        let msg = Message::GossipRequest {
            from_seq: 0,
            limit: 10,
        };
        packet.payload = serde_json::to_vec(&msg).unwrap();

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_process_packet_gossip_empty_payload() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"gossip".to_vec());
        // Empty payload

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_process_packet_wellknown_core() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b".well-known".to_vec());
        packet.add_option(CoapOption::UriPath, b"core".to_vec());

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        // Discovery returns None (handled separately)
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_process_packet_record_with_valid_json() {
        use crate::types::Hash;

        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"record".to_vec());

        let test_hash = Hash::from_bytes(&[0u8; 32]);
        let msg = Message::GetRecord { hash: test_hash };
        packet.payload = serde_json::to_vec(&msg).unwrap();

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_process_packet_record_empty_payload() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"record".to_vec());

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_process_packet_announce_with_valid_json() {
        use crate::types::Hash;

        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"announce".to_vec());

        let test_hash = Hash::from_bytes(&[1u8; 32]);
        let msg = Message::NewRecord { hash: test_hash };
        packet.payload = serde_json::to_vec(&msg).unwrap();

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_some());
    }

    #[test]
    fn test_process_packet_announce_empty_payload() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"announce".to_vec());

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_ok());
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_process_packet_invalid_json() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());

        let mut packet = Packet::new();
        packet.add_option(CoapOption::UriPath, b"gossip".to_vec());
        packet.payload = b"invalid json {".to_vec();

        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();
        let result = server.process_packet(&packet, &addr);

        assert!(result.is_err());
    }

    #[test]
    fn test_block_state_debug() {
        let state = BlockState {
            data: vec![1, 2, 3],
            block_num: 5,
            more: true,
        };
        let debug_str = format!("{:?}", state);
        assert!(debug_str.contains("BlockState"));
        assert!(debug_str.contains("block_num: 5"));
        assert!(debug_str.contains("more: true"));
    }

    #[test]
    fn test_block_state_clone() {
        let state1 = BlockState {
            data: vec![1, 2, 3],
            block_num: 10,
            more: false,
        };
        let state2 = state1.clone();
        assert_eq!(state1.data, state2.data);
        assert_eq!(state1.block_num, state2.block_num);
        assert_eq!(state1.more, state2.more);
    }

    #[test]
    fn test_coap_server_message_id_wrapping() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        server.message_id = u16::MAX;
        let id = server.next_message_id();
        assert_eq!(id, 0);
    }

    #[test]
    fn test_message_to_path_record_data() {
        use crate::types::{Action, Entry};
        use crate::types::{ActionType, AgentPubKey, EntryType, Record, Signature, Timestamp};

        let action = Action {
            action_type: ActionType::Create,
            author: AgentPubKey([0u8; 32]),
            timestamp: Timestamp::now(),
            seq: 1,
            prev_action: None,
            entry_hash: None,
            signature: Signature([0u8; 64]),
        };

        let entry = Entry {
            entry_type: EntryType::App,
            content: vec![1, 2, 3],
        };

        let record = Record {
            action,
            entry: Some(entry),
        };

        let msg = Message::RecordData { record };

        assert_eq!(CoapServer::message_to_path(&msg), "/record");
    }

    #[test]
    fn test_join_multicast_no_socket() {
        let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        // Without socket, should return Ok (no-op)
        let result = server.join_multicast();
        assert!(result.is_ok());
    }

    #[test]
    fn test_coap_server_is_running_no_socket() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        assert!(!server.is_running());
        server.running = true;
        // Still false because socket is None
        assert!(!server.is_running());
    }

    #[test]
    fn test_coap_multicast_ipv6_constant() {
        assert_eq!(COAP_MULTICAST_IPV6, "ff02::fd");
    }

    #[test]
    fn test_pending_request_fields() {
        let mut packet = Packet::new();
        packet.payload = vec![1, 2, 3];
        let addr: SocketAddr = "192.168.1.1:5683".parse().unwrap();
        let sent_at = Instant::now();

        let pending = PendingRequest {
            packet,
            addr,
            sent_at,
            retransmits: 3,
        };

        assert_eq!(pending.retransmits, 3);
        assert_eq!(pending.addr.port(), 5683);
        assert_eq!(pending.packet.payload, vec![1, 2, 3]);
    }

    #[test]
    fn test_block_state_fields() {
        let state = BlockState {
            data: vec![10, 20, 30, 40, 50],
            block_num: 42,
            more: true,
        };

        assert_eq!(state.data.len(), 5);
        assert_eq!(state.block_num, 42);
        assert!(state.more);
    }

    #[test]
    fn test_coap_config_custom() {
        let config = CoapConfig {
            bind_addr: "192.168.1.100".to_string(),
            port: 5700,
            enable_multicast: false,
            default_confirmable: true,
            ack_timeout_ms: 5000,
            max_retransmit: 10,
        };

        assert_eq!(config.port, 5700);
        assert!(!config.enable_multicast);
        assert!(config.default_confirmable);
        assert_eq!(config.ack_timeout_ms, 5000);
        assert_eq!(config.max_retransmit, 10);
    }

    #[test]
    fn test_create_request_packet_empty_path() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let packet = server.create_request_packet("/", b"", false);

        // Should have content format option
        let cf = packet.get_option(CoapOption::ContentFormat);
        assert!(cf.is_some());
    }

    #[test]
    fn test_pending_requests_multiple() {
        let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
        let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();

        for i in 0u16..5 {
            let packet = Packet::new();
            server.pending_requests.insert(
                i,
                PendingRequest {
                    packet,
                    addr,
                    sent_at: Instant::now(),
                    retransmits: 0,
                },
            );
        }

        assert_eq!(server.pending_requests.len(), 5);

        // Handle ACKs
        server.handle_ack(0);
        server.handle_ack(2);
        server.handle_ack(4);

        assert_eq!(server.pending_requests.len(), 2);
        assert!(server.pending_requests.contains_key(&1));
        assert!(server.pending_requests.contains_key(&3));
    }

    #[test]
    fn test_coap_server_recv_no_socket() {
        smol::block_on(async {
            let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            let result = server.recv().await;
            assert!(result.is_err());
        });
    }

    #[test]
    fn test_coap_server_stop() {
        smol::block_on(async {
            let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            server.running = true;

            let result = server.stop().await;
            assert!(result.is_ok());
            assert!(!server.is_running());
            assert!(server.socket.is_none());
        });
    }

    #[test]
    fn test_coap_server_send_no_socket() {
        smol::block_on(async {
            let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            let addr: SocketAddr = "127.0.0.1:5684".parse().unwrap();
            let msg = Message::Ping {
                node_id: "test".to_string(),
            };

            let result = server.send(&addr, &msg, false).await;
            assert!(result.is_err());
        });
    }

    #[test]
    fn test_coap_server_send_response_no_socket() {
        smol::block_on(async {
            let server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            let addr: SocketAddr = "127.0.0.1:5684".parse().unwrap();
            let request = Packet::new();

            let result = server
                .send_response(&addr, &request, ResponseType::Content, None)
                .await;
            assert!(result.is_err());
        });
    }

    #[test]
    fn test_coap_server_send_discovery_no_socket() {
        smol::block_on(async {
            let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            // Without socket, send_discovery should complete (no-op when socket is None)
            let result = server.send_discovery().await;
            // Should return Ok since it just checks if socket exists
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_coap_server_handle_retransmissions_no_socket() {
        smol::block_on(async {
            let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            // Without pending requests, should complete
            let result = server.handle_retransmissions().await;
            assert!(result.is_ok());
        });
    }

    #[test]
    fn test_coap_server_handle_retransmissions_timed_out() {
        smol::block_on(async {
            let mut server = CoapServer::new("0.0.0.0".to_string(), 5683, "test".to_string());
            let addr: SocketAddr = "127.0.0.1:5683".parse().unwrap();

            // Insert a pending request with old timestamp
            let packet = Packet::new();
            server.pending_requests.insert(
                100,
                PendingRequest {
                    packet,
                    addr,
                    sent_at: Instant::now() - Duration::from_secs(10), // Old
                    retransmits: MAX_RETRANSMIT,                       // Max retries already
                },
            );

            // Should remove timed out request
            let result = server.handle_retransmissions().await;
            assert!(result.is_ok());
            assert!(!server.pending_requests.contains_key(&100));
        });
    }
}