forest-filecoin 0.33.2

Rust Filecoin implementation.
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
// Copyright 2019-2026 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

// Contains the implementation of Message Pool component.
// The Message Pool is the component of forest that handles pending messages for
// inclusion in the chain. Messages are added either directly for locally
// published messages or through pubsub propagation.

use std::{num::NonZeroUsize, sync::Arc, time::Duration};

use crate::blocks::{CachingBlockHeader, Tipset, TipsetKey};
use crate::chain::{HeadChanges, MINIMUM_BASE_FEE};
#[cfg(test)]
use crate::db::SettingsStore;
use crate::eth::is_valid_eth_tx_for_sending;
use crate::libp2p::{NetworkMessage, PUBSUB_MSG_STR, Topic};
use crate::message::{ChainMessage, MessageRead as _, SignedMessage, valid_for_block_inclusion};
use crate::networks::{ChainConfig, NEWEST_NETWORK_VERSION};
use crate::rpc::eth::types::EthAddress;
use crate::shim::{
    address::{Address, Protocol},
    crypto::{Signature, SignatureType},
    econ::TokenAmount,
    gas::{Gas, price_list_by_network_version},
};
use crate::state_manager::IdToAddressCache;
use crate::state_manager::utils::is_valid_for_sending;
use crate::utils::ShallowClone as _;
use crate::utils::cache::SizeTrackingLruCache;
use crate::utils::get_size::CidWrapper;
use ahash::{HashMap, HashMapExt, HashSet, HashSetExt};
use anyhow::Context as _;
use cid::Cid;
use futures::StreamExt;
use fvm_ipld_encoding::to_vec;
use get_size2::GetSize;
use itertools::Itertools;
use nonzero_ext::nonzero;
use parking_lot::RwLock as SyncRwLock;
use tokio::{sync::broadcast::error::RecvError, task::JoinSet, time::interval};
use tracing::warn;

use crate::message_pool::{
    config::MpoolConfig,
    errors::Error,
    head_change, metrics,
    msgpool::{
        BASE_FEE_LOWER_BOUND_FACTOR_CONSERVATIVE, RBF_DENOM, RBF_NUM, recover_sig,
        republish_pending_messages,
    },
    provider::Provider,
    utils::get_base_fee_lower_bound,
};

// LruCache sizes have been taken from the lotus implementation
const BLS_SIG_CACHE_SIZE: NonZeroUsize = nonzero!(40000usize);
const SIG_VAL_CACHE_SIZE: NonZeroUsize = nonzero!(32000usize);
const KEY_CACHE_SIZE: NonZeroUsize = nonzero!(1_048_576usize);
const STATE_NONCE_CACHE_SIZE: NonZeroUsize = nonzero!(32768usize);

#[derive(Clone, Debug, Hash, PartialEq, Eq, GetSize)]
pub(crate) struct StateNonceCacheKey {
    tipset_key: TipsetKey,
    addr: Address,
}

pub const MAX_ACTOR_PENDING_MESSAGES: u64 = 1000;
pub const MAX_UNTRUSTED_ACTOR_PENDING_MESSAGES: u64 = 10;
const MAX_NONCE_GAP: u64 = 4;
/// Maximum size of a serialized message in bytes. This is an anti-DOS measure to prevent
/// large messages from being added to the message pool.
const MAX_MESSAGE_SIZE: usize = 64 << 10; // 64 KiB

/// Trust policy for whether a message is from a trusted or untrusted source.
/// Untrusted sources are subject to stricter limits.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TrustPolicy {
    Trusted,
    Untrusted,
}

/// Strictness policy for pending insertion enforces nonce-gap and replace-by-fee-during-gap rules.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StrictnessPolicy {
    Strict,
    Relaxed,
}

/// Simple structure that contains a hash-map of messages where k: a message
/// from address, v: a message which corresponds to that address.
#[derive(Clone, Default, Debug)]
pub struct MsgSet {
    pub(in crate::message_pool) msgs: HashMap<u64, SignedMessage>,
    next_sequence: u64,
}

impl MsgSet {
    /// Generate a new `MsgSet` with an empty hash-map and setting the sequence
    /// specifically.
    pub fn new(sequence: u64) -> Self {
        MsgSet {
            msgs: HashMap::new(),
            next_sequence: sequence,
        }
    }

    /// Add a signed message to the `MsgSet`. Increase `next_sequence` if the
    /// message has a sequence greater than any existing message sequence.
    /// Use this method when pushing a message coming from trusted sources.
    pub fn add_trusted<T>(
        &mut self,
        api: &T,
        m: SignedMessage,
        strictness: StrictnessPolicy,
    ) -> Result<(), Error>
    where
        T: Provider,
    {
        self.add(api, m, strictness, true)
    }

    /// Add a signed message to the `MsgSet`. Increase `next_sequence` if the
    /// message has a sequence greater than any existing message sequence.
    /// Use this method when pushing a message coming from untrusted sources.
    pub fn add_untrusted<T>(
        &mut self,
        api: &T,
        m: SignedMessage,
        strictness: StrictnessPolicy,
    ) -> Result<(), Error>
    where
        T: Provider,
    {
        self.add(api, m, strictness, false)
    }

    /// Insert a message into this set, maintaining `next_sequence`.
    ///
    /// - If the message nonce equals `next_sequence`, advance past any
    ///   consecutive existing messages (gap-filling loop).
    /// - If the nonce exceeds `next_sequence + max_nonce_gap` and [`StrictnessPolicy::Strict`],
    ///   reject with [`Error::NonceGap`].
    /// - Replace-by-fee for an existing nonce is rejected when strict and
    ///   a nonce gap is present.
    ///
    /// [`StrictnessPolicy`] and `trusted` are independent: strictness controls whether
    /// nonce gap checks run, while `trusted` sets `max_nonce_gap` [`MAX_NONCE_GAP`]
    /// and the per-actor pending message limit.
    pub(in crate::message_pool) fn add<T>(
        &mut self,
        api: &T,
        m: SignedMessage,
        strictness: StrictnessPolicy,
        trusted: bool,
    ) -> Result<(), Error>
    where
        T: Provider,
    {
        let strict = matches!(strictness, StrictnessPolicy::Strict);
        let max_nonce_gap: u64 = if trusted { MAX_NONCE_GAP } else { 0 };
        let max_actor_pending_messages = if trusted {
            api.max_actor_pending_messages()
        } else {
            api.max_untrusted_actor_pending_messages()
        };

        let mut next_nonce = self.next_sequence;
        let nonce_gap = if m.sequence() == next_nonce {
            next_nonce += 1;
            while self.msgs.contains_key(&next_nonce) {
                next_nonce += 1;
            }
            false
        } else if strict && m.sequence() > next_nonce + max_nonce_gap {
            tracing::debug!(
                nonce = m.sequence(),
                next_nonce,
                "message nonce has too big a gap from expected nonce"
            );
            return Err(Error::NonceGap);
        } else {
            m.sequence() > next_nonce
        };

        let has_existing = if let Some(exms) = self.msgs.get(&m.sequence()) {
            if strict && nonce_gap {
                tracing::debug!(
                    nonce = m.sequence(),
                    next_nonce,
                    "rejecting replace by fee because of nonce gap"
                );
                return Err(Error::NonceGap);
            }
            if m.cid() != exms.cid() {
                let premium = &exms.message().gas_premium;
                let min_price = premium.clone()
                    + ((premium * RBF_NUM).div_floor(RBF_DENOM))
                    + TokenAmount::from_atto(1u8);
                if m.message().gas_premium <= min_price {
                    return Err(Error::GasPriceTooLow);
                }
            } else {
                return Err(Error::DuplicateSequence);
            }
            true
        } else {
            false
        };

        // Only check the limit when adding a new message, not when replacing an existing one (RBF)
        if !has_existing && self.msgs.len() as u64 >= max_actor_pending_messages {
            return Err(Error::TooManyPendingMessages(
                m.message.from().to_string(),
                trusted,
            ));
        }

        if strict && nonce_gap {
            tracing::debug!(
                from = %m.from(),
                nonce = m.sequence(),
                next_nonce,
                "adding nonce-gapped message"
            );
        }

        self.next_sequence = next_nonce;
        if self.msgs.insert(m.sequence(), m).is_none() {
            metrics::MPOOL_MESSAGE_TOTAL.inc();
        }
        Ok(())
    }

    /// Remove the message at `sequence` and adjust `next_sequence`.
    ///
    /// - **Applied** (included on-chain): advance `next_sequence` to
    ///   `sequence + 1` if needed. For messages not in our pool, also run
    ///   the gap-filling loop to advance past consecutive known messages.
    /// - **Pruned** (evicted): rewind `next_sequence` to `sequence` if the
    ///   removal creates a gap.
    pub fn rm(&mut self, sequence: u64, applied: bool) {
        if self.msgs.remove(&sequence).is_none() {
            if applied && sequence >= self.next_sequence {
                self.next_sequence = sequence + 1;
                while self.msgs.contains_key(&self.next_sequence) {
                    self.next_sequence += 1;
                }
            }
            return;
        }
        metrics::MPOOL_MESSAGE_TOTAL.dec();

        // adjust next sequence
        if applied {
            // we removed a (known) message because it was applied in a tipset
            // we can't possibly have filled a gap in this case
            if sequence >= self.next_sequence {
                self.next_sequence = sequence + 1;
            }
            return;
        }
        // we removed a message because it was pruned
        // we have to adjust the sequence if it creates a gap or rewinds state
        if sequence < self.next_sequence {
            self.next_sequence = sequence;
        }
    }
}

/// This contains all necessary information needed for the message pool.
/// Keeps track of messages to apply, as well as context needed for verifying
/// transactions.
pub struct MessagePool<T> {
    /// The local address of the client
    local_addrs: Arc<SyncRwLock<Vec<Address>>>,
    /// A map of pending messages where the key is the resolved key address
    pub pending: Arc<SyncRwLock<HashMap<Address, MsgSet>>>,
    /// The current tipset (a set of blocks)
    pub cur_tipset: Arc<SyncRwLock<Tipset>>,
    /// The underlying provider
    pub api: Arc<T>,
    /// Sender half to send messages to other components
    pub network_sender: flume::Sender<NetworkMessage>,
    /// A cache for BLS signature keyed by Cid
    pub bls_sig_cache: SizeTrackingLruCache<CidWrapper, Signature>,
    /// A cache for BLS signature keyed by Cid
    pub sig_val_cache: SizeTrackingLruCache<CidWrapper, ()>,
    /// Cache for ID address ID to key address resolution.
    pub key_cache: IdToAddressCache,
    /// Cache for state nonce lookups keyed by (`TipsetKey`, `Address`).
    pub state_nonce_cache: SizeTrackingLruCache<StateNonceCacheKey, u64>,
    /// A set of republished messages identified by their Cid
    pub republished: Arc<SyncRwLock<HashSet<Cid>>>,
    /// Acts as a signal to republish messages from the republished set of
    /// messages
    pub repub_trigger: flume::Sender<()>,
    local_msgs: Arc<SyncRwLock<HashSet<SignedMessage>>>,
    /// Configurable parameters of the message pool
    pub config: MpoolConfig,
    /// Chain configuration
    pub chain_config: Arc<ChainConfig>,
}

/// Resolve an address to its key form, checking the cache first.
/// Non-ID addresses are returned unchanged.
pub(in crate::message_pool) fn resolve_to_key<T: Provider>(
    api: &T,
    key_cache: &IdToAddressCache,
    addr: &Address,
    cur_ts: &Tipset,
) -> Result<Address, Error> {
    let id = addr.id().ok();
    if let Some(id) = &id
        && let Some(resolved) = key_cache.get_cloned(id)
    {
        return Ok(resolved);
    }
    let resolved = api.resolve_to_deterministic_address_at_finality(addr, cur_ts)?;
    if let Some(id) = id {
        key_cache.push(id, resolved);
    }
    Ok(resolved)
}

/// Get the state nonce for an address, accounting for messages already included in `cur_ts`.
pub(in crate::message_pool) fn get_state_sequence<T: Provider>(
    api: &T,
    key_cache: &IdToAddressCache,
    state_nonce_cache: &SizeTrackingLruCache<StateNonceCacheKey, u64>,
    addr: &Address,
    cur_ts: &Tipset,
) -> Result<u64, Error> {
    let nk = StateNonceCacheKey {
        tipset_key: cur_ts.key().clone(),
        addr: *addr,
    };

    if let Some(cached) = state_nonce_cache.get_cloned(&nk) {
        return Ok(cached);
    }

    let actor = api.get_actor_after(addr, cur_ts)?;
    let mut next_nonce = actor.sequence;

    if let (Ok(resolved), Ok(messages)) = (
        resolve_to_key(api, key_cache, addr, cur_ts)
            .inspect_err(|e| tracing::warn!(%addr, "failed to resolve address to key: {e:#}")),
        api.messages_for_tipset(cur_ts)
            .inspect_err(|e| tracing::warn!("failed to get messages for tipset: {e:#}")),
    ) {
        for msg in messages.iter() {
            if let Ok(from) = resolve_to_key(api, key_cache, &msg.from(), cur_ts).inspect_err(
                |e| tracing::warn!(from = %msg.from(), "failed to resolve message sender: {e:#}"),
            ) && from == resolved
            {
                let n = msg.sequence() + 1;
                if n > next_nonce {
                    next_nonce = n;
                }
            }
        }
    }

    state_nonce_cache.push(nk, next_nonce);
    Ok(next_nonce)
}

impl<T> MessagePool<T>
where
    T: Provider,
{
    /// Gets the current tipset
    pub fn current_tipset(&self) -> Tipset {
        self.cur_tipset.read().clone()
    }

    pub fn resolve_to_key(&self, addr: &Address, cur_ts: &Tipset) -> Result<Address, Error> {
        resolve_to_key(self.api.as_ref(), &self.key_cache, addr, cur_ts)
    }

    /// Add a signed message to the pool and its address.
    fn add_local(&self, m: SignedMessage) -> Result<(), Error> {
        let cur_ts = self.current_tipset();
        let resolved = self.resolve_to_key(&m.from(), &cur_ts)?;
        self.local_addrs.write().push(resolved);
        self.local_msgs.write().insert(m);
        Ok(())
    }

    /// Push a signed message to the `MessagePool`. Additionally performs basic
    /// checks on the validity of a message.
    pub async fn push_internal(
        &self,
        msg: SignedMessage,
        trust_policy: TrustPolicy,
    ) -> Result<Cid, Error> {
        self.check_message(&msg)?;
        let cid = msg.cid();
        let cur_ts = self.current_tipset();
        let publish = self.add_tipset(msg.clone(), &cur_ts, true, trust_policy)?;
        let msg_ser = to_vec(&msg)?;
        let network_name = self.chain_config.network.genesis_name();
        self.add_local(msg)?;
        if publish {
            self.network_sender
                .send_async(NetworkMessage::PubsubMessage {
                    topic: Topic::new(format!("{PUBSUB_MSG_STR}/{network_name}")),
                    message: msg_ser,
                })
                .await
                .map_err(|_| Error::Other("Network receiver dropped".to_string()))?;
        }
        Ok(cid)
    }

    /// Push a signed message to the `MessagePool` from an trusted source.
    pub async fn push(&self, msg: SignedMessage) -> Result<Cid, Error> {
        self.push_internal(msg, TrustPolicy::Trusted).await
    }

    /// Push a signed message to the `MessagePool` from an untrusted source.
    pub async fn push_untrusted(&self, msg: SignedMessage) -> Result<Cid, Error> {
        self.push_internal(msg, TrustPolicy::Untrusted).await
    }

    fn check_message(&self, msg: &SignedMessage) -> Result<(), Error> {
        if to_vec(msg)?.len() > MAX_MESSAGE_SIZE {
            return Err(Error::MessageTooBig);
        }
        let to = msg.message().to();
        if to.protocol() == Protocol::Delegated {
            EthAddress::from_filecoin_address(&to).context(format!(
                "message recipient {to} is a delegated address but not a valid Eth Address"
            ))?;
        }
        valid_for_block_inclusion(msg.message(), Gas::new(0), NEWEST_NETWORK_VERSION)?;
        if msg.value() > *crate::shim::econ::TOTAL_FILECOIN {
            return Err(Error::MessageValueTooHigh);
        }
        if msg.gas_fee_cap().atto() < &MINIMUM_BASE_FEE.into() {
            return Err(Error::GasFeeCapTooLow);
        }
        self.verify_msg_sig(msg)
    }

    /// This is a helper to push that will help to make sure that the message
    /// fits the parameters to be pushed to the `MessagePool`.
    pub fn add(&self, msg: SignedMessage) -> Result<(), Error> {
        self.check_message(&msg)?;
        let ts = self.current_tipset();
        self.add_tipset(msg, &ts, false, TrustPolicy::Trusted)?;
        Ok(())
    }

    /// Verify the message signature. first check if it has already been
    /// verified and put into cache. If it has not, then manually verify it
    /// then put it into cache for future use.
    fn verify_msg_sig(&self, msg: &SignedMessage) -> Result<(), Error> {
        let cid = msg.cid();

        if let Some(()) = self.sig_val_cache.get_cloned(&(cid).into()) {
            return Ok(());
        }

        msg.verify(self.chain_config.eth_chain_id)
            .map_err(|e| Error::Other(e.to_string()))?;

        self.sig_val_cache.push(cid.into(), ());

        Ok(())
    }

    /// Verify the `state_sequence` and balance for the sender of the message
    /// given then call `add_locked` to finish adding the `signed_message`
    /// to pending.
    fn add_tipset(
        &self,
        msg: SignedMessage,
        cur_ts: &Tipset,
        local: bool,
        trust_policy: TrustPolicy,
    ) -> Result<bool, Error> {
        let sequence = self.get_state_sequence(&msg.from(), cur_ts)?;

        if sequence > msg.message().sequence {
            return Err(Error::SequenceTooLow);
        }

        let sender_actor = self.api.get_actor_after(&msg.message().from(), cur_ts)?;

        // This message can only be included in the next epoch and beyond, hence the +1.
        let nv = self.chain_config.network_version(cur_ts.epoch() + 1);
        let eth_chain_id = self.chain_config.eth_chain_id;
        if msg.signature().signature_type() == SignatureType::Delegated
            && !is_valid_eth_tx_for_sending(eth_chain_id, nv, &msg)
        {
            return Err(Error::Other(
                "Invalid Ethereum message for the current network version".to_owned(),
            ));
        }
        if !is_valid_for_sending(nv, &sender_actor) {
            return Err(Error::Other(
                "Sender actor is not a valid top-level sender".to_owned(),
            ));
        }

        let publish = verify_msg_before_add(&msg, cur_ts, local, &self.chain_config)?;

        let balance = self.get_state_balance(&msg.from(), cur_ts)?;

        let msg_balance = msg.required_funds();
        if balance < msg_balance {
            return Err(Error::NotEnoughFunds);
        }
        let strictness = if local {
            StrictnessPolicy::Relaxed
        } else {
            StrictnessPolicy::Strict
        };
        self.add_helper(msg, trust_policy, strictness)?;
        Ok(publish)
    }

    /// Finish verifying signed message before adding it to the pending `mset`
    /// hash-map. If an entry in the hash-map does not yet exist, create a
    /// new `mset` that will correspond to the from message and push it to
    /// the pending hash-map.
    fn add_helper(
        &self,
        msg: SignedMessage,
        trust_policy: TrustPolicy,
        strictness: StrictnessPolicy,
    ) -> Result<(), Error> {
        let from = msg.from();
        let cur_ts = self.current_tipset();
        add_helper(
            self.api.as_ref(),
            &self.bls_sig_cache,
            self.pending.as_ref(),
            &self.key_cache,
            &cur_ts,
            msg,
            self.get_state_sequence(&from, &cur_ts)?,
            trust_policy,
            strictness,
        )
    }

    /// Get the sequence for a given address, return Error if there is a failure
    /// to retrieve the respective sequence.
    pub fn get_sequence(&self, addr: &Address) -> Result<u64, Error> {
        let cur_ts = self.current_tipset();

        let sequence = self.get_state_sequence(addr, &cur_ts)?;

        let pending = self.pending.read();
        let msgset = self
            .resolve_to_key(addr, &cur_ts)
            .ok()
            .and_then(|resolved| pending.get(&resolved))
            .or_else(|| pending.get(addr));
        match msgset {
            Some(mset) => {
                if sequence > mset.next_sequence {
                    return Ok(sequence);
                }
                Ok(mset.next_sequence)
            }
            None => Ok(sequence),
        }
    }

    /// Get the state of the sequence for a given address in `cur_ts`.
    fn get_state_sequence(&self, addr: &Address, cur_ts: &Tipset) -> Result<u64, Error> {
        get_state_sequence(
            self.api.as_ref(),
            &self.key_cache,
            &self.state_nonce_cache,
            addr,
            cur_ts,
        )
    }

    /// Get the state balance for the actor that corresponds to the supplied
    /// address and tipset, if this actor does not exist, return an error.
    fn get_state_balance(&self, addr: &Address, ts: &Tipset) -> Result<TokenAmount, Error> {
        let actor = self.api.get_actor_after(addr, ts)?;
        Ok(TokenAmount::from(&actor.balance))
    }

    /// Return a tuple that contains a vector of all signed messages and the
    /// current tipset for self.
    pub fn pending(&self) -> (Vec<SignedMessage>, Tipset) {
        let pending = self.pending.read().clone();
        let len = pending.values().map(|mset| mset.msgs.len()).sum();
        let mut out = Vec::with_capacity(len);

        for mset in pending.into_values() {
            out.extend(
                mset.msgs
                    .into_values()
                    .sorted_unstable_by_key(|m| m.message().sequence),
            );
        }

        let cur_ts = self.current_tipset();

        (out, cur_ts)
    }

    /// Return a Vector of signed messages for a given from address. This vector
    /// will be sorted by each `message`'s sequence. If no corresponding
    /// messages found, return None result type.
    pub fn pending_for(&self, a: &Address) -> Option<Vec<SignedMessage>> {
        let cur_ts = self.current_tipset();
        let resolved = self
            .resolve_to_key(a, &cur_ts)
            .inspect_err(|e| tracing::debug!(%a, "pending_for: failed to resolve address: {e:#}"))
            .ok()?;
        let pending = self.pending.read();
        let mset = pending.get(&resolved)?;
        if mset.msgs.is_empty() {
            return None;
        }

        Some(
            mset.msgs
                .values()
                .cloned()
                .sorted_by_key(|v| v.message().sequence)
                .collect(),
        )
    }

    /// Return Vector of signed messages given a block header for self.
    pub fn messages_for_blocks<'a>(
        &self,
        blks: impl Iterator<Item = &'a CachingBlockHeader>,
    ) -> Result<Vec<SignedMessage>, Error> {
        let mut msg_vec: Vec<SignedMessage> = Vec::new();

        for block in blks {
            let (umsg, mut smsgs) = self.api.messages_for_block(block)?;

            msg_vec.append(smsgs.as_mut());
            for msg in umsg {
                let smsg = recover_sig(&self.bls_sig_cache, msg)?;
                msg_vec.push(smsg)
            }
        }
        Ok(msg_vec)
    }

    /// Loads local messages to the message pool to be applied.
    pub fn load_local(&mut self) -> Result<(), Error> {
        let mut local_msgs = self.local_msgs.write();
        for k in local_msgs.iter().cloned().collect_vec() {
            self.add(k.clone()).unwrap_or_else(|err| {
                if err == Error::SequenceTooLow {
                    warn!("error adding message: {:?}", err);
                    local_msgs.remove(&k);
                }
            })
        }

        Ok(())
    }

    #[cfg(test)]
    pub fn get_config(&self) -> &MpoolConfig {
        &self.config
    }

    #[cfg(test)]
    pub fn set_config<DB: SettingsStore>(
        &mut self,
        db: &DB,
        cfg: MpoolConfig,
    ) -> Result<(), Error> {
        cfg.save_config(db)
            .map_err(|e| Error::Other(e.to_string()))?;
        self.config = cfg;
        Ok(())
    }

    #[cfg(test)]
    pub async fn apply_head_change(
        &self,
        revert: Vec<crate::blocks::Tipset>,
        apply: Vec<crate::blocks::Tipset>,
    ) -> Result<(), Error>
    where
        T: 'static,
    {
        head_change(
            self.api.as_ref(),
            &self.bls_sig_cache,
            self.repub_trigger.clone(),
            self.republished.as_ref(),
            self.pending.as_ref(),
            self.cur_tipset.as_ref(),
            &self.key_cache,
            &self.state_nonce_cache,
            revert,
            apply,
        )
        .await
    }
}

impl<T> MessagePool<T>
where
    T: Provider + Send + Sync + 'static,
{
    /// Creates a new `MessagePool` instance.
    pub fn new(
        api: T,
        network_sender: flume::Sender<NetworkMessage>,
        config: MpoolConfig,
        chain_config: Arc<ChainConfig>,
        services: &mut JoinSet<anyhow::Result<()>>,
    ) -> Result<MessagePool<T>, Error>
    where
        T: Provider,
    {
        let local_addrs = Arc::new(SyncRwLock::new(Vec::new()));
        let pending = Arc::new(SyncRwLock::new(HashMap::new()));
        let tipset = Arc::new(SyncRwLock::new(api.get_heaviest_tipset()));
        let bls_sig_cache =
            SizeTrackingLruCache::new_with_metrics("bls_sig".into(), BLS_SIG_CACHE_SIZE);
        let sig_val_cache =
            SizeTrackingLruCache::new_with_metrics("sig_val".into(), SIG_VAL_CACHE_SIZE);
        let key_cache = SizeTrackingLruCache::new_with_metrics("mpool_key".into(), KEY_CACHE_SIZE);
        let state_nonce_cache =
            SizeTrackingLruCache::new_with_metrics("state_nonce".into(), STATE_NONCE_CACHE_SIZE);
        let local_msgs = Arc::new(SyncRwLock::new(HashSet::new()));
        let republished = Arc::new(SyncRwLock::new(HashSet::new()));
        let block_delay = chain_config.block_delay_secs;

        let (repub_trigger, repub_trigger_rx) = flume::bounded::<()>(4);
        let mut mp = MessagePool {
            local_addrs,
            pending,
            cur_tipset: tipset,
            api: Arc::new(api),
            bls_sig_cache,
            sig_val_cache,
            key_cache,
            state_nonce_cache,
            local_msgs,
            republished,
            config,
            network_sender,
            repub_trigger,
            chain_config: Arc::clone(&chain_config),
        };

        mp.load_local()?;

        let mut head_changes_rx = mp.api.subscribe_head_changes();

        let api = mp.api.clone();
        let bls_sig_cache = mp.bls_sig_cache.shallow_clone();
        let pending = mp.pending.clone();
        let republished = mp.republished.clone();
        let key_cache = mp.key_cache.shallow_clone();
        let state_nonce_cache = mp.state_nonce_cache.shallow_clone();

        let current_ts = mp.cur_tipset.clone();
        let repub_trigger = mp.repub_trigger.clone();

        // Reacts to new HeadChanges
        services.spawn(async move {
            loop {
                match head_changes_rx.recv().await {
                    Ok(HeadChanges { reverts, applies }) => {
                        if let Err(e) = head_change(
                            api.as_ref(),
                            &bls_sig_cache,
                            repub_trigger.clone(),
                            republished.as_ref(),
                            pending.as_ref(),
                            &current_ts,
                            &key_cache,
                            &state_nonce_cache,
                            reverts,
                            applies,
                        )
                        .await
                        {
                            tracing::warn!("Error changing head: {e}");
                        }
                    }
                    Err(RecvError::Lagged(e)) => {
                        warn!("Head change subscriber lagged: skipping {e} events");
                    }
                    Err(RecvError::Closed) => {
                        break Ok(());
                    }
                }
            }
        });

        let api = mp.api.clone();
        let pending = mp.pending.clone();
        let cur_tipset = mp.cur_tipset.clone();
        let republished = mp.republished.clone();
        let local_addrs = mp.local_addrs.clone();
        let key_cache = mp.key_cache.shallow_clone();
        let network_sender = Arc::new(mp.network_sender.clone());
        let republish_interval = u64::from(10 * block_delay + chain_config.propagation_delay_secs);
        // Reacts to republishing requests
        services.spawn(async move {
            let mut repub_trigger_rx = repub_trigger_rx.stream();
            let mut interval = interval(Duration::from_secs(republish_interval));
            loop {
                tokio::select! {
                    _ = interval.tick() => (),
                    _ = repub_trigger_rx.next() => (),
                }
                if let Err(e) = republish_pending_messages(
                    api.as_ref(),
                    network_sender.as_ref(),
                    pending.as_ref(),
                    cur_tipset.as_ref(),
                    republished.as_ref(),
                    local_addrs.as_ref(),
                    &key_cache,
                    &chain_config,
                )
                .await
                {
                    warn!("Failed to republish pending messages: {}", e.to_string());
                }
            }
        });
        Ok(mp)
    }
}

// Helpers for MessagePool

/// Finish verifying signed message before adding it to the pending `mset`
/// hash-map. If an entry in the hash-map does not yet exist, create a new
/// `mset` that will correspond to the from message and push it to the pending
/// hash-map.
#[allow(clippy::too_many_arguments)]
pub(in crate::message_pool) fn add_helper<T>(
    api: &T,
    bls_sig_cache: &SizeTrackingLruCache<CidWrapper, Signature>,
    pending: &SyncRwLock<HashMap<Address, MsgSet>>,
    key_cache: &IdToAddressCache,
    cur_ts: &Tipset,
    msg: SignedMessage,
    sequence: u64,
    trust_policy: TrustPolicy,
    strictness: StrictnessPolicy,
) -> Result<(), Error>
where
    T: Provider,
{
    if msg.signature().signature_type() == SignatureType::Bls {
        bls_sig_cache.push(msg.cid().into(), msg.signature().clone());
    }

    api.put_message(&ChainMessage::Signed(msg.clone().into()))?;
    api.put_message(&ChainMessage::Unsigned(msg.message().clone().into()))?;

    let resolved_from = resolve_to_key(api, key_cache, &msg.from(), cur_ts)?;
    let mut pending = pending.write();
    let mset = pending
        .entry(resolved_from)
        .or_insert_with(|| MsgSet::new(sequence));
    match trust_policy {
        TrustPolicy::Trusted => mset.add_trusted(api, msg, strictness)?,
        TrustPolicy::Untrusted => mset.add_untrusted(api, msg, strictness)?,
    }

    Ok(())
}

fn verify_msg_before_add(
    m: &SignedMessage,
    cur_ts: &Tipset,
    local: bool,
    chain_config: &ChainConfig,
) -> Result<bool, Error> {
    let epoch = cur_ts.epoch();
    let min_gas = price_list_by_network_version(chain_config.network_version(epoch))
        .on_chain_message(m.chain_length()?);
    valid_for_block_inclusion(m.message(), min_gas.total(), NEWEST_NETWORK_VERSION)?;
    if !cur_ts.block_headers().is_empty() {
        let base_fee = &cur_ts.block_headers().first().parent_base_fee;
        let base_fee_lower_bound =
            get_base_fee_lower_bound(base_fee, BASE_FEE_LOWER_BOUND_FACTOR_CONSERVATIVE);
        if m.gas_fee_cap() < base_fee_lower_bound {
            if local {
                warn!(
                    "local message will not be immediately published because GasFeeCap doesn't meet the lower bound for inclusion in the next 20 blocks (GasFeeCap: {}, baseFeeLowerBound: {})",
                    m.gas_fee_cap(),
                    base_fee_lower_bound
                );
                return Ok(false);
            }
            return Err(Error::SoftValidationFailure(format!(
                "GasFeeCap doesn't meet base fee lower bound for inclusion in the next 20 blocks (GasFeeCap: {}, baseFeeLowerBound:{})",
                m.gas_fee_cap(),
                base_fee_lower_bound
            )));
        }
    }
    Ok(local)
}

/// Remove a message from pending given the from address and sequence.
/// The `from` address should already be resolved to its key form.
pub fn remove(
    from: &Address,
    pending: &SyncRwLock<HashMap<Address, MsgSet>>,
    sequence: u64,
    applied: bool,
) -> Result<(), Error> {
    let mut pending = pending.write();
    let mset = if let Some(mset) = pending.get_mut(from) {
        mset
    } else {
        return Ok(());
    };

    mset.rm(sequence, applied);

    if mset.msgs.is_empty() {
        pending.remove(from);
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::blocks::RawBlockHeader;
    use crate::chain::ChainStore;
    use crate::db::MemoryDB;
    use crate::message_pool::provider::Provider;
    use crate::message_pool::test_provider::TestApi;
    use crate::networks::ChainConfig;
    use crate::shim::econ::TokenAmount;
    use crate::shim::state_tree::{ActorState, StateTree, StateTreeVersion};
    use crate::utils::db::CborStoreExt as _;

    use super::*;
    use crate::shim::message::Message as ShimMessage;

    fn make_smsg(from: Address, seq: u64, premium: u64) -> SignedMessage {
        SignedMessage::mock_bls_signed_message(ShimMessage {
            from,
            sequence: seq,
            gas_premium: TokenAmount::from_atto(premium),
            gas_limit: 1_000_000,
            ..ShimMessage::default()
        })
    }

    // Regression test for https://github.com/ChainSafe/forest/pull/6118 which fixed a bogus 100M
    // gas limit. There are no limits on a single message.
    #[test]
    fn add_helper_message_gas_limit_test() {
        let api = TestApi::default();
        let bls_sig_cache = SizeTrackingLruCache::new_mocked();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let pending = SyncRwLock::new(HashMap::new());
        let cur_ts = api.get_heaviest_tipset();
        let message = ShimMessage {
            gas_limit: 666_666_666,
            ..ShimMessage::default()
        };
        let msg = SignedMessage::mock_bls_signed_message(message);
        let sequence = msg.message().sequence;
        let res = add_helper(
            &api,
            &bls_sig_cache,
            &pending,
            &key_cache,
            &cur_ts,
            msg,
            sequence,
            TrustPolicy::Trusted,
            StrictnessPolicy::Relaxed,
        );
        assert!(res.is_ok());
    }

    // Test that RBF (Replace By Fee) is allowed even when at max_actor_pending_messages capacity
    // This matches Lotus behavior where the check is: https://github.com/filecoin-project/lotus/blob/5f32d00550ddd2f2d0f9abe97dbae07615f18547/chain/messagepool/messagepool.go#L296-L299
    #[test]
    fn test_rbf_at_capacity() {
        let api = TestApi::with_max_actor_pending_messages(10);
        let mut mset = MsgSet::new(0);

        // Fill up to capacity (10 messages)
        for i in 0..10 {
            let res = mset.add_trusted(
                &api,
                make_smsg(Address::default(), i, 100),
                StrictnessPolicy::Relaxed,
            );
            assert!(res.is_ok(), "Failed to add message {i}");
        }

        // Should reject adding a NEW message (sequence 10) when at capacity
        let res = mset.add_trusted(
            &api,
            make_smsg(Address::default(), 10, 100),
            StrictnessPolicy::Relaxed,
        );
        assert!(matches!(res, Err(Error::TooManyPendingMessages(_, _))));

        // Should ALLOW replacing an existing message (RBF) even when at capacity
        // Replace message with sequence 5 with higher gas premium
        let res = mset.add_trusted(
            &api,
            make_smsg(Address::default(), 5, 200),
            StrictnessPolicy::Relaxed,
        );
        assert!(res.is_ok(), "RBF should be allowed at capacity");
    }

    #[test]
    fn test_resolve_to_key_returns_non_id_unchanged() {
        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let ts = api.get_heaviest_tipset();

        let bls_addr = Address::new_bls(&[1u8; 48]).unwrap();
        let result = resolve_to_key(&api, &key_cache, &bls_addr, &ts).unwrap();
        assert_eq!(result, bls_addr);
        assert_eq!(
            key_cache.len(),
            0,
            "cache should not be populated for non-ID addresses"
        );
    }

    #[test]
    fn test_resolve_to_key_resolves_id_and_caches() {
        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let ts = api.get_heaviest_tipset();

        let id_addr = Address::new_id(100);
        let key_addr = Address::new_bls(&[5u8; 48]).unwrap();
        api.set_key_address_mapping(&id_addr, &key_addr);

        let result = resolve_to_key(&api, &key_cache, &id_addr, &ts).unwrap();
        assert_eq!(result, key_addr);
        assert_eq!(
            key_cache.len(),
            1,
            "cache should have one entry after resolution"
        );

        // Second call should hit the cache (no API call needed)
        let result2 = resolve_to_key(&api, &key_cache, &id_addr, &ts).unwrap();
        assert_eq!(result2, key_addr);
    }

    #[test]
    fn test_add_helper_keys_pending_by_resolved_address() {
        let api = TestApi::default();
        let bls_sig_cache = SizeTrackingLruCache::new_mocked();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let pending = SyncRwLock::new(HashMap::new());
        let cur_ts = api.get_heaviest_tipset();

        let id_addr = Address::new_id(200);
        let key_addr = Address::new_bls(&[7u8; 48]).unwrap();
        api.set_key_address_mapping(&id_addr, &key_addr);
        api.set_state_sequence(&key_addr, 0);

        let message = ShimMessage {
            from: id_addr,
            gas_limit: 1_000_000,
            ..ShimMessage::default()
        };
        let msg = SignedMessage::mock_bls_signed_message(message);

        add_helper(
            &api,
            &bls_sig_cache,
            &pending,
            &key_cache,
            &cur_ts,
            msg,
            0,
            TrustPolicy::Trusted,
            StrictnessPolicy::Relaxed,
        )
        .unwrap();

        let pending_read = pending.read();
        assert!(
            pending_read.get(&key_addr).is_some(),
            "pending should be keyed by the resolved key address"
        );
        assert!(
            pending_read.get(&id_addr).is_none(),
            "pending should NOT have an entry under the raw ID address"
        );
    }

    #[test]
    fn test_get_sequence_works_with_both_address_forms() {
        let api = TestApi::default();
        let bls_sig_cache = SizeTrackingLruCache::new_mocked();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let pending = SyncRwLock::new(HashMap::new());
        let cur_ts = api.get_heaviest_tipset();

        let id_addr = Address::new_id(300);
        let key_addr = Address::new_bls(&[9u8; 48]).unwrap();
        api.set_key_address_mapping(&id_addr, &key_addr);
        api.set_state_sequence(&key_addr, 0);

        // Add two messages from the ID address
        for seq in 0..2 {
            let message = ShimMessage {
                from: id_addr,
                sequence: seq,
                gas_limit: 1_000_000,
                ..ShimMessage::default()
            };
            let msg = SignedMessage::mock_bls_signed_message(message);
            add_helper(
                &api,
                &bls_sig_cache,
                &pending,
                &key_cache,
                &cur_ts,
                msg,
                0,
                TrustPolicy::Trusted,
                StrictnessPolicy::Relaxed,
            )
            .unwrap();
        }

        let state_seq = api.get_actor_after(&id_addr, &cur_ts).unwrap().sequence;
        let resolved_for_id = resolve_to_key(&api, &key_cache, &id_addr, &cur_ts).unwrap();
        let resolved_for_key = resolve_to_key(&api, &key_cache, &key_addr, &cur_ts).unwrap();
        assert_eq!(resolved_for_id, resolved_for_key);

        let mset = pending.read();
        let next_seq = mset.get(&resolved_for_id).unwrap().next_sequence;
        let expected = std::cmp::max(state_seq, next_seq);
        assert_eq!(expected, 2, "should reflect both pending messages");
    }

    #[test]
    fn test_gap_filling_advances_next_sequence() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        assert_eq!(mset.next_sequence, 1);

        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 2, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        assert_eq!(mset.next_sequence, 1, "gap at 1, so next_sequence stays");

        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 1, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        assert_eq!(
            mset.next_sequence, 3,
            "filling the gap should advance past all consecutive messages"
        );
    }

    #[test]
    fn test_trusted_allows_any_nonce_gap() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        let res = mset.add_trusted(
            &api,
            make_smsg(Address::default(), 10, 100),
            StrictnessPolicy::Relaxed,
        );
        assert!(
            res.is_ok(),
            "trusted adds skip nonce gap enforcement (StrictnessPolicy::Relaxed)"
        );
    }

    #[test]
    fn test_strict_allows_small_nonce_gap() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        // Strict + trusted -> max_nonce_gap=4 (non-local add path)
        mset.add(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Strict,
            true,
        )
        .unwrap();
        let res = mset.add(
            &api,
            make_smsg(Address::default(), 3, 100),
            StrictnessPolicy::Strict,
            true,
        );
        assert!(
            res.is_ok(),
            "strict+trusted: gap of 2 (within MAX_NONCE_GAP=4) should succeed"
        );
    }

    #[test]
    fn test_strict_rejects_large_nonce_gap() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        // Strict + trusted -> max_nonce_gap=4
        mset.add(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Strict,
            true,
        )
        .unwrap();
        let res = mset.add(
            &api,
            make_smsg(Address::default(), 6, 100),
            StrictnessPolicy::Strict,
            true,
        );
        assert_eq!(
            res,
            Err(Error::NonceGap),
            "strict+trusted: gap of 5 (exceeds MAX_NONCE_GAP=4) should be rejected"
        );
    }

    #[test]
    fn test_strict_untrusted_rejects_any_gap() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        // Strict + untrusted -> max_nonce_gap=0
        mset.add(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Strict,
            false,
        )
        .unwrap();
        let res = mset.add(
            &api,
            make_smsg(Address::default(), 2, 100),
            StrictnessPolicy::Strict,
            false,
        );
        assert_eq!(
            res,
            Err(Error::NonceGap),
            "strict+untrusted: any gap (maxNonceGap=0) is rejected"
        );
    }

    #[test]
    fn test_non_strict_untrusted_skips_gap_check() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        // Relaxed + untrusted -> gap check skipped (PushUntrusted path)
        mset.add_untrusted(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        let res = mset.add_untrusted(
            &api,
            make_smsg(Address::default(), 5, 100),
            StrictnessPolicy::Relaxed,
        );
        assert!(
            res.is_ok(),
            "non-strict untrusted (PushUntrusted) skips gap enforcement"
        );
    }

    #[test]
    fn test_strict_rbf_during_gap_rejected() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        // Set up a gap using relaxed trusted (local push path)
        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 2, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();

        // Strict RBF at nonce 2 should be rejected due to gap at nonce 1
        let res = mset.add(
            &api,
            make_smsg(Address::default(), 2, 200),
            StrictnessPolicy::Strict,
            true,
        );
        assert_eq!(
            res,
            Err(Error::NonceGap),
            "strict RBF should be rejected when nonce gap exists"
        );
    }

    #[test]
    fn test_rbf_without_gap_still_works() {
        let api = TestApi::default();
        let mut mset = MsgSet::new(0);

        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 0, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 1, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();
        mset.add_trusted(
            &api,
            make_smsg(Address::default(), 2, 100),
            StrictnessPolicy::Relaxed,
        )
        .unwrap();

        let res = mset.add_trusted(
            &api,
            make_smsg(Address::default(), 1, 200),
            StrictnessPolicy::Relaxed,
        );
        assert!(res.is_ok(), "RBF without a nonce gap should succeed");
    }

    #[test]
    fn test_get_state_sequence_accounts_for_tipset_messages() {
        use crate::message_pool::test_provider::mock_block;

        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let state_nonce_cache = SizeTrackingLruCache::new_mocked();

        let sender = Address::new_bls(&[3u8; 48]).unwrap();
        api.set_state_sequence(&sender, 5);

        let block = mock_block(1, 1);
        api.inner.lock().set_block_messages(
            &block,
            vec![make_smsg(sender, 5, 100), make_smsg(sender, 7, 100)],
        );
        let ts = Tipset::from(block);

        let nonce = get_state_sequence(&api, &key_cache, &state_nonce_cache, &sender, &ts).unwrap();
        assert_eq!(
            nonce, 8,
            "should account for non-consecutive tipset message at nonce 7"
        );
    }

    #[test]
    fn test_get_state_sequence_ignores_other_addresses() {
        use crate::message_pool::test_provider::mock_block;

        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let state_nonce_cache = SizeTrackingLruCache::new_mocked();

        let addr_a = Address::new_bls(&[4u8; 48]).unwrap();
        let addr_b = Address::new_bls(&[5u8; 48]).unwrap();
        api.set_state_sequence(&addr_a, 0);
        api.set_state_sequence(&addr_b, 0);

        let block = mock_block(1, 1);
        api.inner.lock().set_block_messages(
            &block,
            vec![
                make_smsg(addr_b, 0, 100),
                make_smsg(addr_b, 1, 100),
                make_smsg(addr_b, 2, 100),
            ],
        );
        let ts = Tipset::from(block);

        let nonce_a =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &addr_a, &ts).unwrap();
        assert_eq!(
            nonce_a, 0,
            "addr_a nonce should be unaffected by addr_b's messages"
        );

        let nonce_b =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &addr_b, &ts).unwrap();
        assert_eq!(
            nonce_b, 3,
            "addr_b nonce should reflect its tipset messages"
        );
    }

    #[test]
    fn test_get_state_sequence_cache_hit() {
        use crate::message_pool::test_provider::mock_block;

        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let state_nonce_cache: SizeTrackingLruCache<StateNonceCacheKey, u64> =
            SizeTrackingLruCache::new_mocked();

        let sender = Address::new_bls(&[6u8; 48]).unwrap();
        api.set_state_sequence(&sender, 5);

        let block = mock_block(1, 1);
        api.inner
            .lock()
            .set_block_messages(&block, vec![make_smsg(sender, 5, 100)]);
        let ts = Tipset::from(block);

        let nonce1 =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &sender, &ts).unwrap();
        assert_eq!(nonce1, 6);

        // Mutate the underlying state; the cache should still return the old value.
        api.set_state_sequence(&sender, 99);
        let nonce2 =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &sender, &ts).unwrap();
        assert_eq!(
            nonce2, 6,
            "second call should return the cached value, not re-read state"
        );
    }

    #[test]
    fn test_get_state_sequence_cache_miss_on_different_tipset() {
        use crate::message_pool::test_provider::mock_block;

        let api = TestApi::default();
        let key_cache = SizeTrackingLruCache::new_mocked();
        let state_nonce_cache: SizeTrackingLruCache<StateNonceCacheKey, u64> =
            SizeTrackingLruCache::new_mocked();

        let sender = Address::new_bls(&[7u8; 48]).unwrap();
        api.set_state_sequence(&sender, 10);

        let block_a = mock_block(1, 1);
        let ts_a = Tipset::from(&block_a);

        let nonce_a =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &sender, &ts_a).unwrap();
        assert_eq!(nonce_a, 10);

        // Different tipset should be a cache miss and re-read state.
        api.set_state_sequence(&sender, 20);
        let block_b = mock_block(2, 2);
        let ts_b = Tipset::from(&block_b);

        let nonce_b =
            get_state_sequence(&api, &key_cache, &state_nonce_cache, &sender, &ts_b).unwrap();
        assert_eq!(
            nonce_b, 20,
            "different tipset should miss the cache and read fresh state"
        );
    }

    #[test]
    fn resolve_to_key_uses_finality_lookback() {
        let db = Arc::new(MemoryDB::default());

        let mut cfg = ChainConfig::default();
        cfg.policy.chain_finality = 1;
        let cfg = Arc::new(cfg);

        let bls_a = Address::new_bls(&[8u8; 48]).unwrap();
        let bls_b = Address::new_bls(&[9u8; 48]).unwrap();

        // root_a: only contains f0300
        let mut st_a = StateTree::new(db.clone(), StateTreeVersion::V5).unwrap();
        st_a.set_actor(
            &Address::new_id(300),
            ActorState::new_empty(Cid::default(), Some(bls_a)),
        )
        .unwrap();
        let root_a = st_a.flush().unwrap();

        // root_b: only contains f0400
        let mut st_b = StateTree::new(db.clone(), StateTreeVersion::V5).unwrap();
        st_b.set_actor(
            &Address::new_id(400),
            ActorState::new_empty(Cid::default(), Some(bls_b)),
        )
        .unwrap();
        let root_b = st_b.flush().unwrap();

        let genesis = Tipset::from(CachingBlockHeader::new(RawBlockHeader {
            state_root: root_a,
            ..Default::default()
        }));
        db.put_cbor_default(genesis.block_headers().first())
            .unwrap();

        let ts1 = Tipset::from(CachingBlockHeader::new(RawBlockHeader {
            parents: genesis.key().clone(),
            epoch: 1,
            state_root: root_a,
            timestamp: 1,
            ..Default::default()
        }));
        db.put_cbor_default(ts1.block_headers().first()).unwrap();

        let head = Tipset::from(CachingBlockHeader::new(RawBlockHeader {
            parents: ts1.key().clone(),
            epoch: 2,
            state_root: root_b,
            timestamp: 2,
            ..Default::default()
        }));
        db.put_cbor_default(head.block_headers().first()).unwrap();

        let cs = ChainStore::new(
            db.clone(),
            db.clone(),
            db,
            cfg,
            genesis.block_headers().first().clone(),
        )
        .unwrap();

        // f0300 exists in lookback state (root_a) → resolves successfully.
        let result = Provider::resolve_to_deterministic_address_at_finality(
            &cs,
            &Address::new_id(300),
            &head,
        )
        .unwrap();
        assert_eq!(result, bls_a);

        // f0400 exists only in head state (root_b), not in lookback → fails.
        Provider::resolve_to_deterministic_address_at_finality(&cs, &Address::new_id(400), &head)
            .expect_err("actor only in head state must not resolve via finality lookback");
    }
}