algochat 0.2.1

Rust implementation of the AlgoChat protocol for encrypted messaging on Algorand
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
//! Blockchain interfaces for Algorand integration.
//!
//! This module provides traits for interacting with Algorand nodes (algod)
//! and indexers. Implementations can use any Algorand SDK.

use crate::models::DiscoveredKey;
use crate::types::Result;

/// Configuration for Algorand node connections.
#[derive(Debug, Clone)]
pub struct AlgorandConfig {
    /// Algod node URL.
    pub algod_url: String,
    /// Algod API token.
    pub algod_token: String,
    /// Indexer URL (optional).
    pub indexer_url: Option<String>,
    /// Indexer API token (optional).
    pub indexer_token: Option<String>,
}

impl AlgorandConfig {
    /// Creates a new configuration for connecting to Algorand nodes.
    pub fn new(algod_url: &str, algod_token: &str) -> Self {
        Self {
            algod_url: algod_url.to_string(),
            algod_token: algod_token.to_string(),
            indexer_url: None,
            indexer_token: None,
        }
    }

    /// Sets the indexer configuration.
    pub fn with_indexer(mut self, url: &str, token: &str) -> Self {
        self.indexer_url = Some(url.to_string());
        self.indexer_token = Some(token.to_string());
        self
    }

    /// Creates configuration for LocalNet (Algokit sandbox).
    pub fn localnet() -> Self {
        Self {
            algod_url: "http://localhost:4001".to_string(),
            algod_token: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                .to_string(),
            indexer_url: Some("http://localhost:8980".to_string()),
            indexer_token: Some(
                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
            ),
        }
    }

    /// Creates configuration for TestNet (via Nodely).
    pub fn testnet() -> Self {
        Self {
            algod_url: "https://testnet-api.4160.nodely.dev".to_string(),
            algod_token: String::new(),
            indexer_url: Some("https://testnet-idx.4160.nodely.dev".to_string()),
            indexer_token: Some(String::new()),
        }
    }

    /// Creates configuration for MainNet (via Nodely).
    pub fn mainnet() -> Self {
        Self {
            algod_url: "https://mainnet-api.4160.nodely.dev".to_string(),
            algod_token: String::new(),
            indexer_url: Some("https://mainnet-idx.4160.nodely.dev".to_string()),
            indexer_token: Some(String::new()),
        }
    }
}

/// Transaction information returned after submission.
#[derive(Debug, Clone)]
pub struct TransactionInfo {
    /// Transaction ID.
    pub txid: String,
    /// Round in which the transaction was confirmed (if confirmed).
    pub confirmed_round: Option<u64>,
}

/// A note field transaction from the blockchain.
#[derive(Debug, Clone)]
pub struct NoteTransaction {
    /// Transaction ID.
    pub txid: String,
    /// Sender address.
    pub sender: String,
    /// Receiver address.
    pub receiver: String,
    /// Note field contents.
    pub note: Vec<u8>,
    /// Round in which the transaction was confirmed.
    pub confirmed_round: u64,
    /// Timestamp of the block (Unix time).
    pub round_time: u64,
}

/// Trait for interacting with an Algorand node (algod).
#[async_trait::async_trait]
pub trait AlgodClient: Send + Sync {
    /// Get the current network parameters.
    async fn get_suggested_params(&self) -> Result<SuggestedParams>;

    /// Get account information.
    async fn get_account_info(&self, address: &str) -> Result<AccountInfo>;

    /// Submit a signed transaction.
    async fn submit_transaction(&self, signed_txn: &[u8]) -> Result<String>;

    /// Wait for a transaction to be confirmed.
    async fn wait_for_confirmation(&self, txid: &str, rounds: u32) -> Result<TransactionInfo>;

    /// Get the current round.
    async fn get_current_round(&self) -> Result<u64>;
}

/// Suggested transaction parameters.
#[derive(Debug, Clone)]
pub struct SuggestedParams {
    /// Fee per byte in microAlgos.
    pub fee: u64,
    /// Minimum fee in microAlgos.
    pub min_fee: u64,
    /// First valid round.
    pub first_valid: u64,
    /// Last valid round.
    pub last_valid: u64,
    /// Genesis ID.
    pub genesis_id: String,
    /// Genesis hash.
    pub genesis_hash: [u8; 32],
}

/// Account information.
#[derive(Debug, Clone)]
pub struct AccountInfo {
    /// Account address.
    pub address: String,
    /// Account balance in microAlgos.
    pub amount: u64,
    /// Minimum balance required.
    pub min_balance: u64,
}

/// Paginated transaction search result.
///
/// Wraps transactions with an optional `next_token` for cursor-based
/// pagination. When `next_token` is present, more results are available.
#[derive(Debug, Clone)]
pub struct PaginatedTransactions {
    /// The transactions in this page.
    pub transactions: Vec<NoteTransaction>,
    /// Opaque cursor for fetching the next page. `None` when no more results.
    pub next_token: Option<String>,
}

/// Default page size for key discovery pagination.
pub const DEFAULT_DISCOVERY_PAGE_SIZE: u32 = 100;

/// Trait for interacting with an Algorand indexer.
#[async_trait::async_trait]
pub trait IndexerClient: Send + Sync {
    /// Search for transactions with notes sent to/from an address.
    async fn search_transactions(
        &self,
        address: &str,
        after_round: Option<u64>,
        limit: Option<u32>,
    ) -> Result<Vec<NoteTransaction>>;

    /// Search for transactions between two addresses.
    async fn search_transactions_between(
        &self,
        address1: &str,
        address2: &str,
        after_round: Option<u64>,
        limit: Option<u32>,
    ) -> Result<Vec<NoteTransaction>>;

    /// Get a specific transaction by ID.
    async fn get_transaction(&self, txid: &str) -> Result<NoteTransaction>;

    /// Wait for a transaction to be indexed.
    async fn wait_for_indexer(&self, txid: &str, timeout_secs: u32) -> Result<NoteTransaction>;

    /// Search for transactions with cursor-based pagination.
    ///
    /// Returns a page of transactions and an optional `next_token` for fetching
    /// the next page. Implementations should use the Algorand indexer's native
    /// `next-token` pagination when available.
    ///
    /// The default implementation falls back to `search_transactions` without
    /// pagination support (returns all results with no next_token).
    async fn search_transactions_paginated(
        &self,
        address: &str,
        limit: Option<u32>,
        next_token: Option<&str>,
    ) -> Result<PaginatedTransactions> {
        let _ = next_token; // ignored in fallback
        let transactions = self.search_transactions(address, None, limit).await?;
        Ok(PaginatedTransactions {
            transactions,
            next_token: None,
        })
    }
}

/// Discovers the encryption public key for an Algorand address.
///
/// Uses paginated search with the indexer's `next-token` cursor to walk
/// through the full transaction history. By default searches exhaustively
/// (max_pages = None). Callers can pass a max page count as a safety bound.
///
/// The key is considered verified if it was signed by the address's Ed25519 key.
pub async fn discover_encryption_key(
    indexer: &dyn IndexerClient,
    address: &str,
) -> Result<Option<DiscoveredKey>> {
    discover_encryption_key_paginated(indexer, address, DEFAULT_DISCOVERY_PAGE_SIZE, None).await
}

/// Discovers the encryption public key with configurable pagination.
///
/// - `page_size`: Number of transactions per indexer page.
/// - `max_pages`: Maximum pages to fetch, or `None` for exhaustive search.
pub async fn discover_encryption_key_paginated(
    indexer: &dyn IndexerClient,
    address: &str,
    page_size: u32,
    max_pages: Option<u32>,
) -> Result<Option<DiscoveredKey>> {
    let mut next_token: Option<String> = None;
    let mut pages_searched: u32 = 0;

    loop {
        let result = indexer
            .search_transactions_paginated(address, Some(page_size), next_token.as_deref())
            .await?;

        // Look for key announcements in the note field
        for tx in &result.transactions {
            if tx.sender != address {
                continue;
            }

            // Check if this is a key announcement (self-transfer with note)
            if tx.receiver != address {
                continue;
            }

            // Try to parse as key announcement
            if let Some(key) = parse_key_announcement(&tx.note, address) {
                return Ok(Some(key));
            }
        }

        pages_searched += 1;

        // Stop if no more pages or empty response
        match result.next_token {
            Some(token) if !result.transactions.is_empty() => {
                next_token = Some(token);
            }
            _ => break,
        }

        // Stop if we've hit the page limit
        if let Some(max) = max_pages {
            if pages_searched >= max {
                break;
            }
        }
    }

    Ok(None)
}

/// Decodes an Algorand address to extract the 32-byte Ed25519 public key.
///
/// Algorand addresses are base32-encoded (no padding) and contain:
/// - 32 bytes: Ed25519 public key
/// - 4 bytes: checksum (last 4 bytes of SHA-512/256 of the public key)
///
/// Returns `None` if the address is malformed or the checksum doesn't match.
fn decode_algorand_address(address: &str) -> Option<[u8; 32]> {
    let decoded = data_encoding::BASE32_NOPAD
        .decode(address.as_bytes())
        .ok()?;
    if decoded.len() != 36 {
        return None;
    }
    let public_key = &decoded[..32];
    let checksum = &decoded[32..36];

    // Verify checksum: last 4 bytes of SHA-512/256(public_key)
    use sha2::Digest;
    let hash = sha2::Sha512_256::digest(public_key);
    if checksum != &hash[hash.len() - 4..] {
        return None;
    }

    let mut ed25519_public_key = [0u8; 32];
    ed25519_public_key.copy_from_slice(public_key);
    Some(ed25519_public_key)
}

/// Parses a key announcement from a transaction note.
fn parse_key_announcement(note: &[u8], address: &str) -> Option<DiscoveredKey> {
    // Key announcement format:
    // - 32 bytes: X25519 public key
    // - 64 bytes (optional): Ed25519 signature

    if note.len() < 32 {
        return None;
    }

    let mut public_key = [0u8; 32];
    public_key.copy_from_slice(&note[..32]);

    let is_verified = if note.len() >= 96 {
        // Has signature, verify it using the Ed25519 public key from the Algorand address
        let signature = &note[32..96];
        match decode_algorand_address(address) {
            Some(ed25519_key) => {
                crate::signature::verify_encryption_key_bytes(&public_key, &ed25519_key, signature)
                    .unwrap_or(false)
            }
            None => false,
        }
    } else {
        false
    };

    Some(DiscoveredKey {
        public_key,
        is_verified,
    })
}

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

    #[test]
    fn test_config_localnet() {
        let config = AlgorandConfig::localnet();
        assert!(config.algod_url.contains("localhost"));
        assert!(config.indexer_url.is_some());
    }

    #[test]
    fn test_config_testnet() {
        let config = AlgorandConfig::testnet();
        assert!(config.algod_url.contains("testnet"));
    }

    #[test]
    fn test_config_mainnet() {
        let config = AlgorandConfig::mainnet();
        assert!(config.algod_url.contains("mainnet"));
    }

    #[test]
    fn test_config_with_indexer() {
        let config = AlgorandConfig::new("http://localhost:4001", "token123")
            .with_indexer("http://localhost:8980", "idx-token");
        assert_eq!(config.algod_url, "http://localhost:4001");
        assert_eq!(config.algod_token, "token123");
        assert_eq!(
            config.indexer_url,
            Some("http://localhost:8980".to_string())
        );
        assert_eq!(config.indexer_token, Some("idx-token".to_string()));
    }

    #[test]
    fn test_decode_algorand_address_valid() {
        // A valid Algorand address (base32-encoded, 58 chars, 36 bytes decoded)
        // Generate one: 32 bytes pubkey + 4 bytes checksum
        let pubkey = [0u8; 32];
        use sha2::Digest;
        let hash = sha2::Sha512_256::digest(pubkey);
        let checksum = &hash[hash.len() - 4..];
        let mut full = Vec::with_capacity(36);
        full.extend_from_slice(&pubkey);
        full.extend_from_slice(checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&full);

        let decoded = decode_algorand_address(&address);
        assert!(decoded.is_some());
        assert_eq!(decoded.unwrap(), pubkey);
    }

    #[test]
    fn test_decode_algorand_address_bad_checksum() {
        // Build an address with correct length but wrong checksum
        let pubkey = [1u8; 32];
        let bad_checksum = [0xFF, 0xFF, 0xFF, 0xFF];
        let mut full = Vec::with_capacity(36);
        full.extend_from_slice(&pubkey);
        full.extend_from_slice(&bad_checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&full);

        let result = decode_algorand_address(&address);
        assert!(result.is_none(), "bad checksum should be rejected");
    }

    #[test]
    fn test_decode_algorand_address_too_short() {
        let result = decode_algorand_address("AAAA");
        assert!(result.is_none());
    }

    #[test]
    fn test_decode_algorand_address_invalid_base32() {
        let result = decode_algorand_address("not-valid-base32!!!");
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_key_announcement_too_short() {
        let note = [0u8; 16]; // Less than 32 bytes
        let result = parse_key_announcement(&note, "SOMEADDR");
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_key_announcement_valid_unsigned() {
        let mut note = [0u8; 32];
        note[0] = 0x42; // Some key data
        let result = parse_key_announcement(&note, "SOMEADDR");
        assert!(result.is_some());
        let key = result.unwrap();
        assert_eq!(key.public_key[0], 0x42);
        assert!(!key.is_verified); // No signature, so not verified
    }

    #[test]
    fn test_parse_key_announcement_with_bad_signature() {
        // 32 bytes key + 64 bytes bad signature = 96 bytes
        let note = [0u8; 96];
        // Use a valid-looking address (we'll use zeros which decode to a valid key)
        let pubkey = [0u8; 32];
        use sha2::Digest;
        let hash = sha2::Sha512_256::digest(pubkey);
        let checksum = &hash[hash.len() - 4..];
        let mut full = Vec::with_capacity(36);
        full.extend_from_slice(&pubkey);
        full.extend_from_slice(checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&full);

        let result = parse_key_announcement(&note, &address);
        assert!(result.is_some());
        let key = result.unwrap();
        // Bad signature should result in unverified
        assert!(!key.is_verified);
    }

    #[test]
    fn test_transaction_info_debug() {
        let info = TransactionInfo {
            txid: "TXID123".to_string(),
            confirmed_round: Some(1000),
        };
        let debug = format!("{:?}", info);
        assert!(debug.contains("TXID123"));
    }

    #[test]
    fn test_note_transaction_clone() {
        let tx = NoteTransaction {
            txid: "TX1".to_string(),
            sender: "SENDER".to_string(),
            receiver: "RECEIVER".to_string(),
            note: vec![1, 2, 3],
            confirmed_round: 100,
            round_time: 1234567890,
        };
        let cloned = tx.clone();
        assert_eq!(cloned.txid, tx.txid);
        assert_eq!(cloned.note, tx.note);
    }

    #[test]
    fn test_parse_key_announcement_with_valid_signature() {
        use ed25519_dalek::{Signer, SigningKey};

        // Create an Ed25519 keypair
        let signing_key = SigningKey::from_bytes(&[42u8; 32]);
        let ed25519_pubkey = signing_key.verifying_key().to_bytes();

        // Build a valid Algorand address from this Ed25519 public key
        use sha2::Digest;
        let hash = sha2::Sha512_256::digest(ed25519_pubkey);
        let checksum = &hash[hash.len() - 4..];
        let mut addr_bytes = Vec::with_capacity(36);
        addr_bytes.extend_from_slice(&ed25519_pubkey);
        addr_bytes.extend_from_slice(checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&addr_bytes);

        // Create an X25519 encryption key and sign it
        let encryption_key = [0xABu8; 32];
        let signature = signing_key.sign(&encryption_key);

        // Build the note: 32 bytes key + 64 bytes signature
        let mut note = Vec::with_capacity(96);
        note.extend_from_slice(&encryption_key);
        note.extend_from_slice(&signature.to_bytes());

        let result = parse_key_announcement(&note, &address);
        assert!(result.is_some());
        let key = result.unwrap();
        assert_eq!(key.public_key, encryption_key);
        assert!(key.is_verified, "valid signature should be verified");
    }

    #[test]
    fn test_parse_key_announcement_wrong_signer() {
        use ed25519_dalek::{Signer, SigningKey};

        // Sign with one key but use a different key in the address
        let signing_key = SigningKey::from_bytes(&[42u8; 32]);
        let different_key = SigningKey::from_bytes(&[99u8; 32]);
        let different_pubkey = different_key.verifying_key().to_bytes();

        // Build address from the DIFFERENT key
        use sha2::Digest;
        let hash = sha2::Sha512_256::digest(different_pubkey);
        let checksum = &hash[hash.len() - 4..];
        let mut addr_bytes = Vec::with_capacity(36);
        addr_bytes.extend_from_slice(&different_pubkey);
        addr_bytes.extend_from_slice(checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&addr_bytes);

        // Sign with the ORIGINAL key (mismatch)
        let encryption_key = [0xABu8; 32];
        let signature = signing_key.sign(&encryption_key);

        let mut note = Vec::with_capacity(96);
        note.extend_from_slice(&encryption_key);
        note.extend_from_slice(&signature.to_bytes());

        let result = parse_key_announcement(&note, &address);
        assert!(result.is_some());
        let key = result.unwrap();
        assert!(!key.is_verified, "wrong signer should not verify");
    }

    #[test]
    fn test_parse_key_announcement_exactly_32_bytes() {
        // Exactly 32 bytes (no signature)
        let note = [0x42u8; 32];
        let result = parse_key_announcement(&note, "SOMEADDR");
        assert!(result.is_some());
        assert!(!result.unwrap().is_verified);
    }

    #[test]
    fn test_parse_key_announcement_between_32_and_96_bytes() {
        // Between 32 and 96 bytes (partial, no valid signature)
        let note = [0x42u8; 64];
        let result = parse_key_announcement(&note, "SOMEADDR");
        assert!(result.is_some());
        assert!(!result.unwrap().is_verified);
    }

    #[test]
    fn test_parse_key_announcement_over_96_bytes() {
        // More than 96 bytes (has signature at correct position)
        let note = vec![0x42u8; 128];
        // First 32 bytes are the key, bytes 32..96 would be the signature
        // With garbage data, this should not verify
        let result = parse_key_announcement(&note, "SOMEADDR");
        assert!(result.is_some());
        assert!(!result.unwrap().is_verified);
    }

    #[test]
    fn test_decode_algorand_address_various_keys() {
        use sha2::Digest;

        // Test with several different key values
        for i in 0u8..5 {
            let pubkey = [i; 32];
            let hash = sha2::Sha512_256::digest(pubkey);
            let checksum = &hash[hash.len() - 4..];
            let mut full = Vec::with_capacity(36);
            full.extend_from_slice(&pubkey);
            full.extend_from_slice(checksum);
            let address = data_encoding::BASE32_NOPAD.encode(&full);

            let decoded = decode_algorand_address(&address);
            assert!(decoded.is_some(), "key {} should decode", i);
            assert_eq!(decoded.unwrap(), pubkey);
        }
    }

    /// Mock indexer for discover_encryption_key tests
    struct MockDiscoveryIndexer {
        transactions: Vec<NoteTransaction>,
    }

    #[async_trait::async_trait]
    impl IndexerClient for MockDiscoveryIndexer {
        async fn search_transactions(
            &self,
            address: &str,
            _after_round: Option<u64>,
            _limit: Option<u32>,
        ) -> crate::types::Result<Vec<NoteTransaction>> {
            Ok(self
                .transactions
                .iter()
                .filter(|tx| tx.sender == address || tx.receiver == address)
                .cloned()
                .collect())
        }

        async fn search_transactions_between(
            &self,
            _a1: &str,
            _a2: &str,
            _after_round: Option<u64>,
            _limit: Option<u32>,
        ) -> crate::types::Result<Vec<NoteTransaction>> {
            Ok(Vec::new())
        }

        async fn get_transaction(&self, _txid: &str) -> crate::types::Result<NoteTransaction> {
            Err(crate::types::AlgoChatError::TransactionFailed(
                "not found".to_string(),
            ))
        }

        async fn wait_for_indexer(
            &self,
            _txid: &str,
            _timeout: u32,
        ) -> crate::types::Result<NoteTransaction> {
            Err(crate::types::AlgoChatError::TransactionFailed(
                "not found".to_string(),
            ))
        }
    }

    #[tokio::test]
    async fn test_discover_encryption_key_no_transactions() {
        let indexer = MockDiscoveryIndexer {
            transactions: Vec::new(),
        };
        let result = discover_encryption_key(&indexer, "SOMEADDR").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_discover_encryption_key_non_self_transfer() {
        let indexer = MockDiscoveryIndexer {
            transactions: vec![NoteTransaction {
                txid: "TX1".to_string(),
                sender: "ALICE".to_string(),
                receiver: "BOB".to_string(), // Not a self-transfer
                note: vec![0u8; 32],
                confirmed_round: 100,
                round_time: 1700000000,
            }],
        };
        let result = discover_encryption_key(&indexer, "ALICE").await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_discover_encryption_key_valid_self_transfer() {
        let key = [0xABu8; 32];
        let address = "MYADDR";

        let indexer = MockDiscoveryIndexer {
            transactions: vec![NoteTransaction {
                txid: "TX1".to_string(),
                sender: address.to_string(),
                receiver: address.to_string(),
                note: key.to_vec(),
                confirmed_round: 100,
                round_time: 1700000000,
            }],
        };
        let result = discover_encryption_key(&indexer, address).await.unwrap();
        assert!(result.is_some());
        let discovered = result.unwrap();
        assert_eq!(discovered.public_key, key);
        assert!(!discovered.is_verified); // Invalid address format, so no signature check
    }

    #[tokio::test]
    async fn test_discover_encryption_key_with_signed_announcement() {
        use ed25519_dalek::{Signer, SigningKey};
        use sha2::Digest;

        let signing_key = SigningKey::from_bytes(&[42u8; 32]);
        let ed25519_pubkey = signing_key.verifying_key().to_bytes();

        // Build valid Algorand address
        let hash = sha2::Sha512_256::digest(ed25519_pubkey);
        let checksum = &hash[hash.len() - 4..];
        let mut addr_bytes = Vec::with_capacity(36);
        addr_bytes.extend_from_slice(&ed25519_pubkey);
        addr_bytes.extend_from_slice(checksum);
        let address = data_encoding::BASE32_NOPAD.encode(&addr_bytes);

        // Create signed key announcement
        let encryption_key = [0xABu8; 32];
        let signature = signing_key.sign(&encryption_key);
        let mut note = Vec::with_capacity(96);
        note.extend_from_slice(&encryption_key);
        note.extend_from_slice(&signature.to_bytes());

        let indexer = MockDiscoveryIndexer {
            transactions: vec![NoteTransaction {
                txid: "TX1".to_string(),
                sender: address.clone(),
                receiver: address.clone(),
                note,
                confirmed_round: 100,
                round_time: 1700000000,
            }],
        };

        let result = discover_encryption_key(&indexer, &address).await.unwrap();
        assert!(result.is_some());
        let discovered = result.unwrap();
        assert_eq!(discovered.public_key, encryption_key);
        assert!(discovered.is_verified);
    }

    #[tokio::test]
    async fn test_discover_encryption_key_skips_short_notes() {
        let address = "MYADDR";

        let indexer = MockDiscoveryIndexer {
            transactions: vec![NoteTransaction {
                txid: "TX1".to_string(),
                sender: address.to_string(),
                receiver: address.to_string(),
                note: vec![1, 2, 3], // Too short for key announcement
                confirmed_round: 100,
                round_time: 1700000000,
            }],
        };

        let result = discover_encryption_key(&indexer, address).await.unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_suggested_params_debug() {
        let params = SuggestedParams {
            fee: 1000,
            min_fee: 1000,
            first_valid: 100,
            last_valid: 1100,
            genesis_id: "testnet-v1.0".to_string(),
            genesis_hash: [0u8; 32],
        };
        let debug = format!("{:?}", params);
        assert!(debug.contains("testnet-v1.0"));
    }

    #[test]
    fn test_account_info_debug() {
        let info = AccountInfo {
            address: "ADDR123".to_string(),
            amount: 1_000_000,
            min_balance: 100_000,
        };
        let debug = format!("{:?}", info);
        assert!(debug.contains("ADDR123"));
        assert!(debug.contains("1000000"));
    }

    // MARK: - Paginated Key Discovery Tests

    use std::collections::HashMap;
    use std::sync::Mutex;

    /// Mock indexer that returns pre-configured pages of results
    struct MockPaginatedIndexer {
        /// Pages keyed by next_token (None = first page)
        pages: HashMap<Option<String>, PaginatedTransactions>,
        /// Track number of search calls
        call_count: Mutex<u32>,
        /// Track last page size requested
        last_limit: Mutex<Option<u32>>,
    }

    impl MockPaginatedIndexer {
        fn new(pages: Vec<PaginatedTransactions>) -> Self {
            let mut map = HashMap::new();
            // First page is keyed by None
            if let Some(first) = pages.first() {
                map.insert(None, first.clone());
            }
            // Subsequent pages keyed by their preceding next_token
            for i in 0..pages.len().saturating_sub(1) {
                if let Some(token) = &pages[i].next_token {
                    map.insert(Some(token.clone()), pages[i + 1].clone());
                }
            }
            Self {
                pages: map,
                call_count: Mutex::new(0),
                last_limit: Mutex::new(None),
            }
        }

        fn call_count(&self) -> u32 {
            *self.call_count.lock().unwrap()
        }

        fn last_limit(&self) -> Option<u32> {
            *self.last_limit.lock().unwrap()
        }
    }

    #[async_trait::async_trait]
    impl IndexerClient for MockPaginatedIndexer {
        async fn search_transactions(
            &self,
            _address: &str,
            _after_round: Option<u64>,
            _limit: Option<u32>,
        ) -> crate::types::Result<Vec<NoteTransaction>> {
            Ok(Vec::new())
        }

        async fn search_transactions_between(
            &self,
            _a1: &str,
            _a2: &str,
            _after_round: Option<u64>,
            _limit: Option<u32>,
        ) -> crate::types::Result<Vec<NoteTransaction>> {
            Ok(Vec::new())
        }

        async fn get_transaction(&self, _txid: &str) -> crate::types::Result<NoteTransaction> {
            Err(crate::types::AlgoChatError::TransactionFailed(
                "not found".to_string(),
            ))
        }

        async fn wait_for_indexer(
            &self,
            _txid: &str,
            _timeout: u32,
        ) -> crate::types::Result<NoteTransaction> {
            Err(crate::types::AlgoChatError::TransactionFailed(
                "not found".to_string(),
            ))
        }

        async fn search_transactions_paginated(
            &self,
            _address: &str,
            limit: Option<u32>,
            next_token: Option<&str>,
        ) -> crate::types::Result<PaginatedTransactions> {
            *self.call_count.lock().unwrap() += 1;
            *self.last_limit.lock().unwrap() = limit;

            let key = next_token.map(|s| s.to_string());
            match self.pages.get(&key) {
                Some(page) => Ok(page.clone()),
                None => Ok(PaginatedTransactions {
                    transactions: Vec::new(),
                    next_token: None,
                }),
            }
        }
    }

    fn make_key_tx(address: &str, key: [u8; 32]) -> NoteTransaction {
        NoteTransaction {
            txid: "TX-KEY".to_string(),
            sender: address.to_string(),
            receiver: address.to_string(),
            note: key.to_vec(),
            confirmed_round: 100,
            round_time: 1700000000,
        }
    }

    fn make_non_key_tx(address: &str, txid: &str) -> NoteTransaction {
        NoteTransaction {
            txid: txid.to_string(),
            sender: address.to_string(),
            receiver: address.to_string(),
            note: vec![1, 2, 3], // Too short for key
            confirmed_round: 100,
            round_time: 1700000000,
        }
    }

    #[tokio::test]
    async fn test_paginated_finds_key_on_first_page() {
        let address = "MYADDR";
        let key = [0xABu8; 32];

        let indexer = MockPaginatedIndexer::new(vec![PaginatedTransactions {
            transactions: vec![make_key_tx(address, key)],
            next_token: None,
        }]);

        let result = discover_encryption_key_paginated(&indexer, address, 50, None)
            .await
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().public_key, key);
        assert_eq!(indexer.call_count(), 1);
    }

    #[tokio::test]
    async fn test_paginated_finds_key_on_second_page() {
        let address = "MYADDR";
        let key = [0xCDu8; 32];

        let indexer = MockPaginatedIndexer::new(vec![
            PaginatedTransactions {
                transactions: vec![make_non_key_tx(address, "TX0")],
                next_token: Some("page2".to_string()),
            },
            PaginatedTransactions {
                transactions: vec![make_key_tx(address, key)],
                next_token: None,
            },
        ]);

        let result = discover_encryption_key_paginated(&indexer, address, 50, None)
            .await
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().public_key, key);
        assert_eq!(indexer.call_count(), 2);
    }

    #[tokio::test]
    async fn test_paginated_max_pages_limits_search() {
        let address = "MYADDR";
        let key = [0xEFu8; 32];

        let indexer = MockPaginatedIndexer::new(vec![
            PaginatedTransactions {
                transactions: vec![make_non_key_tx(address, "TX0")],
                next_token: Some("page2".to_string()),
            },
            PaginatedTransactions {
                transactions: vec![make_key_tx(address, key)],
                next_token: None,
            },
        ]);

        // Only search 1 page — key is on page 2, should NOT find it
        let result = discover_encryption_key_paginated(&indexer, address, 50, Some(1))
            .await
            .unwrap();
        assert!(result.is_none());
        assert_eq!(indexer.call_count(), 1);
    }

    #[tokio::test]
    async fn test_paginated_exhaustive_search_all_pages() {
        let address = "MYADDR";
        let key = [0x42u8; 32];

        let indexer = MockPaginatedIndexer::new(vec![
            PaginatedTransactions {
                transactions: vec![make_non_key_tx(address, "TX0")],
                next_token: Some("p2".to_string()),
            },
            PaginatedTransactions {
                transactions: vec![make_non_key_tx(address, "TX1")],
                next_token: Some("p3".to_string()),
            },
            PaginatedTransactions {
                transactions: vec![make_non_key_tx(address, "TX2")],
                next_token: Some("p4".to_string()),
            },
            PaginatedTransactions {
                transactions: vec![make_key_tx(address, key)],
                next_token: None,
            },
        ]);

        let result = discover_encryption_key_paginated(&indexer, address, 50, None)
            .await
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().public_key, key);
        assert_eq!(indexer.call_count(), 4);
    }

    #[tokio::test]
    async fn test_paginated_empty_history_returns_none() {
        let indexer = MockPaginatedIndexer::new(vec![PaginatedTransactions {
            transactions: Vec::new(),
            next_token: None,
        }]);

        let result = discover_encryption_key_paginated(&indexer, "NOONE", 50, None)
            .await
            .unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_paginated_page_size_forwarded() {
        let indexer = MockPaginatedIndexer::new(vec![PaginatedTransactions {
            transactions: Vec::new(),
            next_token: None,
        }]);

        let _ = discover_encryption_key_paginated(&indexer, "ADDR", 25, None).await;
        assert_eq!(indexer.last_limit(), Some(25));
    }

    #[tokio::test]
    async fn test_paginated_skips_other_senders() {
        let target = "TARGET";
        let key = [0xBBu8; 32];

        // First tx is from a different sender, second is from target
        let other_tx = NoteTransaction {
            txid: "TX0".to_string(),
            sender: "OTHER".to_string(),
            receiver: "OTHER".to_string(),
            note: vec![0xFFu8; 32],
            confirmed_round: 100,
            round_time: 1700000000,
        };

        let indexer = MockPaginatedIndexer::new(vec![PaginatedTransactions {
            transactions: vec![other_tx, make_key_tx(target, key)],
            next_token: None,
        }]);

        let result = discover_encryption_key_paginated(&indexer, target, 50, None)
            .await
            .unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().public_key, key);
    }

    #[test]
    fn test_default_discovery_page_size() {
        assert_eq!(DEFAULT_DISCOVERY_PAGE_SIZE, 100);
    }

    #[test]
    fn test_paginated_transactions_debug() {
        let pt = PaginatedTransactions {
            transactions: Vec::new(),
            next_token: Some("token123".to_string()),
        };
        let debug = format!("{:?}", pt);
        assert!(debug.contains("token123"));
    }
}